Exemplo n.º 1
0
    def POST(self, group_id):
        r, g = client.get('/groups/%i/' % int(group_id))

        i = {'user_id':session.user.user_id}
        r, j = client.post('/groups/%i/requests/' % int(group_id), data=i)

        i = {'user_id':g.creator_id}
        r, j = client.post('/groups/%i/requests/%i/' % (int(group_id),int(session.user.user_id)), data=i)

        if ok(r):
            flash(_.group.join.ok)
            raise web.redirect('/groups/%i/' % int(group_id))
        else:
            flash(_.group.join.fail)
            raise web.redirect('/notifications/')
def create_t1_logical_router(router_name, edge_cluster=False):
    api_endpoint = ROUTERS_ENDPOINT

    router_type = 'TIER1'

    t1_router_id = check_logical_router(router_name)
    if t1_router_id is not None:
        return t1_router_id

    payload = {
        'resource_type':
        'LogicalRouter',
        'description':
        "Logical router of type {}, created by nsx-t-gen!!".format(
            router_type),
        'display_name':
        router_name,
        'router_type':
        router_type
    }

    if edge_cluster:
        payload['edge_cluster_id'] = get_edge_cluster_id()

    resp = client.post(api_endpoint, payload)

    router_id = resp.json()['id']
    router_key = build_router_key(TIER1, router_name)
    global_id_map[router_key] = router_id
    print("Created Logical Router '{}' of type '{}'".format(
        router_name, router_type))
    return router_id
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']
Exemplo n.º 4
0
def create_network_security_group(nsgroup_name, tag_map):
    api_endpoint = NSGROUP_ENDPOINT
    payload={
        'resource_type' : 'NSGroup',
        'display_name' : nsgroup_name,
        'membership_criteria' : [ ],
        'members' : [ ]
    }

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

    resp = client.post(api_endpoint, payload ).json()

    if resp.get('error_code') is None:
        print 'Created NS Group: {}'.format(nsgroup_name)
        print ''
        return resp['id']

    print 'Problem in creating NS Group: {}'.format(nsgroup_name)
    print 'Associated Error: {}'.format(resp)
    exit(1)
Exemplo n.º 5
0
def create_ha_switching_profile():
  pas_tag_name   = os.getenv('NSX_T_PAS_NCP_CLUSTER_TAG')
  ha_switching_profiles = yaml.load(os.getenv('NSX_T_HA_SWITCHING_PROFILE_SPEC'))['ha_switching_profiles']
  
  api_endpoint = SWITCHING_PROFILE_ENDPOINT

  for ha_switching_profile in ha_switching_profiles:
    switching_profile_name = ha_switching_profile['name']  
    switching_profile_id   = check_switching_profile(ha_switching_profile['name'])
    if switching_profile_id is None:
      payload={
          'resource_type': 'SpoofGuardSwitchingProfile',
          'description': 'Spoofguard switching profile for ncp-cluster-ha, created by nsx-t-gen!!',
          'display_name': switching_profile_name, 
          'white_list_providers': ['LSWITCH_BINDINGS']
        }
      resp = client.post(api_endpoint, payload )
      switching_profile_id=resp.json()['id']

    global_id_map['SP:' + switching_profile_name] = switching_profile_id
    switching_profile_tags = {  
                                'ncp/cluster': pas_tag_name , 
                                'ncp/shared_resource': 'true' , 
                                'ncp/ha': 'true' 
                              }
    update_tag(SWITCHING_PROFILE_ENDPOINT + '/' + switching_profile_id, switching_profile_tags)
  print('Done creating HASwitchingProfiles\n')
