def list_taps(project, fields): out = {} auth = identity.Password( auth_url=os.environ['OS_SERVICE_ENDPOINT'], username=os.environ['OS_USERNAME'], password=os.environ['OS_PASSWORD'], project_name=os.environ['OS_PROJECT_NAME'], project_domain_id=os.environ['OS_PROJECT_DOMAIN_ID'], user_domain_id=os.environ['OS_USER_DOMAIN_ID']) sess = session.Session(auth=auth) nc = client.Client(session=sess) prog = re.compile(r'</(' + project + ')/endpoint>-<(.*)(?:-\w{6})?>-<(.*)>-<(.*)>') ports = nc.list_ports() for thisport in ports['ports']: m = prog.match(thisport['name']) if m: project, topo, node, connection = m.group(1), m.group(2), m.group( 3), m.group(4) if not project in out: out[project] = {} if not topo in out[project]: out[project][topo] = [] if connection == project: tmp = 'Management Network' else: tmp = connection ip = thisport['fixed_ips'][0]['ip_address'] if ip in ['10.255.255.1', '10.255.255.2']: ip = '' out[project][topo].append({ 'id': thisport['id'], 'from': node, 'to': tmp, 'mac': thisport['mac_address'], 'ip': ip }) pt = prettytable.PrettyTable([ "Project", "Topology", "Node", "Link", "Interface", "MAC Address", "IP Address" ]) pt.align = "l" for project in out: projectname = project for topo in out[project]: toponame = topo out[project][topo].sort(key=itemgetter('from')) for port in out[project][topo]: pt.add_row([ projectname, toponame, port['from'], port['to'], "tap" + port['id'][0:11], port['mac'], port['ip'] ]) if len(toponame) > 0: toponame = "" projectname = "" columns = pt.field_names if fields: columns = [] for i in list(hyphen_range(fields)): columns.append(pt.field_names[i - 1]) print pt.get_string(fields=columns) return 0
def client(self): url = ("http://127.0.0.1:%s" % self.neutron_cfg_fixture.config.DEFAULT.bind_port) return client.Client(auth_strategy="noauth", endpoint_url=url)
#!/usr/bin/env python import os import sys from neutronclient.v2_0 import client as neutronclient nc = neutronclient.Client(username=os.getenv('OS_USERNAME'), password=os.getenv('OS_PASSWORD'), tenant_name=os.getenv('OS_TENANT_NAME'), auth_url=os.getenv('OS_AUTH_URL')) from novaclient.v1_1 import client as novaclient novac = novaclient.Client(os.getenv('OS_USERNAME'), os.getenv('OS_PASSWORD'), os.getenv('OS_TENANT_NAME'), os.getenv('OS_AUTH_URL')) from keystoneclient.v2_0 import client keystone = client.Client(username=os.getenv('OS_USERNAME'), password=os.getenv('OS_PASSWORD'), tenant_name=os.getenv('OS_TENANT_NAME'), auth_url=os.getenv('OS_AUTH_URL')) glance_endpoint = keystone.service_catalog.get_endpoints('image').get( 'image')[0].get('internalURL') ## HACKITY HACK HACK HACK if (glance_endpoint.endswith('/v2') or glance_endpoint.endswith('/v1')): glance_endpoint = glance_endpoint.rsplit('/', 1)[0] print "Found a glance endpoint at {}".format(glance_endpoint) for tenant in keystone.tenants.list(): if tenant.name == 'service': svc_tenant = tenant.id
def neutron(self): try: return neutron_client.Client(session=self.session.keystone_session) except neutron_exceptions.NeutronClientException as e: logger.exception('Failed to create neutron client: %s', e) raise OpenStackBackendError(e)
def __init__(self, session): super(NeutronResources, self).__init__(session) self.client = neutron_client.Client(session=session.keystone_session) self.project_id = session.project_id
type=str, default='admin', help='Keystone user project name, must have admin access') opts = parser.parse_args() auth_params = { "username": os.environ.get("OS_USERNAME", opts.username), "password": os.environ.get("OS_PASSWORD", opts.password), "tenant_name": os.environ.get("OS_PROJECT_NAME", opts.project_name), } auth = identity.V2Password(os.environ.get("OS_AUTH_URL", opts.auth_url), **auth_params) try: sess = session.Session(auth=auth) nc = client.Client(session=sess) network_name = opts.network network = nc.list_networks(name=network_name)['networks'][0] print(network['provider:segmentation_id']) create_body = { 'port': { 'network_id': network['id'], 'admin_state_up': True, 'name': 'generic_switch_test' } } port_id = nc.create_port(create_body)['port']['id'] host = nc.list_agents(agent_type='Open vSwitch agent')['agents'][0]['host']
def __init__(self, auth_attr): auth = identity.Password(**auth_attr) sess = session.Session(auth=auth) self.client = neutron_client.Client(session=sess)
def _get_client(region_name): neutron_settings = CONF.neutron return nclient.Client(**auth_utils.get_session_client_parameters( service_type='network', region=region_name, conf=neutron_settings))
def get_neutron_client(session=None): if not session: session = login_lib.load_dumped_session() neutron = neutron_client.Client(session=session) return neutron
def init_neutron(): return nclient.Client(session=get_session())
def main(): exit_code = -1 start_time = time.time() ks_creds = openstack_utils.get_credentials("keystone") nv_creds = openstack_utils.get_credentials("nova") nt_creds = openstack_utils.get_credentials("neutron") keystone = ksclient.Client(**ks_creds) user_id = openstack_utils.get_user_id(keystone, ks_creds['username']) if user_id == '': logger.error("Error : Failed to get id of %s user" % ks_creds['username']) exit(-1) logger.info("Creating tenant '%s'..." % PROMISE_TENANT_NAME) tenant_id = openstack_utils.create_tenant(keystone, PROMISE_TENANT_NAME, TENANT_DESCRIPTION) if not tenant_id: logger.error("Error : Failed to create %s tenant" % PROMISE_TENANT_NAME) exit(-1) logger.debug("Tenant '%s' created successfully." % PROMISE_TENANT_NAME) roles_name = ["admin", "Admin"] role_id = '' for role_name in roles_name: if role_id == '': role_id = openstack_utils.get_role_id(keystone, role_name) if role_id == '': logger.error("Error : Failed to get id for %s role" % role_name) exit(-1) logger.info("Adding role '%s' to tenant '%s'..." % (role_id, PROMISE_TENANT_NAME)) if not openstack_utils.add_role_user(keystone, user_id, role_id, tenant_id): logger.error("Error : Failed to add %s on tenant %s" % (ks_creds['username'], PROMISE_TENANT_NAME)) exit(-1) logger.debug("Role added successfully.") logger.info("Creating user '%s'..." % PROMISE_USER_NAME) user_id = openstack_utils.create_user(keystone, PROMISE_USER_NAME, PROMISE_USER_PWD, None, tenant_id) if not user_id: logger.error("Error : Failed to create %s user" % PROMISE_USER_NAME) exit(-1) logger.debug("User '%s' created successfully." % PROMISE_USER_NAME) logger.info("Updating OpenStack credentials...") ks_creds.update({ "username": PROMISE_TENANT_NAME, "password": PROMISE_TENANT_NAME, "tenant_name": PROMISE_TENANT_NAME, }) nt_creds.update({ "tenant_name": PROMISE_TENANT_NAME, }) nv_creds.update({ "project_id": PROMISE_TENANT_NAME, }) glance = openstack_utils.get_glance_client() nova = nvclient.Client("2", **nv_creds) logger.info("Creating image '%s' from '%s'..." % (PROMISE_IMAGE_NAME, GLANCE_IMAGE_PATH)) image_id = openstack_utils.create_glance_image(glance, PROMISE_IMAGE_NAME, GLANCE_IMAGE_PATH) if not image_id: logger.error("Failed to create the Glance image...") exit(-1) logger.debug("Image '%s' with ID '%s' created successfully." % (PROMISE_IMAGE_NAME, image_id)) flavor_id = openstack_utils.get_flavor_id(nova, PROMISE_FLAVOR_NAME) if flavor_id == '': logger.info("Creating flavor '%s'..." % PROMISE_FLAVOR_NAME) flavor_id = openstack_utils.create_flavor(nova, PROMISE_FLAVOR_NAME, PROMISE_FLAVOR_RAM, PROMISE_FLAVOR_DISK, PROMISE_FLAVOR_VCPUS) if not flavor_id: logger.error("Failed to create the Flavor...") exit(-1) logger.debug("Flavor '%s' with ID '%s' created successfully." % (PROMISE_FLAVOR_NAME, flavor_id)) else: logger.debug("Using existing flavor '%s' with ID '%s'..." % (PROMISE_FLAVOR_NAME, flavor_id)) neutron = ntclient.Client(**nt_creds) network_dic = openstack_utils.create_network_full(neutron, PROMISE_NET_NAME, PROMISE_SUBNET_NAME, PROMISE_ROUTER_NAME, PROMISE_SUBNET_CIDR) if not network_dic: logger.error("Failed to create the private network...") exit(-1) logger.info("Exporting environment variables...") os.environ["NODE_ENV"] = "functest" os.environ["OS_PASSWORD"] = PROMISE_USER_PWD os.environ["OS_TEST_IMAGE"] = image_id os.environ["OS_TEST_FLAVOR"] = flavor_id os.environ["OS_TEST_NETWORK"] = network_dic["net_id"] os.environ["OS_TENANT_NAME"] = PROMISE_TENANT_NAME os.environ["OS_USERNAME"] = PROMISE_USER_NAME os.chdir(PROMISE_REPO_DIR + '/source/') results_file_name = os.path.join(RESULTS_DIR, 'promise-results.json') results_file = open(results_file_name, 'w+') cmd = 'npm run -s test -- --reporter json' logger.info("Running command: %s" % cmd) ret = subprocess.call(cmd, shell=True, stdout=results_file, stderr=subprocess.STDOUT) results_file.close() if ret == 0: logger.info("The test succeeded.") # test_status = 'OK' else: logger.info("The command '%s' failed." % cmd) # test_status = "Failed" # Print output of file with open(results_file_name, 'r') as results_file: data = results_file.read() logger.debug("\n%s" % data) json_data = json.loads(data) suites = json_data["stats"]["suites"] tests = json_data["stats"]["tests"] passes = json_data["stats"]["passes"] pending = json_data["stats"]["pending"] failures = json_data["stats"]["failures"] start_time_json = json_data["stats"]["start"] end_time = json_data["stats"]["end"] duration = float(json_data["stats"]["duration"]) / float(1000) logger.info("\n" "****************************************\n" " Promise test report\n\n" "****************************************\n" " Suites: \t%s\n" " Tests: \t%s\n" " Passes: \t%s\n" " Pending: \t%s\n" " Failures:\t%s\n" " Start: \t%s\n" " End: \t%s\n" " Duration:\t%s\n" "****************************************\n\n" % (suites, tests, passes, pending, failures, start_time_json, end_time, duration)) if args.report: stop_time = time.time() json_results = { "timestart": start_time, "duration": duration, "tests": int(tests), "failures": int(failures) } logger.debug("Promise Results json: " + str(json_results)) # criteria for Promise in Release B was 100% of tests OK status = "FAIL" if int(tests) > 32 and int(failures) < 1: status = "PASS" exit_code = 0 ft_utils.push_results_to_db("promise", "promise", start_time, stop_time, status, json_results) exit(exit_code)
}) for volume in volumes: try: cinder.volumes.delete(volume) print("Volume %s deleted" % volume.name) except cinderc.exceptions.NotFound as e: print(e) sys.exit(1) except cinderc.exceptions.ClientException as e: print(e) sys.exit(1) # Neutron: Deleting routers, subnets, networks, security groups and releasing floating IPs neutron = neutronc.Client(session=sess, project_id=project_id, endpoint_type='internalURL') # Deleting all security groups but default for sec_group in neutron.list_security_groups()['security_groups']: if sec_group['project_id'] == project_id and sec_group['name'] != "default": neutron.delete_security_group(sec_group['id']) print("Security group %s deleted" % sec_group['id']) # Deleting floating IPs for ip in neutron.list_floatingips()['floatingips']: if ip['project_id'] == project_id: neutron.delete_floatingip(ip['id']) print("Floating IP %s released" % ip['floating_ip_address'])
def neutron_client(self) -> neutron_client.Client: if not self.__neutron_client: conf = self._auth_conf.copy() conf['password'] = conf.pop('api_key') self.__neutron_client = neutron_client.Client(**conf) return self.__neutron_client
def __init__(self, auth_attr): auth_cred = auth_attr.copy() verify = 'True' == auth_cred.pop('cert_verify', 'True') or False auth = identity.Password(**auth_cred) sess = session.Session(auth=auth, verify=verify) self.client = neutron_client.Client(session=sess)
def __init__(self, **kwargs): self.session = kwargs.get("session") self.client = NClient.Client(session=self.session)
try: username = os.environ['OS_USERNAME'] password = os.environ['OS_PASSWORD'] project_name = os.environ['OS_PROJECT_NAME'] project_domain_id = os.environ['OS_PROJECT_DOMAIN_ID'] user_domain_id = os.environ['OS_USER_DOMAIN_ID'] auth_url = os.environ['OS_AUTH_URL'] auth = identity.Password(auth_url=auth_url, username=username, password=password, project_name=project_name, project_domain_id=project_domain_id, user_domain_id=user_domain_id) sess = session.Session(auth=auth) neutron = neutron_client.Client(session=sess) nova = nova_client.Client("2.0", session=sess) except Exception as e: print "\nAn Exception was raised: ", type(e), e, "\n" sys.exit() # GLobal variables network_id = '' subnet_id = '' router_id = '' many_router_list = [] # Function to run a Linux command def run_command(cmd): try: p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
def setUp(self): super(ClientTestBase, self).setUp() test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) try: test_timeout = int(test_timeout) except ValueError: test_timeout = 0 if test_timeout > 0: self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) if (os.environ.get('OS_STDOUT_CAPTURE') == 'True' or os.environ.get('OS_STDOUT_CAPTURE') == '1'): stdout = self.useFixture(fixtures.StringStream('stdout')).stream self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) if (os.environ.get('OS_STDERR_CAPTURE') == 'True' or os.environ.get('OS_STDERR_CAPTURE') == '1'): stderr = self.useFixture(fixtures.StringStream('stderr')).stream self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) if (os.environ.get('OS_LOG_CAPTURE') != 'False' and os.environ.get('OS_LOG_CAPTURE') != '0'): self.useFixture( fixtures.LoggerFixture(nuke_handlers=False, format=self.log_format, level=None)) # Collecting of credentials: # # Grab the cloud config from a user's clouds.yaml file. # First look for a functional_admin cloud, as this is a cloud # that the user may have defined for functional testing that has # admin credentials. # If that is not found, get the devstack config and override the # username and project_name to be admin so that admin credentials # will be used. # # Finally, fall back to looking for environment variables to support # existing users running these the old way. We should deprecate that # as tox 2.0 blanks out environment. # # TODO(sdague): while we collect this information in # tempest-lib, we do it in a way that's not available for top # level tests. Long term this probably needs to be in the base # class. openstack_config = os_client_config.config.OpenStackConfig() try: cloud_config = openstack_config.get_one_cloud('functional_admin') except os_client_config.exceptions.OpenStackConfigException: try: cloud_config = openstack_config.get_one_cloud( 'devstack', auth=dict(username='******', project_name='admin')) except os_client_config.exceptions.OpenStackConfigException: try: cloud_config = openstack_config.get_one_cloud('envvars') except os_client_config.exceptions.OpenStackConfigException: cloud_config = None if cloud_config is None: raise NoCloudConfigException( "Could not find a cloud named functional_admin or a cloud" " named devstack. Please check your clouds.yaml file and" " try again.") auth_info = cloud_config.config['auth'] user = auth_info['username'] passwd = auth_info['password'] self.project_name = auth_info['project_name'] auth_url = auth_info['auth_url'] user_domain_id = auth_info['user_domain_id'] self.project_domain_id = auth_info['project_domain_id'] if 'insecure' in cloud_config.config: self.insecure = cloud_config.config['insecure'] else: self.insecure = False auth = identity.Password(username=user, password=passwd, project_name=self.project_name, auth_url=auth_url, project_domain_id=self.project_domain_id, user_domain_id=user_domain_id) session = ksession.Session(auth=auth, verify=(not self.insecure)) self.client = self._get_novaclient(session) self.glance = glanceclient.Client('2', session=session) # pick some reasonable flavor / image combo if "flavor" not in CACHE: CACHE["flavor"] = pick_flavor(self.client.flavors.list()) if "image" not in CACHE: CACHE["image"] = pick_image(self.glance.images.list()) self.flavor = CACHE["flavor"] self.image = CACHE["image"] if "network" not in CACHE: # Get the networks from neutron. neutron = neutronclient.Client(session=session) neutron_networks = neutron.list_networks()['networks'] # Convert the neutron dicts to Network objects. nets = [] for network in neutron_networks: nets.append(networks.Network(networks.NeutronManager, network)) # Keep track of whether or not there are multiple networks # available to the given tenant because if so, a specific # network ID has to be passed in on server create requests # otherwise the server POST will fail with a 409. CACHE['multiple_networks'] = len(nets) > 1 CACHE["network"] = pick_network(nets) self.network = CACHE["network"] self.multiple_networks = CACHE['multiple_networks'] # create a CLI client in case we'd like to do CLI # testing. tempest.lib does this really weird thing where it # builds a giant factory of all the CLIs that it knows # about. Eventually that should really be unwound into # something more sensible. cli_dir = os.environ.get( 'OS_NOVACLIENT_EXEC_DIR', os.path.join(os.path.abspath('.'), '.tox/functional/bin')) self.cli_clients = tempest.lib.cli.base.CLIClient( username=user, password=passwd, tenant_name=self.project_name, uri=auth_url, cli_dir=cli_dir, insecure=self.insecure) self.keystone = keystoneclient.Client(session=session, username=user, password=passwd) self.cinder = cinderclient.Client(auth=auth, session=session)
if (options.user != None): OS_USERNAME = options.user if (options.passwd != None): OS_PASSWORD = options.passwd if (options.tenant_name != None): OS_TENANT_NAME = options.tenant_name if (options.auth_url != None): OS_AUTH_URL = options.auth_url creds = get_keystone_creds() if creds == None: raise RunTimeError("Could not find Keystone environment variables") neutron = nuclient.Client(**creds) tmp_nets = options.mac_net_ip_list.split(",") for net in tmp_nets: tmp_mac_ip_net = net.split("@") mac = tmp_mac_ip_net[0] ip_list = tmp_mac_ip_net[1] network_name = tmp_mac_ip_net[2] _validate_mac_addr(mac) ip_range_list = [] validate_ip_ranges(ip_list, ip_range_list) tmp_network = find_network(network_name) if tmp_network == None: raise RuntimeError("Could not locate Network: " + network_name) MAC_IP_NET_LIST.append((mac, ip_range_list, tmp_network, network_name))
def _get_network_client(self): return neutron_client.Client(session=self.identity_client.session, service_type='network', region_name=self.conf.region, endpoint_type='publicURL')
output = f.read() output = output.splitlines() if output == []: script_ended = True break else: time.sleep(1) print "perfdhcp ended\n" # Wait for measure_cpu_memory and port-churn and network-churn # running in a separate thread to stop time.sleep(10) neutron_credentials = get_neutron_credentials() neutron = neutron_client.Client(**neutron_credentials) # Delete remaining churned networks, subnets and ports print "Deleting remaining churned networks, subnets and ports\n" f = os.popen( "timeout 60 neutron port-list | grep 'existing\|new' | awk \'{print $2}\' 2> /dev/null" ) output = f.read() output = output.splitlines() for i in output: try: # neutron.delete_port(i) os.system("neutron port-delete " + i + " &> /dev/null") time.sleep(0.5)
def displayImages_flavors_zones(self, region, c_name, userRecords): img = [] img_id = [] net_id = [] net_val = [] v = [] flavor = [] content = [] i = 0 n = 0 y = 0 self.username = c_name self.region = region self.imgId = '' self.imgName = '' self.visible = '' region_val = [] current_dir = os.environ["HOME"] chk = self.username.find('@') if chk != -1: storeusername = self.username.split('@') uname = storeusername[0] if chk == -1: uname = self.username self.auth = userRecords for key, value in self.auth.iteritems(): if key == 'token': token = value if key == 'project_name': project_name = value if key == 'project_domain_name': project_domain_name = value print '- LOADING : ........ ', sys.stdout.flush() try: if self.region == 'SCL1': novaauth = v3.Token( auth_url='http://expostack.tf-net.mydomain.com:35357/v3', token=token, project_name=project_name, project_domain_name=project_domain_name) if self.region == 'LA1': novaauth = v3.Token( auth_url='http://expostack-02.tf-net.mydomain.com:35357/v3', token=token, project_name=project_name, project_domain_name=project_domain_name) session_id = session.Session(auth=novaauth) keystone = client.Client(session=session_id) nova = novaClient.Client('2', session=session_id) glance = glclient.Client('2', session=session_id) neutron = nclient.Client(session=session_id) except (exceptions.AuthorizationFailure): self.progress() print ' [DONE]' print('\n') prompt = '- Error: Unable to authenticate or validate the existing authorization token for ' + uname + ' at ' + time.strftime( "%d/%m/%Y") + ' ' + time.strftime("%I:%M:%S") + '.' self.log(self.region, c_name, prompt) print(prompt) return 1 except (exceptions.Unauthorized): self.progress() print ' [DONE]' print('\n') prompt = '- Error: Authentication failed due to invalid token for ' + uname + ' at ' + time.strftime( "%d/%m/%Y") + ' ' + time.strftime("%I:%M:%S") + '.' self.log(self.region, c_name, prompt) print(prompt) return 1 try: userDisplay = PrettyTable([ "CATALOG NAME", "ACCESS", "FLAVOR", "ZONES", "NETWORK NAME", "REGION NAME" ]) userDisplay.align["CATALOG NAME"] = "l" userDisplay.align["ACCESS"] = "l" userDisplay.align["FLAVOR"] = "l" userDisplay.align["ZONES"] = "l" userDisplay.align["NETWORK NAME"] = "l" userDisplay.align["REGION NAME"] = "l" userDisplay.padding_width = 1 glanceImages = glance.images.list() images = list(glanceImages) with open( current_dir + "/" + '.' + self.region + "/" + '.' + uname.lower() + "/" + '.' + 'images' + '.json', 'wt') as out: sendJson = dump(images, out, sort_keys=True, indent=4, separators=(',', ': ')) with open( current_dir + "/" + '.' + self.region + "/" + '.' + uname.lower() + "/" + '.' + 'images' + '.json', 'r') as f: data = load(f) for item in data: for key, value in item.items(): if key == 'id': self.imgId = value if key == 'name': self.imgName = value if key == 'visibility': self.visible = value imgList = self.makeImage(self.visible, self.imgName) imgID = self.makeImgId(self.visible, self.imgId) imgVisible = self.makeVisible(self.visible) if imgList: img.insert(i, imgList) if imgID: img_id.insert(i, imgID) if imgVisible: v.insert(i, imgVisible) i = i + 1 flavors = nova.flavors.list() for item in flavors: flavor.insert(n, item.name) n = n + 1 if len(v) > len(flavor): first = len(v) second = len(flavor) third = first - second for blank in range(third): flavor.append('-') third = third - 1 fl = flavor zone = open( current_dir + "/" + '.' + self.region + "/" + '.' + uname.lower() + "/" + '.zones', 'w') zones = nova.availability_zones.list(detailed=True) for z in zones: one = str(z).replace('<AvailabilityZone:', '') two = str(one).replace('>', '') zone.write(str(two).lstrip() + ',') zone.close() with open(current_dir + "/" + '.' + self.region + "/" + '.' + uname.lower() + "/" + '.zones') as f: lines = f.read() content = lines.rstrip(',').split(',') if len(v) > len(content): init = len(v) sec = len(content) th = init - sec for empty in range(th): content.append('-') th = th - 1 zones_list = content network = neutron.list_networks() with open( current_dir + "/" + '.' + self.region + "/" + '.' + uname.lower() + "/" + '.network.json', 'wt') as out: netJson = dump(network, out, sort_keys=True, indent=4, separators=(',', ': ')) with open( current_dir + "/" + '.' + self.region + "/" + '.' + uname.lower() + "/" + '.network.json', 'r') as f: net_data = load(f) for key, value in net_data.items(): for column in value: for net_key, net_value in column.items(): if net_key == 'id': net_id.insert(y, net_value) if net_key == 'name': net_val.insert(y, net_value) y = y + 1 network_id = net_id network_val = net_val if len(v) > len(network_id): net_one = len(v) net_two = len(network_id) net_th = net_one - net_two for blank in range(net_th): network_id.append('-') network_val.append('-') net_th = net_th - 1 _net_id = network_id _net_val = network_val region_val = self.region.split() if len(v) > len(region_val): r_one = len(v) r_two = len(region_val) r_th = r_one - r_two for rank in range(r_th): region_val.append('-') r_th = r_th - 1 _region_val = region_val for l, m, n, p, q, r in map(None, img, v, fl, zones_list, _net_val, _region_val): userDisplay.add_row([l, m, n, p, q, r]) self.progress() print ' [DONE]' print('\n') print '- USE THE TABLE DETAILS: IMAGE, FLAVOR, AVAILABILITY ZONES, NETWORK NAME FOR INSTANCE CREATION.' print(userDisplay) except (IOError, IndexError, KeyError, NameError, OSError, RuntimeError, SyntaxError, IndentationError, TypeError, UnboundLocalError, ValueError): self.progress() print ' [DONE]' print('\n') prompt = '- Error: Could not fetch the resource records for ' + uname + ' at ' + time.strftime( "%d/%m/%Y") + ' ' + time.strftime("%I:%M:%S") + '.' self.log(self.region, uname, prompt) print(prompt) return 1 else: prompt = '- Info: Resource records fetch successful for ' + uname + ' at ' + time.strftime( "%d/%m/%Y") + ' ' + time.strftime("%I:%M:%S") + '.' self.log(self.region, uname, prompt) print(prompt) return 0
help="Dump only non allocated floating IP bridge mac_maps") cliargs = argparser.parse_args() if not cliargs.username: cliargs.username = raw_input("Username: "******"ports"] if cliargs.bridge: floating_ips = neutron.list_floatingips()["floatingips"] floating_ips_by_ip = {} for fip in floating_ips: floating_ips_by_ip[fip["floating_ip_address"]] = fip port_paths = [] for port in ports: if not cliargs.bridge: port_str = "%s,%s,2147483647" % (port["mac_address"], port["id"]) port_paths.append( "/midonet/v2/zoom/0/tables/Network/%s/mac_table/0/%s" % (port["network_id"], port_str))
def factory_fn(token, endpoint): return neutron.Client(token=token, endpoint_url=endpoint, insecure=credential.https_insecure, cacert=credential.https_cacert)
def client(self): return neutron_clientv20.Client(session=self.auth_session, region_name=self.region_name)
import pdb from neutronclient.v2_0 import client from credentials import get_credentials from config import TENANT_BASE_INDEX, NETWORK_COUNT, \ EXTERNAL_NETWORK, print_scale_test_config, DEPLOYMENT_ID, \ ASR_HOST, ASR_USER, ASR_PASSWORD, ENABLE_ASR_VERIFICATION, TENANT_COUNT, \ TENANT_NAME_PREFIX, TENANT_NAME, TENANT_CREATION, VM_COUNT from tenants import create_tenant, discover_tenant from vm_instances import discover_vm_on_network, launch_vm_on_network from networks import delete_networks, delete_vm credentials = get_credentials() neutron = client.Client(**credentials) tenant_data = [] router_data = [] network_dict = {} def tenant_discovery(): pdb.set_trace() #for i in range(len(TENANT_NAME)): #tenant_name = TENANT_NAME[i] #tenant_data.append(discover_tenant()) #discover_tenant() tenant_data = [{ 'id': u'2931fbe17e8445da875bb915a29d0bbf', 'name': u'admin' }, { 'id': u'2e93f5f662974b1284e8be13dd472e48', 'name': u'demo' }, {
def nova_deploy_instace(): service_types = [] service_status = {} INITIAL_STATUS = "UNKNOWN" service_url = {} FLAVOR_NAME = "cirros.1" NETWORK_NAME = "default" IMAGE_NAME = "cirros-0.3.4" #keystone = client.Client(username=os.environ['OS_USERNAME'], # password=os.environ['OS_PASSWORD'], # tenant_name=os.environ['OS_TENANT_NAME'], # auth_url=os.environ['OS_AUTH_URL']) auth = v2.Password(auth_url=os.environ["OS_AUTH_URL"], username=os.environ["OS_USERNAME"], password=os.environ['OS_PASSWORD'], tenant_name=os.environ['OS_TENANT_NAME']) sess = session.Session(auth=auth) #get keystone session keystone = client.Client(session=sess) #print keystone.tenants.list() nova = novaClient.Client("2", session=keystone.session, timings=True, timeout=1) flavor = nova.flavors.find(name=FLAVOR_NAME) if not flavor: print "No flavour found" exit(0) #Get glance images glance = glanceClient.Client("1", session=keystone.session) image = glance.images.find(name=IMAGE_NAME) if not image: print "No image found" exit(0) #get neutron /netrowk info neutron = neutronClient.Client(session=keystone.session) networks = neutron.list_networks(name=NETWORK_NAME) if not networks: print "No default network found" exit(0) nics = [{'net-id': networks['networks'][0]['id']}] index = 0 while index == 0: results = [] try: # Starting nova instance result = initResult() nova.reset_timings() result["action"] = "Create" result["invoked_time"] = str(datetime.datetime.now()) instance = nova.servers.create(name="PUTTUR_IS_HERE", image=image, flavor=flavor, nics=nics) instance_id = instance.id result["time"] = getTimings(nova.get_timings()) result['id'] = instance_id result['name'] = instance.name nova.reset_timings() # Poll at 2?? second intervals, until the status is no longer 'BUILD' or need to decide when to stop '' till it is running? status = instance.status result["status"] = status if status == "ERROR": result["error_state"] = instance.error results.append(result) print_result(results) exit(0) results.append(result) #exit(0) #check status while status == 'BUILD': time.sleep(1) result = initResult() # Retrieve the instance again so the status field updates try: nova.reset_timings() instance = nova.servers.get(instance_id) if instance.status != status: result["invoked_time"] = str(datetime.datetime.now()) status = instance.status result["action"] = "GET_STATUS" result["status"] = status if hasattr(instance, "fault"): result["fault"] = get_fault(instance.fault) result["time"] = getTimings(nova.get_timings()) results.append(result) except Exception as err: result["error_state"] = err results.append(result) #if the status is Not Build, delete except Exception as err: result["error_state"] = err results.append(result) #print_result(results) #Delete instance and print result = delete_instance(nova, instance_id) results.append(result) print_result(results)
def setUp(self): super(ITestCase, self).setUp() self.common_config = cfg.ITConfig().common_config self.vanilla_config = cfg.ITConfig().vanilla_config self.vanilla_two_config = cfg.ITConfig().vanilla_two_config self.hdp_config = cfg.ITConfig().hdp_config telnetlib.Telnet(self.common_config.SAHARA_HOST, self.common_config.SAHARA_PORT) keystone = keystone_client.Client( username=self.common_config.OS_USERNAME, password=self.common_config.OS_PASSWORD, tenant_name=self.common_config.OS_TENANT_NAME, auth_url=self.common_config.OS_AUTH_URL) keystone.management_url = self.common_config.OS_AUTH_URL self.common_config.OS_TENANT_ID = [ tenant.id for tenant in keystone.tenants.list() if tenant.name == self.common_config.OS_TENANT_NAME ][0] self.sahara = sahara_client.Client( version=self.common_config.SAHARA_API_VERSION, username=self.common_config.OS_USERNAME, api_key=self.common_config.OS_PASSWORD, project_name=self.common_config.OS_TENANT_NAME, auth_url=self.common_config.OS_AUTH_URL, sahara_url='http://%s:%s/v%s/%s' % (self.common_config.SAHARA_HOST, self.common_config.SAHARA_PORT, self.common_config.SAHARA_API_VERSION, self.common_config.OS_TENANT_ID)) self.nova = nova_client.Client( username=self.common_config.OS_USERNAME, api_key=self.common_config.OS_PASSWORD, project_id=self.common_config.OS_TENANT_NAME, auth_url=self.common_config.OS_AUTH_URL) self.neutron = neutron_client.Client( username=self.common_config.OS_USERNAME, password=self.common_config.OS_PASSWORD, tenant_name=self.common_config.OS_TENANT_NAME, auth_url=self.common_config.OS_AUTH_URL) if not self.common_config.FLAVOR_ID: self.flavor_id = self.nova.flavors.create(name='i-test-flavor-%s' % str(uuid.uuid4())[:8], ram=1024, vcpus=1, disk=10, ephemeral=10).id else: self.flavor_id = self.common_config.FLAVOR_ID if not self.common_config.PATH_TO_SSH_KEY: self.common_config.USER_KEYPAIR_ID += str(uuid.uuid4())[:8] self.private_key = self.nova.keypairs.create( self.common_config.USER_KEYPAIR_ID).private_key else: self.private_key = open(self.common_config.PATH_TO_SSH_KEY).read()
def __init__(self, creds): self.neutronclient = neutron_client.Client(**creds)
def neutron(context): return neutronclient.Client(session=context.session, service_type='network')
parser.add_option("--password", dest="password", default="password", help="password", metavar="PASSWORD") parser.add_option("--tenant", dest="tenant", default="admin", help="tenant", metavar="TENANT") (options, args) = parser.parse_args() client = neutron.Client(username=options.username, password=options.password, tenant_name=options.tenant, auth_url=options.auth_url, insecure=True, service_type='network') try: agents = client.list_agents() except Exception: # neutronclient.exceptions.Unauthorized: print "Failed to authenticate to Keystone" sys.exit(-1) except: print "Failed to query service" sys.exit(-1) agents = filter( lambda agent: agent["host"] == options.host and agent["binary"] == options. binary, agents["agents"])