Example #1
0
def add_lbr_virtual_server(virtual_server_defn):
    virtual_server_name = virtual_server_defn['name']

    existing_vip_name = ('%s%s' % (virtual_server_defn['name'], 'Vip'))
    existing_virtual_server = check_for_existing_lbr_virtual_server(
        existing_vip_name)

    virtual_server_api_endpoint = LBR_VIRTUAL_SERVER_ENDPOINT
    pool_id = add_lbr_pool(virtual_server_defn)

    # Go with TCP App profile and source-ip persistence profile
    lbFastTcpAppProfile = global_id_map[
        'APP_PROFILE:nsx-default-lb-fast-tcp-profile']
    lbSourceIpPersistenceProfile = global_id_map[
        'PERSISTENCE_PROFILE:nsx-default-source-ip-persistence-profile']

    vs_payload = {
        'resource_type': 'LbVirtualServer',
        'display_name': ('%s%s' % (virtual_server_defn['name'], 'Vip')),
        'max_concurrent_connections': 10000,
        'max_new_connection_rate': 1000,
        'persistence_profile_id': lbSourceIpPersistenceProfile,
        'application_profile_id': lbFastTcpAppProfile,
        'ip_address': virtual_server_defn['vip'],
        'pool_id': pool_id,
        'enabled': True,
        'ip_protocol': 'TCP',
        'port': virtual_server_defn['port'],
        'default_pool_member_port': virtual_server_defn['port']
    }

    if existing_virtual_server is None:
        resp = client.post(virtual_server_api_endpoint, vs_payload).json()

        if resp.get('error_code') is None:
            print 'Created Virtual Server: {}'.format(virtual_server_name)
            print ''
            return resp['id']
        else:
            print 'Problem in creating Virtual Server: {}'.format(
                virtual_server_name)
            print 'Associated Error: {}'.format(resp)
            exit(1)

    # Update existing virtual server
    vs_payload['_revision'] = existing_virtual_server['_revision']
    vs_payload['id'] = existing_virtual_server['id']
    vs_update_api_endpoint = '%s/%s' % (virtual_server_api_endpoint,
                                        existing_virtual_server['id'])

    resp = client.put(vs_update_api_endpoint, vs_payload, check=False)
    if resp.status_code < 400:
        print 'Updated Virtual Server: {}'.format(virtual_server_name)
        print ''
        return existing_virtual_server['id']
    else:
        print 'Problem in updating Virtual Server: {}'.format(
            virtual_server_name)
        print 'Associated Error: {}'.format(resp.json())
        exit(1)
Example #2
0
def add_lbr_pool(virtual_server_defn):
    virtual_server_name = virtual_server_defn['name']

    existing_pool = check_for_existing_lbr_pool(
        '%s%s' % (virtual_server_name, 'ServerPool'))

    pool_api_endpoint = LBR_POOLS_ENDPOINT
    lbActiveTcpMonitor = global_id_map['MONITOR:nsx-default-tcp-monitor']
    lbPassiveMonitor = global_id_map['MONITOR:nsx-default-passive-monitor']

    index = 1
    members = []

    pool_payload = {
        'resource_type': 'LbPool',
        'display_name': ('%s%s' % (virtual_server_name, 'ServerPool')),
        'tcp_multiplexing_number': 6,
        'min_active_members': 1,
        'tcp_multiplexing_enabled': False,
        'passive_monitor_id': lbPassiveMonitor,
        'active_monitor_ids': [lbActiveTcpMonitor],
        'snat_translation': {
            'port_overload': 1,
            'type': 'LbSnatAutoMap'
        },
        'algorithm': 'ROUND_ROBIN'
    }

    for member in virtual_server_defn['members']:
        member_name = ('%s-%s-%d' % (virtual_server_name, 'member', index))
        member = {
            'max_concurrent_connections': 10000,
            'port': member['port'],
            'weight': 1,
            'admin_state': 'ENABLED',
            'ip_address': member['ip'],
            'display_name': member_name,
            'backup_member': False
        }
        members.append(member)
        index += 1
    pool_payload['members'] = members

    print 'Payload for Server Pool: {}'.format(pool_payload)

    if existing_pool is None:
        resp = client.post(pool_api_endpoint, pool_payload).json()
        print 'Created Server Pool: {}'.format(virtual_server_name)
        print ''
        return resp['id']

    # Update existing server pool
    pool_payload['_revision'] = existing_pool['_revision']
    pool_payload['id'] = existing_pool['id']
    pool_update_api_endpoint = '%s/%s' % (pool_api_endpoint,
                                          existing_pool['id'])
    resp = client.put(pool_update_api_endpoint, pool_payload, check=False)
    print 'Updated Server Pool: {}'.format(virtual_server_name)
    print ''
    return existing_pool['id']