def create_t0_logical_router(t0_router):
    api_endpoint = ROUTERS_ENDPOINT

    router_type = 'TIER0'
    edge_cluster_id = get_edge_cluster_id()

    router_name = t0_router['name']
    t0_router_id = check_logical_router(router_name)
    if t0_router_id is not None:
        return t0_router_id

    payload = {
        'resource_type':
        'LogicalRouter',
        'description':
        "Logical router of type {}, created by nsx-t-gen!!".format(
            router_type),
        'display_name':
        router_name,
        'edge_cluster_id':
        edge_cluster_id,
        'router_type':
        router_type,
        'high_availability_mode':
        t0_router['ha_mode'],
    }
    resp = client.post(api_endpoint, payload)

    router_id = resp.json()['id']
    print("Created Logical Router '{}' of type '{}'".format(
        router_name, router_type))
    router_key = build_router_key(TIER0, router_name)
    global_id_map[router_key] = router_id
    return router_id
def create_container_ip_block(ip_block_name, cidr, tags):
    api_endpoint = CONTAINER_IP_BLOCKS_ENDPOINT

    payload = {
        'resource_type': 'IpBlock',
        'display_name': ip_block_name,
        'cidr': cidr
    }

    if tags:
        effective_tags = []
        for key in tags:
            entry = {'scope': key, 'tag': tags[key]}
            effective_tags.append(entry)
        payload['tags'] = effective_tags

    resp = client.post(api_endpoint, payload)

    ip_block_id = resp.json()['id']
    print("Created Container IP Block '{}' with cidr: {}".format(
        ip_block_name, cidr))

    ip_block_key = '%s:%s' % (IP_BLOCK, ip_block_name)
    global_id_map[ip_block_key] = ip_block_id
    cache[ip_block_key] = resp.json()
    return ip_block_id
Exemplo n.º 8
0
def post_json(url: str, data: dict):
    url = _prepare_url(url)
    response = client.post(f"{url_prefix}{url}", data=json.dumps(data),
                           content_type='application/json',
                           follow_redirects=True)

    status_code = _get_status(response.status)
    return json.loads(response.data), status_code
Exemplo n.º 9
0
def generate_self_signed_cert(common_name, csr_request):
    tokens = common_name.split('.')
    if len(tokens) < 3:
        print(
            'Error!! CSR common name is not a full qualified domain name '
            '(provided as nsx mgr FQDN or VIP address): {}!!'.format(
                common_name))
        exit(-1)

    print('Generating CSR request with common name %s' % common_name)
    api_endpoint = TRUST_MGMT_CSRS_ENDPOINT
    payload = {
        'subject': {
            'attributes': [{
                'key': 'CN',
                'value': common_name
            }, {
                'key': 'O',
                'value': csr_request['org_name']
            }, {
                'key': 'OU',
                'value': csr_request['org_unit']
            }, {
                'key': 'C',
                'value': csr_request['country']
            }, {
                'key': 'ST',
                'value': csr_request['state']
            }, {
                'key': 'L',
                'value': csr_request['city']
            }]
        },
        'key_size': csr_request['key_size'],
        'algorithm': csr_request['algorithm']
    }
    resp = client.post(api_endpoint, payload)
    csr_id = resp.json()['id']

    self_sign_cert_api_endpint = TRUST_MGMT_SELF_SIGN_CERT
    self_sign_cert_url = '%s%s%s' % (self_sign_cert_api_endpint, csr_id,
                                     '?action=self_sign')
    self_sign_csr_response = client.post(self_sign_cert_url, '').json()
    print('CSR Request posted with response %s' % self_sign_csr_response)
    return self_sign_csr_response['id']
