def test_multiple_server_all_servers_down(self): httpretty.register_uri(httpretty.GET, "http://127.0.0.2:8082/", body=json.dumps({ 'href': "http://127.0.0.2:8082", 'links': [] })) httpretty.register_uri(httpretty.GET, "http://127.0.0.3:8082/", body=json.dumps({ 'href': "http://127.0.0.3:8082", 'links': [] })) vnclib = vnc_api.VncApi( api_server_host=['127.0.0.1', '127.0.0.2', '127.0.0.3']) # Connect to a server # Expected to connect to one of the server vnclib._request_server(OP_GET, url='/') # Bring down all fake servers httpretty.disable() # Connect to a server # Expected to raise ConnectionError with ExpectedException(ConnectionError): vnclib._request_server(OP_GET, url='/', retry_on_error=False) # Bring up all fake servers httpretty.enable() # Connect to a server # Expected to connect to one of the server vnclib._request_server(OP_GET, url='/')
def connect(self): # Retry till API server is up connected = False self._update_connection_state(ConnectionStatus.INIT) while not connected: try: self._vnc_api_client = vnc_api.VncApi( self._conf_info['admin_user'], self._conf_info['admin_password'], self._conf_info['admin_tenant_name'], self._conf_info['api_server_ip'], self._conf_info['api_server_port'], api_server_use_ssl=self._conf_info['api_server_use_ssl'], auth_host=self._conf_info['auth_host'], auth_port=self._conf_info['auth_port'], auth_protocol=self._conf_info['auth_protocol']) connected = True self._update_connection_state(ConnectionStatus.UP) except requests.exceptions.ConnectionError as e: # Update connection info self._update_connection_state(ConnectionStatus.DOWN, str(e)) time.sleep(3) except vnc_api.ResourceExhaustionError as re: # haproxy throws 503 self._update_connection_state(ConnectionStatus.DOWN, str(re)) time.sleep(3)
def connect(self): # Retry till API server is up connected = False api_server_list = [ s.split(':')[0] for s in self._conf_info['api_servers'] ] api_server_port = self._conf_info['api_servers'][0].split(':')[1] \ if self._conf_info['api_servers'] else None self._update_connection_state(ConnectionStatus.INIT, "Connection to API Server initialized") while not connected: try: self._vnc_api_client = vnc_api.VncApi( self._conf_info['admin_user'], self._conf_info['admin_password'], self._conf_info['admin_tenant_name'], api_server_list, api_server_port, api_server_use_ssl=self._conf_info['api_server_use_ssl'], auth_host=self._conf_info['auth_host'], auth_port=self._conf_info['auth_port'], auth_protocol=self._conf_info['auth_protocol']) connected = True self._update_connection_state( ConnectionStatus.UP, "Connection to API Server established") except Exception as e: # Update connection info self._update_connection_state(ConnectionStatus.DOWN, str(e)) time.sleep(3)
def __init__(self, vnc_cfg, auth_cfg=None): if auth_cfg is None: auth_cfg = {} self.vnc_lib = vnc_api.VncApi( api_server_host=vnc_cfg.get("api_server_host"), api_server_port=vnc_cfg.get("api_server_port"), api_server_use_ssl=vnc_cfg.get("api_server_use_ssl"), apicertfile=vnc_cfg.get("api_certfile"), apikeyfile=vnc_cfg.get("api_keyfile"), apicafile=vnc_cfg.get("api_cafile"), apiinsecure=vnc_cfg.get("api_server_insecure"), username=auth_cfg.get("auth_user"), password=auth_cfg.get("auth_password"), tenant_name=auth_cfg.get("auth_tenant"), auth_token_url=auth_cfg.get("auth_token_url"), ) self.project_name = vnc_cfg.get("project_name", "test-vcenter-fabric") try: self.vnc_lib.project_create( vnc_api.Project(name=self.project_name) ) except vnc_api.RefsExistError: pass self.fabric_name = vnc_cfg.get("fabric_name", "test-fabric") self.create_fabric()
def main(): """ INIT FUNCTION """ try: username = os.environ.get('OS_USERNAME') password = os.environ.get('OS_PASSWORD') api_server = os.environ.get('OS_AUTH_URL').split("//")[1].split(":")[0] project = os.environ.get('OS_TENANT_NAME') parser = argparse.ArgumentParser() parser.add_argument('--from', action='store', dest='old_sg', help='Old security-group name') parser.add_argument('--to', action='store', dest='new_sg', help='New security-group name') args = parser.parse_args() if args.old_sg and args.new_sg: sg_old, sg_new = args.old_sg, args.new_sg vnc = vnc_api.VncApi(username=username, password=password, api_server_host=api_server, tenant_name=project) update_SG(vnc, project, sg_old, sg_new) else: print '\nMissing arguments\n\nUse "./update-sg.py --help"\n' except: print '\nERROR: Please source openstackrc file\n'
def _get_vnc_conn(cls): global vnc_conn if vnc_conn: return vnc_conn # Retry till a api-server is up try: auth_token_url = cfg.CONF.APISERVER.auth_token_url except cfg.NoSuchOptError: auth_token_url = None while True: try: vnc_conn = vnc_api.VncApi( cfg.CONF.keystone_authtoken.admin_user, cfg.CONF.keystone_authtoken.admin_password, cfg.CONF.keystone_authtoken.admin_tenant_name, cfg.CONF.APISERVER.api_server_ip, cfg.CONF.APISERVER.api_server_port, auth_host=cfg.CONF.keystone_authtoken.auth_host, auth_port=cfg.CONF.keystone_authtoken.auth_port, auth_protocol=cfg.CONF.keystone_authtoken.auth_protocol, api_server_use_ssl=cfg.CONF.APISERVER.use_ssl, auth_token_url=auth_token_url) return vnc_conn except requests.exceptions.RequestException as e: time.sleep(3)
def test_multiple_server_roundrobin_session(self): httpretty.register_uri( httpretty.GET, "http://127.1.0.1:8082/", body=json.dumps({'href': "http://127.1.0.1:8082", 'links': []})) httpretty.register_uri( httpretty.GET, "http://127.1.0.2:8082/", body=json.dumps({'href': "http://127.1.0.2:8082", 'links': []})) api_servers = ['127.1.0.3', '127.1.0.2', '127.1.0.1'] vnclib = vnc_api.VncApi( api_server_host=api_servers) # Try connecting to api-server with one node(127.1.0.3) down # Expected the connection to round robin between # 127.1.0.2 and 127.1.0.1 response = vnclib._request_server(OP_GET, url='/') index = api_servers.index(urlparse(response['href']).hostname) for i in range(6): if index < (len(api_servers) - 1): index += 1 else: index = 1 response = vnclib._request_server(OP_GET, url='/') self.assertEqual( response['href'], 'http://%s:8082' % api_servers[index])
def test_server_has_more_types_than_client(self): links = [ { "link": { "href": "http://localhost:8082/foos", "name": "foo", "rel": "collection" } }, { "link": { "href": "http://localhost:8082/foo", "name": "foo", "rel": "resource-base" } }, ] httpretty.register_uri(httpretty.GET, "http://127.0.0.1:8082/", body=json.dumps({ 'href': "http://127.0.0.1:8082", 'links': links })) vnc_api.VncApi()
def vnc_connect(self): """open a connection to the Contrail API server""" if not self.vnc_client: self.vnc_client = vnc_api.VncApi( api_server_host=self.args['api_server'], api_server_port=self.args['api_port']) return self.vnc_client
def setup_api(): keystone_client = get_keystone_client() auth_token = keystone_client.get_token(keystone_client.session) con = vnc_api.VncApi(api_server_host=conf.get('api_server', cfg.CONF.api_address), auth_token=auth_token) return con
def _get_api_connection(self): if self._vnc_lib: return # get connection to api-server REST interface tries = 0 while True: try: tries = tries + 1 self._vnc_lib = vnc_api.VncApi( api_server_host=self._vnc_api_ip, api_server_port=self._vnc_api_port, username=self._auth_user, password=self._auth_passwd, tenant_name=self._admin_tenant) self._connected_to_api_server.set() vnc_lib = self._vnc_lib domain_id = vnc_lib.fq_name_to_id('domain', ['default-domain']) project_id = vnc_lib.fq_name_to_id( 'project', ['default-domain', 'default-project']) break except Exception as e: if tries % RETRIES_BEFORE_LOG == 0: err_msg = "Connect error to contrail api %s tries: %s" \ %(tries, e) self._sandesh_logger.error(err_msg) gevent.sleep(1)
def main(): """ MAIN/AUTHENTICATE """ project_name = 'admin' domain = 'default-domain' username = '******' password = '******' api_server = '10.84.18.1' left_network_name = 'left_VN' left_network_subnet = '192.168.200.0' left_network_mask = 24 right_network_name = 'right_VN' right_network_subnet = '192.168.201.0' right_network_mask = 24 policy_name = 'red-to-blue' vnc = vnc_api.VncApi(username=username, password=password, api_server_host = api_server, tenant_name=project_name) create_VirtualNetwork(left_network_name, left_network_subnet, left_network_mask, vnc, domain, project_name) create_VirtualNetwork(right_network_name, right_network_subnet, right_network_mask, vnc, domain, project_name) create_NetworkPolicy(policy_name, left_network_name, right_network_name, vnc, domain, project_name) add_NetworkPolicy(policy_name, left_network_name, vnc, domain, project_name) add_NetworkPolicy(policy_name, right_network_name, vnc, domain, project_name)
def main(): """ MAIN/AUTHENTICATE """ vnc = vnc_api.VncApi(username='******', password='', api_server_host='192.168.1.1', tenant_name='admin') project = vnc.project_read(fq_name=['default-domain', 'admin']) left_network_name = 'left_VN' left_network_subnet = '192.168.200.0' left_network_mask = 24 right_network_name = 'right_VN' right_network_subnet = '192.168.201.0' right_network_mask = 24 create_VirtualNetwork(left_network_name, left_network_subnet, left_network_mask, vnc, project) create_VirtualNetwork(right_network_name, right_network_subnet, right_network_mask, vnc, project) service_template = create_ServiceTemplate(vnc) create_ServiceInstance(vnc, project, service_template)
def vnc_connect(self): vnc_client = vnc_api.VncApi(username=admin_user, password=admin_password, tenant_name=tenant, api_server_host=api_server, api_server_port=api_port, auth_host=keystone_server) return vnc_client
def vnc_connect(self): """open a connection to the Contrail API server""" self.vnc_client = vnc_api.VncApi(username=admin_user, password=admin_password, tenant_name=tenant, api_server_host=api_server, api_server_port=api_port) return self.vnc_client
def _get_vnc_conn(self): if self._vnc_lib: return self._vnc_lib = vnc_api.VncApi(api_server_host=self._vnc_api_ip, api_server_port=self._vnc_api_port, username=self._auth_user, password=self._auth_passwd, tenant_name=self._admin_tenant)
def create_networks(networks, project, neutron, vncconf): vnc = None if vncexists: if vncconf: if "password" not in vncconf: vncconf["password"] = getpass.getpass( '[vnc_api] Password for %s:' % vncconf["username"]) try: vnc = vnc_api.VncApi( api_server_host=vncconf["api_host"], auth_host=vncconf["auth_host"], username=vncconf["username"], password=vncconf["password"], tenant_name=vncconf["tenant_name"], auth_port=vncconf.get("auth_port", "5000"), auth_protocol=vncconf.get("auth_protocol", "https"), auth_url=vncconf.get("auth_url", "/v3/auth/tokens"), auth_type=vncconf.get("auth_type", "keystone"), ksinsecure=vncconf.get("ksinsecure", True)) logging.info("vnc_api initialized.") except Exception as e: logging.error( "Problem occurred during vnc_api initialization \n" + str(e)) for net in networks: try: netname = net.name id = project.__getattribute__("id") network = { 'name': netname, 'admin_state_up': 'True', 'tenant_id': id, 'project_id': id } nt = neutron.create_network({'network': network}) subnetname = net.name + "_subnet" subnet = { "name": subnetname, "tenant_id": id, "cidr": net.subnet, "network_id": nt["network"]["id"], "ip_version": 4 } sn = neutron.create_subnet({'subnet': subnet}) logging.info("Subnet " + str(sn) + " created.") if net.routes: update = {'host_routes': net.routes} su = neutron.update_subnet(sn["subnet"]["id"], {'subnet': update}) logging.info("Subnet " + str(su) + " updated with routes.") except Exception as e: logging.error( "Problem occurred during creating network on project \n" + str(e)) if vncexists: if net.rt_asn and (net.rt or net.import_rt or net.export_rt): process_route_target(net, nt, vnc)
def find_missing_vmi_refs(api_server_host, more_info=False): """ Gets a list of all floating IPs and organized them between good, unassigned, to_error, and unknown_exception lists. :param api_server_host: the host IP address to connect to. :param more_info: Will print additional information on the IPs. :return: The set of floating IPs organized in types. """ vnc_lib = vnc_api.VncApi(api_server_host=api_server_host) fip_set = { "good": [], # list of properly assigned floating ips "unassigned": [], # list of floating ips with unassigned MappedFixed IP Address "to_error": [], # list of floating ips where vmi_ref has 'to' field set to "['ERROR'] "unknown_exception": [], # keeps track of any unlikely exceptions while searching ips } res = vnc_lib.floating_ips_list(detail="true") for fip in res: try: ip_printed = False for vmi_ref in fip.virtual_machine_interface_refs: if vmi_ref["to"][0] == "ERROR": if more_info: print( "FIP '{}' Invalid VMI reference ('to' == ['ERROR'], parent_type '{}'" .format(fip.floating_ip_address, fip.parent_types)) print("PARENT TYPE to_error: {}".format( fip.parent_types)) fip_set["to_error"].append( (fip.floating_ip_address, fip.uuid)) else: if not ip_printed: if more_info: print( "FIP '{} - Valid VMI REF: {},parent_type '{}'". format( fip.floating_ip_address, fip.virtual_machine_interface_refs, fip.parent_types, )) ip_printed = True fip_set["good"].append((fip.floating_ip_address, fip.uuid)) except AttributeError as exc: if more_info: print( "FIP '{}' No VMI reference present (unassigned FIP?), parent_type '{}'" .format(fip.floating_ip_address, fip.parent_types)) fip_set["unassigned"].append((fip.floating_ip_address, fip.uuid)) except Exception as exc: if more_info: print( "FIP '{}' Exception thrown when examining Floating IP: {}" .format(fip.floating_ip_address, str(exc))) fip_set["unknown_exception"].append(fip.floating_ip_address) return fip_set
def handle_delete(self): vnc = vnc_api.VncApi(username = self.properties[self.USER], password = self.properties[self.PASSWORD], tenant_name = self.properties[self.KEYSTONE_NAME], api_server_host = self.properties[self.API_SERVER]) tenant = vnc.project_read(fq_name = [self.properties[self.DOMAIN], self.properties[self.TENANT_NAME]]) vn_public = vnc.virtual_network_read(fq_name = [self.properties[self.DOMAIN], self.properties[self.TENANT_NAME], self.properties[self.PUBLIC_NETWORK]]) pool = vnc_api.FloatingIpPool(name = self.properties[self.POOL_NAME], parent_obj = vn_public) tenant.del_floating_ip_pool(pool) vnc.floating_ip_pool_delete(pool.uuid) vnc.project_update(tenant)
def __init__(self, vrObject): self.vnc_client = vnc_api.VncApi( username = admin_user, password = admin_password, tenant_name = admin_tenant, api_server_host=api_server, api_server_port=api_port, auth_host=api_server) self.vrObject = vrObject print self.vrObject
def vnc_lib(self): if self._vnc_lib is None: self._vnc_lib = vnc_api.VncApi(self._user, self._passwd, self._tenant, self._api_server_ip, self._api_server_port, self._api_base_url, auth_host=self._auth_host_ip) return self._vnc_lib
def _connect_to_vnc_server(self): admin_user = cfg.CONF.keystone_authtoken.admin_user admin_password = cfg.CONF.keystone_authtoken.admin_password admin_tenant_name = cfg.CONF.keystone_authtoken.admin_tenant_name api_srvr_ip = cfg.CONF.APISERVER.api_server_ip api_srvr_port = cfg.CONF.APISERVER.api_server_port try: auth_host = cfg.CONF.keystone_authtoken.auth_host except cfg.NoSuchOptError: auth_host = "127.0.0.1" try: auth_protocol = cfg.CONF.keystone_authtoken.auth_protocol except cfg.NoSuchOptError: auth_protocol = "http" try: auth_port = cfg.CONF.keystone_authtoken.auth_port except cfg.NoSuchOptError: auth_port = "35357" try: auth_url = cfg.CONF.keystone_authtoken.auth_url except cfg.NoSuchOptError: auth_url = "/v2.0/tokens" try: auth_type = cfg.CONF.auth_strategy except cfg.NoSuchOptError: auth_type = "keystone" try: api_server_url = cfg.CONF.APISERVER.api_server_url except cfg.NoSuchOptError: api_server_url = "/" # Retry till a api-server is up connected = False while not connected: try: self._vnc_lib = vnc_api.VncApi(admin_user, admin_password, admin_tenant_name, api_srvr_ip, api_srvr_port, api_server_url, auth_host=auth_host, auth_port=auth_port, auth_protocol=auth_protocol, auth_url=auth_url, auth_type=auth_type) connected = True except requests.exceptions.RequestException: time.sleep(3) return True
def __init__(self, data): self.vnc_client = vnc_api.VncApi( username = admin_user, password = admin_password, tenant_name = admin_tenant, api_server_host=api_server, api_server_port=api_port, auth_host=api_server) self.ks_client = client.Client(username=admin_user, password=admin_password, tenant_name=admin_tenant, auth_url='http://' + api_server + ':5000/v2.0') print data self.name = data['name']
def setUpClass(cls): super(TestDeviceManager, cls).setUpClass() cls._vnc_api = vnc_api.VncApi(api_server_host=cls.contrail_ip) cls._cleanup_topology_queue = [] cls._cleanup_fabric_queue = [] try: cls._make_fake_fabric() cls._make_fake_topology() except Exception: cls.tearDownClass() raise
def __init__(self, *args, **kwargs): if 'api_server_host' in kwargs: ConfigHandle.api_server_host = kwargs['api_server_host'] if 'tenant' in kwargs: ConfigHandle.tenant = kwargs['tenant'] try: ConfigHandle.vnc_handle = vnc_api.VncApi( api_server_host=self.api_server_host, tenant_name=self.tenant) except Exception as e: ConfigHandle.vnc_handle = None print "Error: connecting to the API server, check the API Server IP" sys.exit(1)
def check(output=sys.stdout): vnc_cli = vnc_api.VncApi(conf_file='/etc/contrail/vnc_api_lib.ini') try: out = vnc_cli._objects_list('global-vrouter-config') exit_code = 0 if len(out.get('global-vrouter-configs', [])) > 0 else 1 # XXX FIXME narrow down exception type except Exception: exit_code = 1 res = {'workload': 'workload_contrail_global_vrouter_config_present', 'exit_code': exit_code} # output result output.write('%(workload)s,exit_code=%(exit_code)s\n' % res)
def test_supported_auth_strategies(self): uri_with_auth = '/try-after-auth' url_with_auth = 'http://127.0.0.1:8082%s' % uri_with_auth httpretty.register_uri( httpretty.GET, url_with_auth, responses=[ httpretty.Response(status=401, body='""'), httpretty.Response(status=200, body='""') ], ) auth_url = "http://127.0.0.1:35357/v2.0/tokens" keystone_api_called = [False] def keytone_api_request(request, url, *args): keystone_api_called[0] = True return _auth_request_status(request, url, 200) httpretty.register_uri(httpretty.POST, auth_url, body=keytone_api_request) # Verify auth strategy is Keystone if not provided and check Keystone # API is requested self.assertEqual(self._vnc_lib._authn_strategy, 'keystone') self._vnc_lib._request_server(OP_GET, url=uri_with_auth) self.assertTrue(keystone_api_called[0]) # Validate we can use 'noauth' auth strategy and check Keystone API is # not requested keystone_api_called = [False] self._vnc_lib = vnc_api.VncApi(conf_file='/tmp/fake-config-file', auth_type='noauth') self.assertEqual(self._vnc_lib._authn_strategy, 'noauth') self._vnc_lib._request_server(OP_GET, url=uri_with_auth) self.assertFalse(keystone_api_called[0]) # Validate we cannot use unsupported authentication strategy with ExpectedException(NotImplementedError): self._vnc_lib = vnc_api.VncApi(auth_type='fake-auth')
def test_multiple_server_all_servers_down(self): httpretty.register_uri(httpretty.GET, "http://127.2.0.1:8082/", body=json.dumps({ 'href': "http://127.2.0.1:8082", 'links': [] })) httpretty.register_uri(httpretty.GET, "http://127.2.0.2:8082/", body=json.dumps({ 'href': "http://127.2.0.2:8082", 'links': [] })) httpretty.register_uri(httpretty.GET, "http://127.2.0.3:8082/", body=json.dumps({ 'href': "http://127.2.0.3:8082", 'links': [] })) vnclib = vnc_api.VncApi( api_server_host=['127.2.0.3', '127.2.0.2', '127.2.0.1']) # Connect to a server # Expected to connect to first server response = vnclib._request_server(OP_GET, url='/') self.assertEqual(response['href'], 'http://127.2.0.2:8082') # Bring down all fake servers httpretty.disable() # Connect to a server # Expected to connect to second server # first server will used during authenticate with ExpectedException(ConnectionError): vnclib._request_server(OP_GET, url='/', retry_on_error=False) # Bring up all fake servers httpretty.enable() # Connect to a server # Expected to connect to first server response = vnclib._request_server(OP_GET, url='/') self.assertEqual(response['href'], 'http://127.2.0.3:8082') # Connect to a server # Expected to connect to second server response = vnclib._request_server(OP_GET, url='/') self.assertEqual(response['href'], 'http://127.2.0.2:8082') # Expected to connect to third server response = vnclib._request_server(OP_GET, url='/') self.assertEqual(response['href'], 'http://127.2.0.1:8082') # Expected to connect to first server response = vnclib._request_server(OP_GET, url='/') self.assertEqual(response['href'], 'http://127.2.0.3:8082')
def main(): stk = Stack() client = vnc_api.VncApi("127.0.0.1", 8082, False) delete_recursively(client, stk, str(sys.argv[1])) print("I am dumping all stack") stk.printitm() print("I just dunped all stack") while stk.isEmpty() == False: print("Am clearing stack") pend_uuid = stk.peek() print("Pending uuid: " , pend_uuid) delete_by_uuid(client, pend_uuid) stk.pop()
def vnc_lib(self): if ContrailResource._vnc_lib is None: ContrailResource._vnc_lib = vnc_api.VncApi( self._user, self._passwd, self._tenant, self._api_server_ip.split(), self._api_server_port, self._api_base_url, api_server_use_ssl=self._use_ssl, auth_host=self._auth_host_ip, auth_protocol=self._auth_protocol) return ContrailResource._vnc_lib