Example #3
0
 def updateBatchHelper(cls, endpoint, objs):
     batch_results = riq.put(cls.endpoint() + endpoint,
                             {"objects": [obj.payload() for obj in objs]})
     batch_results['successObjects'] = [
         cls(data=obj) for obj in batch_results['successObjects']
     ]
     for errorObj in batch_results['errorObjects']:
         errorObj['object'] = cls(data=errorObj['object'])
     return batch_results
Example #4
0
def add_t0_route_nat_rules():
    nat_rules_defns = get_rsc_def_if_configured('nsx_t_nat_rules_spec_int',
                                                'nat_rules')
    if not nat_rules_defns:
        return

    t0_router_id = global_id_map['ROUTER:TIER0:' +
                                 nat_rules_defns[0]['t0_router']]
    if t0_router_id is None:
        print('Error!! No T0Router found with name: {}'.format(
            nat_rules_defns[0]['t0_router']))
        exit - 1

    api_endpoint = '%s/%s/%s' % (ROUTERS_ENDPOINT, t0_router_id, 'nat/rules')

    changes_detected = False
    existing_nat_rules = client.get(api_endpoint).json()['results']
    for nat_rule in nat_rules_defns:

        rule_payload = {
            'resource_type': 'NatRule',
            'enabled': True,
            'rule_priority': nat_rule['rule_priority'],
            'translated_network': nat_rule['translated_network']
        }

        if nat_rule['nat_type'] == 'dnat':
            rule_payload['action'] = 'DNAT'
            rule_payload['match_destination_network'] = nat_rule[
                'destination_network']
        else:
            rule_payload['action'] = 'SNAT'
            rule_payload['match_source_network'] = nat_rule['source_network']

        existing_nat_rule = check_for_existing_rule(existing_nat_rules,
                                                    rule_payload)
        if None == existing_nat_rule:
            changes_detected = True
            print('Adding new Nat rule: {}'.format(rule_payload))
            resp = client.post(api_endpoint, rule_payload)
        else:
            rule_payload['id'] = existing_nat_rule['id']
            rule_payload['display_name'] = existing_nat_rule['display_name']
            rule_payload['_revision'] = existing_nat_rule['_revision']
            if rule_payload['rule_priority'] != existing_nat_rule[
                    'rule_priority']:
                changes_detected = True
                print('Updating just the priority of existing nat rule: {}'.
                      format(rule_payload))
                update_api_endpint = '%s%s%s' % (api_endpoint, '/',
                                                 existing_nat_rule['id'])
                resp = client.put(update_api_endpint, rule_payload)

    if changes_detected:
        print('Done adding/updating nat rules for T0Routers!!\n')
    else:
        print('Detected no change with nat rules for T0Routers!!\n')
Example #5
0
 def updateBatchHelper(self, endpoint, objs):
     batch_results = riq.put(self.endpoint() + endpoint,
                             {"objects": [obj.payload() for obj in objs]})
     batch_results['successObjects'] = [
         self._object_class(parent=self._parent, data=obj)
         for obj in batch_results['successObjects']
     ]
     for errorObj in batch_results['errorObjects']:
         errorObj['object'] = self._object_class(parent=self._parent,
                                                 data=errorObj['object'])
     return batch_results
Example #6
0
def update_tag(api_endpoint, tag_map):
    tags = []
    resp = client.get(api_endpoint)
    updated_payload = resp.json()

    for key in tag_map:
        entry = {'scope': key, 'tag': tag_map[key]}
        tags.append(entry)
    updated_payload['tags'] = tags

    resp = client.put(api_endpoint, updated_payload)