Exemplo n.º 10
0
 def createBatchHelper(cls, endpoint, objs):
     batch_results = riq.post(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
Exemplo n.º 11
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')
def set_cluster_vip_address():
    vip_addr = os.getenv('nsx_manager_virtual_ip_int', '').strip()
    if vip_addr == '' or vip_addr == 'null':
        print(
            'No yaml payload set for the NSX_T_LBR_SPEC, ignoring loadbalancer section!'
        )
        return

    current_vip = client.get(VIP_ENDPOINT).json()['ip_address']
    if current_vip != vip_addr:
        clear_vip_endpoint = '%s?%s' % (VIP_ENDPOINT,
                                        'action=clear_virtual_ip')
        client.post(clear_vip_endpoint, None)
        print('Setting new nsx manager virtual IP address at %s' % vip_addr)
        new_vip_endpoint = '%s?%s&%s=%s' % (
            VIP_ENDPOINT, 'action=set_virtual_ip', 'ip_address', vip_addr)
        client.post(new_vip_endpoint, None)
    else:
        print('Detected no change with nsx manager VIP address!')
Exemplo n.º 13
0
 def createBatchHelper(self, endpoint, objs):
     batch_results = riq.post(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
Exemplo n.º 14
0
 def POST(self):
     i = web.input()
     r, j = client.post('/login/', data=i)
     if ok(r):
         flash(_.login.ok)
         session.user = j
         session.username = i.username
         raise web.redirect("/")
     else:
         flash(_.login.fail)
         raise web.redirect('/login/')
Exemplo n.º 15
0
 def POST(self, id):
     if not user():
         return web.notfound()
     render = web.template.render('asset', base='after.common', globals=globals())
     r, j = client.post('/users/%i/friends/' % int(user().user_id), data={'friend_id': int(id)})
     if ok(r):
         flash(_.user.friend.ok)
         raise web.redirect('/users/%i/' % int(id))
     else:
         flash(_.user.friend.fail)
         raise web.redirect('/users/%i/' % int(id))
Exemplo n.º 16
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)
Exemplo n.º 17
0
 def POST(self, group_id):
     if not user():
         return web.notfound()
     i = {'user_id':session.user.user_id}
     r, j = client.post('/groups/%i/requests/' % int(group_id), data=i)
     if ok(r):
         flash(_.group.join.ok)
         return web.redirect('/groups/%i/' % int(group_id))
     else:
         flash(_.group.join.fail)
         return web.redirect('/groups/%i/' % int(group_id))
Exemplo n.º 18
0
 def POST(self, group_id):
     i = web.input()
     i.content += '<a href="/groups/%i/">#%s#</a><form method="post" action="/groups/%i/accept/"><button class="pull-left btn btn-primary btn-sm">Join</button></form>' % (int(i.group_id), i.group_title, int(i.group_id))
     i.user_id = session.user.user_id
     r, j = client.post('/notifications/new/', data=i)
     if ok(r):
         flash(_.notification.invite.ok)
         raise web.redirect('/groups/%i/' % int(i.group_id))
     else:
         flash(_.notification.invite.fail)
         raise web.redirect('/groups/%i/' % int(i.group_id))
Exemplo n.º 19
0
def set_cluster_vip_address():
    vip_addr = os.getenv('nsx_manager_virtual_ip_int', '').strip()
    if not vip_addr or vip_addr == '' or vip_addr == 'null':
        print('No VIP address set, ignoring VIP settings!')
        return
    current_vip = client.get(VIP_ENDPOINT).json()['ip_address']
    if current_vip != vip_addr:
        clear_vip_endpoint = '%s?%s' % (VIP_ENDPOINT,
                                        'action=clear_virtual_ip')
        client.post(clear_vip_endpoint, None)
        print('Setting new nsx manager virtual IP address at %s' % vip_addr)
        new_vip_endpoint = '%s?%s&%s=%s' % (
            VIP_ENDPOINT, 'action=set_virtual_ip', 'ip_address', vip_addr)
        rsp = client.post(new_vip_endpoint, None)
        print('Setting VIP at %s returned with response code %s', vip_addr,
              rsp)
    else:
        print('Detected no change with nsx manager VIP address!')
    # This function will check if there's already CSR with vip fqdn
    configure_self_signed_certs(cluster_cert=True)
Exemplo n.º 20
0
 def POST(self, id):
     if not user():
         return web.notfound()
     i = web.input()
     i.creator_id = session.user.user_id
     r, j = client.post('/topics/%i/comments/' % int(id), data=i)
     if ok(r):
         flash(_.comment.new.ok)
         raise web.redirect('/topics/%i/' % int(id));
     else:
         flash(_.comment.fail.ok)
         raise web.redirect('/topics/%i/' % int(id));
Exemplo n.º 21
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
Exemplo n.º 22
0
def create_t1_logical_router_and_port(t0_router_name, t1_router_name, t0_router_subnet):
  api_endpoint = ROUTER_PORTS_ENDPOINT

  t0_router_id=create_t0_logical_router_and_port(t0_router_name, t0_router_subnet)
  t1_router_id=create_t1_logical_router(t1_router_name)

  name = "LogicalRouterLinkPortFrom%sTo%s" % (t0_router_name, t1_router_name )
  descp = "Port created on %s router for %s" % (t0_router_name, t1_router_name )
  target_display_name = "LinkedPort_%sTo%s" % (t0_router_name, t1_router_name )

  payload1={
      'resource_type': 'LogicalRouterLinkPortOnTIER0',
      'description': descp,
      'display_name': name,
      'logical_router_id': t0_router_id
    }

  resp = client.post(api_endpoint, payload1)
  target_id=resp.json()['id']

  name = "LogicalRouterLinkPortFrom%sTo%s" % (t1_router_name, t0_router_name )
  descp = "Port created on %s router for %s" % (t1_router_name, t0_router_name )
  target_display_name = "LinkedPort_%sTo%s"% (t1_router_name, t0_router_name )

  payload2 = {
        'resource_type': 'LogicalRouterLinkPortOnTIER1',
        'description': descp,
        'display_name': name,
        'logical_router_id': t1_router_id,
        'linked_logical_router_port_id' : {
          'target_display_name' : target_display_name,
          'target_type' : 'LogicalRouterLinkPortOnTIER0',
          'target_id' : target_id
        }
      }

  resp = client.post(api_endpoint, payload2)
  print("Created Logical Router Port between T0Router: '{}' and T1Router: '{}'".format(t0_router_name, t1_router_name))
  logical_router_port_id=resp.json()['id']
  return logical_router_port_id
Exemplo n.º 23
0
 def POST(self):
     if not is_admin():
         return web.notfound()
     i = web.input()
     i.user_id = session.user.user_id
     render = web.template.render('asset', base='after.common', globals=globals())
     r, j = client.post('/notifications/new/', data=i)
     if ok(r):
         flash(_.notification.new.ok)
         raise web.redirect('/notifications/new/')
     else:
         flash(_.notification.new.fail)
         raise web.redirect('/notifications/new/')
Exemplo n.º 24
0
 def POST(self):
     if not user():
         return web.notfound()
     i = web.input()
     i.user_id = session.user.user_id
     render = web.template.render('asset', base='after.common', globals=globals())
     r, j = client.post('/groups/', data=i)
     if ok(r):
         flash(_.group.new.ok)
         raise web.redirect('/groups/%i/' % int(j.group_id))
     else:
         flash(_.group.new.fail)
         raise web.redirect('/groups/new/')
Exemplo n.º 25
0
    def dataHandler(self, d):
        """
            Get an XML string d and extract data and insert it into the database
        """
        data = []
        rec_handler = record()
        start = d.find('<result', 0)
        while start != -1:
            end = d.find('/>', start)
            if end == -1:
                start = -1
            else:
                end = end + 2
                xml.sax.parseString(d[start:end], rec_handler)
                temp = rec_handler.fromXMLString()
                print >> sys.stdout, str(d[start:end])
                data.append(rec_handler.fromXMLString())
                start = d.find('<results', end)

        self.db.addLaps(data)
        for lap in data:
            post_dictionary = client.prepare_data(lap)
            client.post(self.postUrl, post_dictionary)
Exemplo n.º 26
0
 def POST(self, topic_id):
     if not is_admin():
         return web.notfound()
     render = web.template.render('asset', base='after.common', globals=globals())
     i = web.input()
     i.content += '<a href="/topics/%i/">#%s#</a>' % (int(i.topic_id), i.topic_title)
     i.user_id = session.user.user_id
     r, j = client.post('/notifications/new/', data=i)
     if ok(r):
         flash(_.notification.recommend.ok)
         raise web.redirect('/topics/%i/' % int(i.topic_id))
     else:
         flash(_.notification.recommend.fail)
         raise web.redirect('/topics/%i/' % int(i.topic_id))
Exemplo n.º 27
0
def inst(text, prefix, count, voice):
    # a binary of an audio file will be sent as a response
    # TODO: take more param values to set up properly
    print("Voice = " + voice)
    response = client.post(text, voice, 1, 1)
    # check if response = 200 success
    if (response.status_code != 200):
        #TODO: in GUI.py, retrieving value -1 should engage an error message
        print("response = " + str(response))
        return -1
    filename = prefix + str(count) + '.wav'
    with open('assets/' + filename, 'wb') as f:
        f.write(response.content)
    return 'assets/' + filename
Exemplo n.º 28
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 ''
Exemplo n.º 29
0
def create_container_ip_block(ip_block_name, cidr):
  api_endpoint = CONTAINER_IP_BLOCKS_ENDPOINT
  
  payload={
      'resource_type': 'IpBlock',
      'display_name': ip_block_name,
      'cidr': cidr
    }
  resp = client.post(api_endpoint, payload )

  ip_block_id=resp.json()['id']
  print("Created Container IP Block '{}' with cidr: {}".format(ip_block_name, cidr))
  
  global_id_map['IPBLOCK:' + ip_block_name] = ip_block_id
  return ip_block_id
Exemplo n.º 30
0
 def POST(self):
     i = web.input()
     if i.password2 != i.password:
         flash(_.reg.password_mismatch)
         raise web.redirect('/reg/')
     i.is_public = int('is_public' in i)
     i.is_admin = 0
     i.is_vip = 0
     del i.password2
     r, j = client.post('/users/', data=i)
     if ok(r):
         flash(_.reg.ok)
         raise web.redirect('/login/')
     else:
         flash(_.reg.fail)
         raise web.redirect('/reg/')
Exemplo n.º 31
0
def create_logical_switch(logical_switch_name):
  api_endpoint = SWITCHES_ENDPOINT
  transport_zone_id=get_transport_zone_id(None)

  payload={ 'transport_zone_id': transport_zone_id,
        'display_name': logical_switch_name,
        'admin_state': 'UP',
        'replication_mode': 'MTEP'
      }

  resp = client.post(api_endpoint, payload )

  logical_switch_id=resp.json()['id']
  print("Created Logical Switch '{}'".format(logical_switch_name))

  global_id_map['LS:' + logical_switch_name] = logical_switch_id
  return logical_switch_id
Exemplo n.º 32
0
 def POST(self):
     if not user() or is_banned():
         return web.notfound()
     i = web.input(image={})
     i.user_id = session.user.user_id
     i.is_public = int('is_public' in i)
     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.post('/topics/', data=i)
     if ok(r):
         flash(_.topic.new.ok)
         raise web.redirect('/topics/%i/' % int(j.topic_id))
     else:
         flash(_.topic.new.fail)
         return web.redirect('/topics/new/')
Exemplo n.º 33
0
def create_external_ip_pool(ip_pool_name, cidr, gateway, start_ip, end_ip,
                            tags):
    api_endpoint = EXTERNAL_IP_POOL_ENDPOINT

    payload = {
        'resource_type':
        'IpPool',
        'display_name':
        ip_pool_name,
        'subnets': [{
            'allocation_ranges': [{
                'start': start_ip,
                'end': end_ip
            }],
            'cidr': cidr,
            'gateway_ip': gateway,
            'dns_nameservers': []
        }],
    }

    if tags:
        effective_tags = []
        for key in tags:
            entry = {'scope': key, 'tag': tags[key]}
            effective_tags.append(entry)
        effective_tags.append({'scope': 'ncp/external', 'tag': 'true'})

        payload['tags'] = effective_tags

    resp = client.post(api_endpoint, payload)
    if not resp.ok:
        print "Error: IP pool not created for %s" % ip_pool_name
        print resp.json()
        return

    ip_pool_id = resp.json()['id']
    print(
        "Created External IP Pool '{}' with cidr: {}, gateway: {}, start: {}, end: {}"
        .format(ip_pool_name, cidr, gateway, start_ip, end_ip))
    ip_pool_key = '%s:%s' % (IP_POOL, ip_pool_name)
    global_id_map[ip_pool_key] = ip_pool_id
    cache[ip_pool_key] = resp.json()
    return ip_pool_id
def create_ha_switching_profile():
    ha_switching_profiles_defn = os.getenv(
        'nsx_t_ha_switching_profile_spec_int', '').strip()
    if ha_switching_profiles_defn == '' or ha_switching_profiles_defn == 'null':
        print(
            'No yaml payload set for the NSX_T_HA_SWITCHING_PROFILE_SPEC, ignoring HASpoofguard profile section!'
        )
        return

    ha_switching_profiles = yaml.load(
        ha_switching_profiles_defn)['ha_switching_profiles']
    if ha_switching_profiles is None:
        print(
            'No valid yaml payload set for the NSX_T_HA_SWITCHING_PROFILE_SPEC, ignoring HASpoofguard profile section!'
        )
        return

    api_endpoint = SWITCHING_PROFILE_ENDPOINT

    for ha_switching_profile in ha_switching_profiles:
        switching_profile_name = ha_switching_profile['name']
        switching_profile_id = check_switching_profile(
            ha_switching_profile['name'])
        if switching_profile_id is None:
            payload = {
                'resource_type': 'SpoofGuardSwitchingProfile',
                'description':
                'Spoofguard switching profile for ncp-cluster-ha, created by nsx-t-gen!!',
                'display_name': switching_profile_name,
                'white_list_providers': ['LSWITCH_BINDINGS']
            }
            resp = client.post(api_endpoint, payload)
            switching_profile_id = resp.json()['id']

        global_id_map['SP:' + switching_profile_name] = switching_profile_id
        switching_profile_tags = {
            'ncp/shared_resource': 'true',
            'ncp/ha': 'true'
        }
        update_tag(SWITCHING_PROFILE_ENDPOINT + '/' + switching_profile_id,
                   switching_profile_tags)
    print('Done creating HASwitchingProfiles\n')
Exemplo n.º 35
0
def create_active_monitor(active_monitor_entry):
    api_endpoint = LBR_MONITORS_ENDPOINT
    payload={
        'resource_type' : active_monitor_entry['type'],
        'display_name' : active_monitor_entry['name'],
        'monitor_port' : active_monitor_entry['monitor_port']
    }

    if active_monitor_entry['type'] == 'LbHttpMonitor':
        payload['request_url'] = active_monitor_entry['path']

    resp = client.post(api_endpoint, payload ).json()

    if resp.get('error_code') is None:
        print 'Created Active monitor: {}'.format(active_monitor_entry['name'])
        print ''
        return resp['id']

    print 'Problem in creating Active monitor: {}'.format(active_monitor_entry['name'])
    print 'Associated Error: {}'.format(resp)
    exit(1)
Exemplo n.º 36
0
 def POST(self, group_id, user_id, is_approved):
     if not user():
         return web.notfound()
     i = {'user_id':session.user.user_id}
     if int(is_approved) == 1:
         r, j = client.post('/groups/%i/requests/%i/' % (int(group_id),int(user_id)), data=i)
         if ok(r):
             flash(_.group.admin.ok)
             return web.redirect('/groups/requests/')
         else:
             flash(_.group.admin.fail)
             return web.redirect('/groups/requests/')
     elif int(is_approved) == 0:
         r, j = client.delete('/groups/%i/requests/%i/' % (int(group_id),int(user_id)), data=i)
         if ok(r):
             flash(_.group.admin.ok)
             return web.redirect('/groups/requests/')
         else:
             flash(_.group.admin.fail)
             return web.redirect('/groups/requests/')
     return web.notfound()
Exemplo n.º 37
0
def create_external_ip_pool(ip_pool_name, cidr, gateway, start_ip, end_ip):
  api_endpoint = EXTERNAL_IP_POOL_ENDPOINT
  
  payload={
      'resource_type': 'IpPool',
      'display_name': ip_pool_name,      
      'subnets' : [ {  
        'allocation_ranges' : [ { 
          'start' : start_ip,
          'end' : end_ip
        } ],
        'cidr' : cidr,
        'gateway_ip' : gateway,
        'dns_nameservers' : [ ]
       } ],
    }
  resp = client.post(api_endpoint, payload )

  ip_pool_id=resp.json()['id']
  print("Created External IP Pool '{}' with cidr: {}, gateway: {}, start: {},"
    + " end: {}".format(ip_pool_name, cidr, gateway, start_ip, end_ip))
  global_id_map['IPPOOL:' + ip_pool_name] = ip_pool_id
  return ip_pool_id
Exemplo n.º 38
0
def create_t0_logical_router_and_port(t0_router):

    api_endpoint = ROUTER_PORTS_ENDPOINT
    router_name = t0_router['name']
    subnet = t0_router['subnet']

    router_id = create_t0_logical_router(router_name)
    logical_router_port_id = check_logical_router_port(t0_router_id)
    if logical_router_port_id is not None:
        return t0_router_id

    name = "LogicalRouterUplinkPortFor%s" % (router_name)
    descp = "Uplink Port created for %s router" % (router_name)
    target_display_name = "LogicalRouterUplinkFor%s" % (router_name)

    network = subnet.split('/')[0]
    cidr = subnet.split('/')[1]

    payload1 = {
        'resource_type': 'LogicalRouterUpLinkPort',
        'description': descp,
        'display_name': name,
        'logical_router_id': router_id,
        #'edge_cluster_member_index' : [ t0_router['edge_index'] ],
        'subnets': [{
            'ip_addresses': [network],
            'prefix_length': cidr
        }]
    }

    resp = client.post(api_endpoint, payload1)
    target_id = resp.json()['id']

    print("Created Logical Router Uplink Port for T0Router: '{}'".format(
        router_name))
    logical_router_port_id = resp.json()['id']
    return router_id
Exemplo n.º 39
0
# License for the specific language governing permissions and limitations
# under the License.

import client

import random
import uuid


client = client.DCIClient(end_point="http://127.0.0.1:5000",
                          login="******", password="******")

for _ in range(10):
    product = client.post('/api/products',
                          data={'name': str(uuid.uuid4())[:18],
                                'data': {
                                'product_keys': {
                                    'foo': ['bar1', 'bar2']}}})
    product_id = product.json()["id"]

    version = client.post('/api/versions',
                          data={'name': str(uuid.uuid4())[:18],
                                'product_id': product_id,
                                'data': {
                                'version_keys': {
                                    'foo': ['bar1', 'bar2']}}})
    version_id = version.json()["id"]

    for _ in range(5):

        test = client.post('/api/tests',
Exemplo n.º 40
0
 def save(self) :
     return riq.post('configs',{'meta':self.meta,'creds':self.creds,'mappings':self.mappings})
Exemplo n.º 41
0
 def createBatchHelper(self, endpoint, objs):
     batch_results = riq.post(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
Exemplo n.º 42
0
 def create(self, options={}):
     return self.parse(riq.post(self.endpoint(), self.payload(), options))
Exemplo n.º 43
0
 def createBatchHelper(cls, endpoint, objs):
     batch_results = riq.post(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