Example #7
0
def add_loadbalancers():
    lbrs_defn = get_rsc_def_if_configured('nsx_t_lbr_spec_int',
                                          'loadbalancers')
    if not lbrs_defn:
        return

    for lbr in lbrs_defn:
        t1_router_id = global_id_map['ROUTER:TIER1:' + lbr['t1_router']]
        if t1_router_id is None:
            print(
                'Error!! No T1Router found with name: {} referred against '
                'LBR: {}'.format(lbr['t1_router'], lbr['name']))
            return

        lbr_api_endpoint = LBR_SERVICES_ENDPOINT
        lbr_service_payload = {
            'resource_type': 'LbService',
            'size': lbr['size'].upper(),
            'error_log_level': 'INFO',
            'display_name': lbr['name'],
            'attachment': {
                'target_display_name': lbr['t1_router'],
                'target_type': 'LogicalRouter',
                'target_id': t1_router_id
            }
        }

        virtual_servers = []
        for virtual_server_defn in lbr['virtual_servers']:
            virtual_server_id = add_lbr_virtual_server(virtual_server_defn)
            virtual_servers.append(virtual_server_id)

        lbr_service_payload['virtual_server_ids'] = virtual_servers

        existing_lbr = check_for_existing_lbr(lbr['name'])
        if existing_lbr is None:
            resp = client.post(lbr_api_endpoint, lbr_service_payload).json()
            print 'Created LBR: {}'.format(lbr['name'])
            print resp
            # TODO: error handling
        else:
            # Update existing LBR
            lbr_id = existing_lbr['id']

            lbr_service_payload['_revision'] = existing_lbr['_revision']
            lbr_service_payload['id'] = existing_lbr['id']

            lbr_update_api_endpoint = '%s/%s' % (lbr_api_endpoint, lbr_id)
            resp = client.put(lbr_update_api_endpoint,
                              lbr_service_payload,
                              check=False)
            print 'Updated LBR: {}'.format(lbr['name'])
            print resp
Example #8
0
 def POST(self, id, is_banned):
     if not is_admin():
         return web.notfound()
     render = web.template.render('asset', base='after.common', globals=globals())
     r, j = client.get('/users/%i/' % int(id))
     if ok(r):
         j.is_banned = int(is_banned)
         r, j = client.put('/users/%i/' % int(id), data=j)
         if ok(r):
             flash(_.user.ban.ok)
             return web.redirect('/users/%i/' % int(id))
     flash(_.user.ban.fail)
     return web.redirect('/users/%i/' % int(id))
Example #9
0
 def POST(self, id):
     i = web.input()
     print type(i)
     i.is_public = int('is_public' in i)
     del i.old_password
     del i.password2
     r, j = client.put('/users/%i/' % int(id), data=i)
     if ok(r):
         flash(_.user.edit.ok)
         raise web.redirect('/users/%i/' % int(id))
     else:
         flash(_.user.edit.fail)
         raise web.redirect('/users/%i/edit/' % int(id))
Example #10
0
 def POST(self, id, is_vip):
     if not is_admin() and int(is_vip) != 2:
         return web.notfound()
     render = web.template.render('asset', base='after.common', globals=globals())
     r, j = client.get('/users/%i/' % int(id))
     if ok(r):
         j.is_vip = int(is_vip)
         r, j = client.put('/users/%i/' % int(id), data=j)
         if ok(r):
             flash(_.vip.set.ok if int(is_vip != 2) else _.vip.set.up.ok)
             return web.redirect('/users/%i/' % int(id))
     flash(_.vip.set.fail)
     return web.redirect('/users/%i/' % int(id))
Example #11
0
def disable_auto_install_for_compute_fabric():
    compute_fabric_collection_api_endpoint = COMPUTE_COLLECTION_FABRIC_TEMPLATES_ENDPOINT
    transport_node_collection_api_endpoint = COMPUTE_COLLECTION_TRANSPORT_NODES_ENDPOINT

    outer_resp = client.get(compute_fabric_collection_api_endpoint)
    #print 'Got Compute collection respo: {}'.format(outer_resp)
    compute_fabric_templates = outer_resp.json()['results']
    for compute_fabric in compute_fabric_templates:
        #print 'Iterating over Compute fabric respo: {}'.format(compute_fabric)
        compute_fabric['auto_install_nsx'] = False
        compute_fabric_id = compute_fabric['id']

        compute_collection_id = compute_fabric['compute_collection_id']

        # First remove the related transport node template from the compute collection relationship
        transport_node_association_from_compute_fabric_api_endpoint = '%s?compute_collection_id=%s' % (
            transport_node_collection_api_endpoint, compute_collection_id)

        get_resp = client.get(
            transport_node_association_from_compute_fabric_api_endpoint,
            check=False)
        if get_resp.status_code == 200:
            try:
                for transport_node in get_resp.json()['results']:
                    transport_node_id = transport_node['id']
                    transport_node_removal_api_endpoint = '%s/%s' % (
                        transport_node_collection_api_endpoint,
                        transport_node_id)
                    delete_resp = client.delete(
                        transport_node_removal_api_endpoint, check=False)
                    print 'Removed auto-linking of Host as Transport Node in Fabric for Compute Manager: {}'.format(
                        compute_fabric['compute_collection_id'])
            except Exception as e:
                print 'No transport nodes associated'
                #ignore
        # Now change the compute fabric template
        compute_fabric_update_api_endpoint = '%s/%s' % (
            compute_fabric_collection_api_endpoint, compute_fabric_id)
        resp = client.put(compute_fabric_update_api_endpoint,
                          compute_fabric,
                          check=False)

        if resp.status_code < 400:
            print 'Disabled auto install of NSX in Compute Fabric: {}'.format(
                compute_fabric['compute_collection_id'])
            print ''
        else:
            print 'Problem in disabling auto install in Compute Fabric: {}'.format(
                compute_fabric['compute_collection_id'])
            print 'Associated Error: {}'.format(resp.json())
            exit(1)
Example #12
0
def add_loadbalancers():

  lbrs_defn = yaml.load(os.getenv('NSX_T_LBR_SPEC'))['loadbalancers']
  if len(lbrs_defn) <= 0:
    return

  for lbr in lbrs_defn:
    t1_router_id = global_id_map['ROUTER:TIER1:' + lbr['t1_router']]
    if t1_router_id is None:
      print('Error!! No T1Router found with name: {} referred against LBR: {}'.format(lbr['t1_router'], lbr['name']))
      exit -1

    lbr_api_endpoint = LBR_SERVICES_ENDPOINT
    lbr_service_payload = {
        'resource_type': 'LbService',
        'size' : lbr['size'].upper(),
        'error_log_level' : 'INFO',
        'display_name' : lbr['name'],
        'attachment': {
            'target_display_name': lbr['t1_router'],
            'target_type': 'LogicalRouter',
            'target_id': t1_router_id
        }     
    }

    virtual_servers = []
    for virtual_server_defn in lbr['virtual_servers']:
      virtual_server_id = add_lbr_virtual_server(virtual_server_defn)
      virtual_servers.append(virtual_server_id)

    lbr_service_payload['virtual_server_ids'] = virtual_servers

    existing_lbr = check_for_existing_lbr(lbr['name'])
    if existing_lbr is None:
      resp = client.post(lbr_api_endpoint, lbr_service_payload ).json()
      lbr_id = resp['id']
      print 'Created LBR: {}'.format(lbr['name'])
      print ''
    else:
      # Update existing LBR
      lbr_id = existing_lbr['id']

      lbr_service_payload['_revision'] = existing_lbr['_revision']
      lbr_service_payload['id'] = existing_lbr['id']    

      lbr_update_api_endpoint = '%s/%s' % (lbr_api_endpoint, lbr_id)
      resp = client.put(lbr_update_api_endpoint, lbr_service_payload, check=False )
      print 'Updated LBR: {}'.format(lbr['name'])
      print ''
Example #13
0
def set_t0_route_redistribution():
  for key in global_id_map:
    if key.startswith('ROUTER:TIER0'):
      t0_router_id = global_id_map[key]
      api_endpoint = '%s/%s/%s' % (ROUTERS_ENDPOINT, t0_router_id, 'routing/redistribution')

      cur_redistribution_resp = client.get(api_endpoint ).json()
      payload={
          'resource_type': 'RedistributionConfig',
          'logical_router_id': t0_router_id,
          'bgp_enabled': True,
          '_revision': cur_redistribution_resp['_revision']
        }
      resp = client.put(api_endpoint, payload )
  print('Done enabling route redistribution for T0Routers\n')
Example #14
0
 def POST(self, id):
     if not user():
         return web.notfound()
     i = web.input(image={})
     i.user_id = session.user.user_id
     i.is_public = int('is_public' in i)
     if i.image.filename:
         i.image_id = os.urandom(16).encode('hex') + os.path.splitext(i.image.filename)[1];
         f = open(image_path(i.image_id), 'wb')
         f.write(i.image.file.read())
         f.close()
         del i.image
     r, j = client.put('/topics/%i/' % int(id), data=i)
     if ok(r):
         flash(_.topic.edit.ok)
         raise web.redirect('/topics/%i/' % int(id))
     else:
         flash(_.topic.edit.fail)
         return web.redirect('/topics/%i/edit/' % int(id))
Example #15
0
def enable_route_advertisement(router_id, advertise_lb_vip=False):
    route_adv = 'routing/advertisement'
    route_adv_endpoint = '%s/%s/%s' % (ROUTERS_ENDPOINT, router_id, route_adv)

    route_adv_resp = client.get(route_adv_endpoint).json()

    payload = {
        "enabled": True,
        "resource_type": "AdvertisementConfig",
        "advertise_nsx_connected_routes": True,
    }
    if advertise_lb_vip:
        payload['advertise_lb_vip'] = True

    route_adv_resp.update(payload)

    resp = client.put(route_adv_endpoint, route_adv_resp)
    adv_lb_vip_msg = 'and LB' if advertise_lb_vip else ''
    print("Enabled route advertisements {}on T1 Router: {}".format(
        adv_lb_vip_msg, router_id))
Example #16
0
 def updateBatchHelper(self, endpoint, objs):
     batch_results = riq.put(self.endpoint()+endpoint, {"objects":[obj.payload() for obj in objs]})
     batch_results['successObjects'] = [self._object_class(parent=self._parent,data=obj) for obj in batch_results['successObjects']]
     for errorObj in batch_results['errorObjects']:
         errorObj['object'] = self._object_class(parent=self._parent,data=errorObj['object'])
     return batch_results
Example #17
0
 def update(self,options={}) :
     return self.parse(riq.put(self.endpoint() + '/' + self.id(),self.payload(),options))
Example #18
0
 def update(self, options={}):
     return self.parse(riq.put(self.endpoint() + "/" + self.id(), self.payload(), options))
Example #19
0
def add_t0_route_nat_rules():

    nat_rules_defn = os.getenv('NSX_T_NAT_RULES_SPEC', '').strip()
    if nat_rules_defn == '' or nat_rules_defn == 'null':
        print(
            'No yaml payload set for the NSX_T_NAT_RULES_SPEC, ignoring nat rules section!'
        )
        return

    nat_rules_defns = yaml.load(nat_rules_defn)['nat_rules']
    if nat_rules_defns is None or len(nat_rules_defns) <= 0:
        print(
            'No nat rule entries in the NSX_T_NAT_RULES_SPEC, nothing to add/update!'
        )
        return

    t0_router_id = global_id_map['ROUTER:TIER0:' +
                                 nat_rules_defns[0]['t0_router']]
    if t0_router_id is None:
        print('Error!! No T0Router found with name: {}'.format(
            nat_rules_defns[0]['t0_router']))
        exit - 1

    api_endpoint = '%s/%s/%s' % (ROUTERS_ENDPOINT, t0_router_id, 'nat/rules')

    changes_detected = False
    existing_nat_rules = client.get(api_endpoint).json()['results']
    for nat_rule in nat_rules_defns:

        rule_payload = {
            'resource_type': 'NatRule',
            'enabled': True,
            'rule_priority': nat_rule['rule_priority'],
            'translated_network': nat_rule['translated_network']
        }

        if nat_rule['nat_type'] == 'dnat':
            rule_payload['action'] = 'DNAT'
            rule_payload['match_destination_network'] = nat_rule[
                'destination_network']
        else:
            rule_payload['action'] = 'SNAT'
            rule_payload['match_source_network'] = nat_rule['source_network']
            if nat_rule.get('destination_network'):
                rule_payload['match_destination_network'] = nat_rule[
                    'destination_network']

        existing_nat_rule = check_for_existing_rule(existing_nat_rules,
                                                    rule_payload)

        resp = None
        if None == existing_nat_rule:
            changes_detected = True
            print('Adding new Nat rule: {}'.format(rule_payload))
            resp = client.post(api_endpoint, rule_payload)
        else:
            rule_payload['id'] = existing_nat_rule['id']
            rule_payload['display_name'] = existing_nat_rule['display_name']
            rule_payload['_revision'] = existing_nat_rule['_revision']
            if rule_payload['rule_priority'] != existing_nat_rule[
                    'rule_priority']:
                changes_detected = True
                print('Updating just the priority of existing nat rule: {}'.
                      format(rule_payload))
                update_api_endpint = '%s%s%s' % (api_endpoint, '/',
                                                 existing_nat_rule['id'])
                resp = client.put(update_api_endpint, rule_payload)

        if resp and resp.status_code >= 400:
            print 'Problem with submitting NAT Rules!!'
            print 'Associated Error: {}'.format(resp.json())
            exit(1)

    if changes_detected:
        print('Done adding/updating nat rules for T0Routers!!\n')
    else:
        print('Detected no change with nat rules for T0Routers!!\n')
Example #20
0
def add_loadbalancers():

    lbr_spec_defn = os.getenv('NSX_T_LBR_SPEC', '').strip()
    if lbr_spec_defn == '' or lbr_spec_defn == 'null':
        print(
            'No yaml payload set for the NSX_T_LBR_SPEC, ignoring loadbalancer section!'
        )
        return

    lbrs_defn = yaml.load(lbr_spec_defn)['loadbalancers']
    if lbrs_defn is None or len(lbrs_defn) <= 0:
        print(
            'No valid yaml passed in the NSX_T_LBR_SPEC, nothing to add/update for LBR!'
        )
        return

    for lbr in lbrs_defn:
        t1_router_id = global_id_map['ROUTER:TIER1:' + lbr['t1_router']]
        if t1_router_id is None:
            print(
                'Error!! No T1Router found with name: {} referred against LBR: {}'
                .format(lbr['t1_router'], lbr['name']))
            exit - 1

        lbr_api_endpoint = LBR_SERVICES_ENDPOINT
        lbr_service_payload = {
            'resource_type': 'LbService',
            'size': lbr['size'].upper(),
            'error_log_level': 'INFO',
            'display_name': lbr['name'],
            'attachment': {
                'target_display_name': lbr['t1_router'],
                'target_type': 'LogicalRouter',
                'target_id': t1_router_id
            }
        }

        virtual_servers = []
        for virtual_server_defn in lbr['virtual_servers']:
            virtual_server_id = add_lbr_virtual_server(virtual_server_defn)
            virtual_servers.append(virtual_server_id)

        lbr_service_payload['virtual_server_ids'] = virtual_servers

        existing_lbr = check_for_existing_lbr(lbr['name'])
        if existing_lbr is None:
            resp = client.post(lbr_api_endpoint, lbr_service_payload).json()

            if resp.get('error_code') is None:
                print 'Created Loadbalancer: {}'.format(lbr['name'])
                print ''
                lbr_id = resp['id']
            else:
                print 'Problem in creating Loadbalancer: {}'.format(
                    lbr['name'])
                print 'Associated Error: {}'.format(resp)
                exit(1)

        else:
            # Update existing LBR
            lbr_id = existing_lbr['id']

            lbr_service_payload['_revision'] = existing_lbr['_revision']
            lbr_service_payload['id'] = existing_lbr['id']

            lbr_update_api_endpoint = '%s/%s' % (lbr_api_endpoint, lbr_id)
            resp = client.put(lbr_update_api_endpoint,
                              lbr_service_payload,
                              check=False)

            if resp.status_code < 400:
                print 'Updated Loadbalancer: {}'.format(lbr['name'])
                print ''
            else:
                print 'Problem in updating Loadbalancer: {}'.format(
                    lbr['name'])
                print 'Associated Error: {}'.format(resp.json())
                exit(1)

            print ''
Example #21
0
    # print(listDatabases())

    
    # print(listDatabases())

    from client import put, get
    
    mongoengine.register_connection(alias='core', name=dbName)
    start = time.perf_counter()
    
    addr = "http://127.0.0.1:500" + str(random.randint(0, 2))
    print("Current Address : ", addr)
    key = 'my_msg'
    value = msg
    put(addr, key, value)
    addr = "http://127.0.0.1:500" + str(random.randint(0, 2))
    print("Recieving Address from Server Address : ", addr)
    recv_msg = get(addr, key)
    # print('Recieved message : ',recv_msg)

    print("Num of Users : ", len(readUsers()))

    parsable_message = recv_msg['payload']['value']
    parseMessage(parsable_message, dbName=None)
    users = readUsers()
    print("Num of Users : ", len(users))
    print("----------------Users----------------- ")
    print_users(users)
    
    finish = time.perf_counter()
Example #22
0
def add_lbr_pool(virtual_server_defn):
    virtual_server_name = virtual_server_defn['name']

    existing_pool = check_for_existing_lbr_pool(
        '%s%s' % (virtual_server_name, 'ServerPool'))

    pool_api_endpoint = LBR_POOLS_ENDPOINT
    lbActiveTcpMonitor = global_id_map['MONITOR:nsx-default-tcp-monitor']
    lbPassiveMonitor = global_id_map['MONITOR:nsx-default-passive-monitor']

    index = 1
    members = []

    pool_payload = {
        'resource_type': 'LbPool',
        'display_name': ('%s%s' % (virtual_server_name, 'ServerPool')),
        'tcp_multiplexing_number': 6,
        'min_active_members': 1,
        'tcp_multiplexing_enabled': False,
        'passive_monitor_id': lbPassiveMonitor,
        'active_monitor_ids': [lbActiveTcpMonitor],
        'snat_translation': {
            'port_overload': 1,
            'type': 'LbSnatAutoMap'
        },
        'algorithm': 'LEAST_CONNECTION'
    }

    monitor_name = virtual_server_defn.get('monitor')
    if monitor_name:
        active_monitor = check_for_existing_active_monitor(monitor_name)
        if active_monitor is None:
            print 'Warning!! Active Monitor specified {} for Server Pool {}ServerPool not found!!'.format(
                monitor_name, virtual_server_name)
            print 'Going with default ActiveTcpMonitor!!\n'
        else:
            pool_payload['active_monitor_ids'] = [active_monitor['id']]

    uses_port_range = False
    nsgroup_name = virtual_server_defn.get('nsgroup')
    if nsgroup_name:
        nsgroup = check_for_existing_nsgroup(nsgroup_name)
        if not nsgroup:
            nsgroup_id = create_network_security_group(nsgroup_name, None)
        else:
            nsgroup_id = nsgroup['id']

        member_group = {
            'grouping_object': {
                'target_display_name': nsgroup_name,
                'is_valid': True,
                'target_type': 'NSGroup',
                'target_id': nsgroup_id
            },
            'ip_revision_filter': 'IPV4',
            'max_ip_list_size': virtual_server_defn.get('max_members', 4)
        }
        pool_payload['member_group'] = member_group

    else:

        for member in virtual_server_defn['members']:
            member_name = ('%s-%s-%d' % (virtual_server_name, 'member', index))
            server_pool_member = {
                'max_concurrent_connections': 10000,
                'port': member['port'],
                'weight': 1,
                'admin_state': 'ENABLED',
                'ip_address': member['ip'],
                'display_name': member_name,
                'backup_member': False
            }
            if server_pool_member.get('port') is None or '-' in str(
                    server_pool_member['port']):
                server_pool_member.pop('port', None)
                uses_port_range = True

            members.append(server_pool_member)
            index += 1

        pool_payload['members'] = members

    if uses_port_range:
        pool_payload.pop('active_monitor_ids', None)

    print 'Payload for Server Pool: {}'.format(pool_payload)

    if existing_pool is None:
        resp = client.post(pool_api_endpoint, pool_payload).json()
        if resp.get('error_code') is None:
            print 'Created Server Pool for virtual server: {}'.format(
                virtual_server_name)
            print ''
            return resp['id']
        else:
            print 'Problem in creating Server Pool for virtual server: {}'.format(
                virtual_server_name)
            print 'Associated Error: {}'.format(resp)
            exit(1)

    # Update existing server pool
    pool_payload['_revision'] = existing_pool['_revision']
    pool_payload['id'] = existing_pool['id']
    pool_update_api_endpoint = '%s/%s' % (pool_api_endpoint,
                                          existing_pool['id'])
    resp = client.put(pool_update_api_endpoint, pool_payload, check=False)
    # This is just requests.models.Response, not dict
    if resp.status_code < 400:
        print 'Updated Server Pool for virtual server: {}'.format(
            virtual_server_name)
        print ''
        return existing_pool['id']
    else:
        print 'Problem in updating Server Pool for virtual server: {}'.format(
            virtual_server_name)
        print 'Associated Error: {}'.format(resp.json())
        exit(1)
Example #23
0
 def updateBatchHelper(cls, endpoint, objs):
     batch_results = riq.put(cls.endpoint()+endpoint, {"objects":[obj.payload() for obj in objs]})
     batch_results['successObjects'] = [cls(data=obj) for obj in batch_results['successObjects']]
     for errorObj in batch_results['errorObjects']:
         errorObj['object'] = cls(data=errorObj['object'])
     return batch_results