def __init__(self): username = User_Name password = Password tenant_name = Tenant project_name = Project_Name project_domain_id = User_Domain_ID user_domain_id = User_Domain_ID keystone_version = Keysstone_Version if keystone_version == 'v3': auth_url = 'http://' + Host_IP + ':5000/v3' VERSION = '2' 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) self.neutron = client.Client(session=sess) self.nova_client = Client(VERSION, session=sess) else: auth_url = 'http://' + Host_IP + ':5000/v2.0' VERSION = '2' auth = identity.Password(auth_url=auth_url, tenant_name=tenant_name, username=username, password=password) sess = session.Session(auth=auth) self.neutron = client.Client(session=sess) self.nova_client = Client(VERSION, session=sess)
def get_nova(creds=None, user=None, project=None): print(user, project) if not creds and user: nova = Client('2', user, '*', project, 'http://os_ip:5000/v2.0/') else: nova = Client(*creds.values()) return nova
def _wait_client_availability(**credentials): client = Client(version=config.CURRENT_NOVA_VERSION, session=get_session(**credentials)) current_microversion = client.versions.find(status='CURRENT').version client.api_version = APIVersion(current_microversion) return client
def do_openstack_login(data, issecure): try: nova = Client(2, data.username, data.password, data.project, data.authurl, insecure=issecure) nova.authenticate() return nova except Unauthorized, e: print >> sys.stderr, "Login error: {0}".format(e.message) sys.exit(1)
def get_stats(self): """Retrieves stats from nova""" keystone = self.get_keystone() tenant_list = keystone.tenants.list() data = { self.prefix: { 'cluster': { 'config': {} }, } } client = NovaClient('2', self.username, self.password, self.tenant, self.auth_url) for tenant in tenant_list: # FIX: nasty but works for now (tenant.id not being taken below :() client.tenant_id = tenant.id data[self.prefix]["tenant-%s" % tenant.name] = { 'limits': {}, 'quotas': {} } data_tenant = data[self.prefix]["tenant-%s" % tenant.name] # Get absolute limits for tenant limits = client.limits.get(tenant_id=tenant.id).absolute for limit in limits: if 'ram' in limit.name.lower(): limit.value = limit.value * 1024.0 * 1024.0 data_tenant['limits'][limit.name] = limit.value # Quotas for tenant quotas = client.quotas.get(tenant.id) for item in ('cores', 'fixed_ips', 'floating_ips', 'instances', 'key_pairs', 'ram', 'security_groups'): if item == 'ram': setattr(quotas, item, getattr(quotas, item) * 1024 * 1024) data_tenant['quotas'][item] = getattr(quotas, item) # Cluster allocation / reserved values for item in ('AllocationRatioCores', 'AllocationRatioRam', 'ReservedNodeCores', 'ReservedNodeRamMB', 'ReservedCores', 'ReservedRamMB'): data[self.prefix]['cluster']['config'][item] = getattr(self, item) # Hypervisor information hypervisors = client.hypervisors.list() for hypervisor in hypervisors: name = "hypervisor-%s" % hypervisor.hypervisor_hostname data[self.prefix][name] = {} for item in ('current_workload', 'free_disk_gb', 'free_ram_mb', 'hypervisor_version', 'memory_mb', 'memory_mb_used', 'running_vms', 'vcpus', 'vcpus_used'): data[self.prefix][name][item] = getattr(hypervisor, item) data[self.prefix][name]['memory_mb_overcommit'] = \ data[self.prefix][name]['memory_mb'] * data[self.prefix]['cluster']['config']['AllocationRatioRam'] data[self.prefix][name]['memory_mb_overcommit_withreserve'] = \ data[self.prefix][name]['memory_mb_overcommit'] - data[self.prefix]['cluster']['config']['ReservedNodeRamMB'] data[self.prefix][name]['vcpus_overcommit'] = \ data[self.prefix][name]['vcpus'] * data[self.prefix]['cluster']['config']['AllocationRatioCores'] data[self.prefix][name]['vcpus_overcommit_withreserve'] = \ data[self.prefix][name]['vcpus_overcommit'] - data[self.prefix]['cluster']['config']['ReservedNodeCores'] return data
def connect(config): nova_client = Client('1.1', username=config['username'], project_id=config['tenant'], api_key=config['password'], auth_url=config['auth_url'], endpoint_type=config['endpoint_type']) try: nova_client.authenticate() except Exception as e: log_error("Connection failed: %s" % e) return nova_client
def _get_nova_client(self): args = self.get_nova_client_args() if 'access_key_id' in self.creds and 'secret_access_key' in self.creds: # this pluggable auth requires api version 2 args[0] = '2' kwargs = self.get_nova_client_kwargs() if 'access_key_id' in self.creds and 'secret_access_key' in self.creds: kwargs['auth_system'] = 'secretkey' nc = NovaClient(*args, **kwargs) nc.volumes = DiabloVolumeManager(nc) return nc
def create_nova_client(user, service_type=None): """Creates a rich client for the Nova API using the test config.""" if test_config.nova_client is None: raise SkipTest("No nova_client info specified in the Test Config " "so this test will be skipped.") from novaclient.client import Client if not service_type: service_type = test_config.nova_client['nova_service_type'] openstack = Client(CONF.nova_client_version, user.auth_user, user.auth_key, user.tenant, test_config.nova_client['auth_url'], service_type=service_type, no_cache=True, cacert=test_config.values.get('cacert', None)) openstack.authenticate() return TestClient(openstack)
def connect(config): try: nova_client = Client( version=config['VERSION'], username=config['USERNAME'], api_key=config['PASSWORD'], tenant_id=config['TENANT_ID'], auth_url=config['AUTH_URL'], service_type = config['SERVICE_TYPE'] ) nova_client.authenticate() except Exception as e: print "Connection failed: %s" % e return nova_client
def main(): credentials = get_data_from_hiera('access') USERNAME = credentials['user'] PASSWORD = credentials['password'] PROJECT_ID = credentials['tenant'] VERSION = 2 IP = get_data_from_hiera('management_vip') AUTH_URL = "http://" + IP + ":5000/v2.0/" parser = OptionParser() parser.add_option("--create_zones", action="store_true", help="Create \ needed availability zones and puts coresponding compute \ services in corresponding availability zones") (options, args) = parser.parse_args() nova = Client(VERSION, USERNAME, PASSWORD, PROJECT_ID, AUTH_URL) vcenter_settings = get_data_from_hiera('vcenter') if options.create_zones: for compute in vcenter_settings['computes']: print("---Start of Compute service {0} zone creation.---".format( compute['service_name'])) check_availability_zones(nova, compute) check_host_in_zone(nova, compute) print("----End of Compute service {0} ----".format( compute['service_name']))
def main(self, argv): parser = self.get_base_parser() (options, args) = parser.parse_known_args(argv) subcommand_parser = self.get_subcommand_parser(1) self.parser = subcommand_parser if options.help or not argv: self.do_help(options) return 0 args = subcommand_parser.parse_args(argv) # Short-circuit and deal with these commands right away. if args.func == self.do_help: self.do_help(args) return 0 client = oneviewclient.Client(address=args.ov_address, username=args.ov_username, password=args.ov_password) novaclient = Client(2, args.os_username, args.os_password, args.os_tenant_name, args.os_auth_url) args.func(client, novaclient, args)
def nova_client(context, region_name=None, password=None): if CONF.nova_compute_url: url = '%(nova_url)s%(tenant)s' % { 'nova_url': normalize_url(CONF.nova_compute_url), 'tenant': context.project_id } else: region = region_name or CONF.service_credentials.region_name url = get_endpoint(context.service_catalog, service_type=CONF.nova_compute_service_type, endpoint_region=region, endpoint_type=CONF.nova_compute_endpoint_type) client = Client(CONF.nova_client_version, username=context.user, password=password, endpoint_override=url, project_id=context.project_id, project_domain_name=context.project_domain_name, user_domain_name=context.user_domain_name, auth_url=CONF.service_credentials.auth_url, auth_token=context.auth_token, insecure=CONF.nova_api_insecure) client.client.auth_token = context.auth_token client.client.endpoint_override = url return client
def __init__(self, controllerIp, cntrlr_uname='heat-admin', cntrlr_passwd='noir0123', keystone_user='******', keystone_password='******', tenant='admin'): self.cntrlrip = controllerIp self.username = cntrlr_uname self.password = cntrlr_passwd self.cred = {} self.cred['version'] = '2' self.cred['username'] = keystone_user self.cred['password'] = keystone_password self.cred['project_name'] = tenant self.cred['auth_url'] = "http://%s:5000/v2.0/" % self.cntrlrip self.cred['auth_url'] = "http://%s:5000/v3/" % self.cntrlrip auth = identity.Password(auth_url=self.cred['auth_url'], username='******', password=self.cred['password'], project_name=self.cred['project_name'], project_domain_name='Default', user_domain_name='Default') sess = session.Session(auth=auth) self.nova = Client("2", session=sess) self.err_strings = [ 'Unable', 'Conflict', 'Bad Request', 'Error', 'Unknown', 'Exception' ]
def nova_show(self, mess, vm): '''Show VM details''' self.check_config(mess) message = '/me is getting the list of VMs for project {}' project_id = self.USER_CONF[mess.frm.person]['project_id'] self.send(mess.frm, message.format(project_id), message_type=mess.type) nova_client = Client(**self.USER_CONF[mess.frm.person]) vm = nova_client.servers.get(vm) pt = PrettyTable(['Key', 'Value']) pt.align = 'l' vm = sorted(vm.to_dict().items()) for key, val in vm: if key in ['links', 'addresses']: continue if key == 'image': val = self.get_image(mess, val['id']) if key == 'flavor': val = self.get_flavor(mess, val['id']) if key == 'networks': for k, v in val.items(): val = '{}: {}'.format(k, ', '.join(v)) if key == 'security_groups': val = ', '.join([k['name'] for k in val]) pt.add_row([key, val]) return '/code {}'.format(pt)
def probe(self): try: nova = Client( '2', self.openstack['username'], self.openstack['password'], project_name=self.openstack['project_name'], user_domain_name=self.openstack['user_domain_name'], project_domain_name=self.openstack['project_domain_name'], auth_url=self.openstack['auth_url'], cacert=self.openstack['cacert'], insecure=self.openstack['insecure']) except Exception as e: self.exit_error(str(e)) try: result = nova.services.list(host=self.host, binary=self.binary) except Exception as e: self.exit_error(str(e)) stati = dict(up=0, disabled=0, down=0, total=0) for agent in result: stati['total'] += 1 if agent.status == 'enabled' and agent.state == 'up': stati['up'] += 1 elif agent.status == 'disabled': stati['disabled'] += 1 else: stati['down'] += 1 for r in stati.keys(): yield osnag.Metric(r, stati[r], min=0)
def detail_server(): print("Detail server----") global sess nova = Client("2.1", session=sess, insecure=True) image_list = nova.images.list() flavor_list = nova.flavors.list() net_list = nova.networks.list() ret_image = [] ret_flavor = [] ret_net = [] for image in image_list: quo = {"name": image.name, "uuid": image.id, "minDisk": image.minDisk} ret_image.append(quo) for flavor in flavor_list: quo = { "name": flavor.name, "vcpu": flavor.vcpus, "RAM": flavor.ram, "Disk": flavor.disk } ret_flavor.append(quo) for net in net_list: quo = {"name": net.label, "id": net.id} ret_net.append(quo) return render_template('admin/create.html', ret_image=ret_image, ret_flavor=ret_flavor, ret_net=ret_net)
def main(): parser = ArgumentParser() parser.add_argument('-u', '--user', default=os.environ['OS_USERNAME']) parser.add_argument('-p', '--password', default=os.environ['OS_PASSWORD']) parser.add_argument('-t', '--tenant', default=os.environ['OS_TENANT_NAME']) parser.add_argument('-a', '--auth-url', default=os.environ['OS_AUTH_URL']) parser.add_argument('-S', '--service-type', default='compute') parser.add_argument('-H', '--host') parser.add_argument('-s', '--scheme', default=DEFAULT_SCHEME) args = parser.parse_args() args.user client = Client(version=2, username=args.user, api_key=args.password, project_id=args.tenant, auth_url=args.auth_url, service_type=args.service_type) if args.host: hypervisors = client.hypervisors.search(args.host) else: hypervisors = client.hypervisors.list() for hv in hypervisors: hostname = hv.hypervisor_hostname.split('.')[0] for key, value in hv.to_dict().iteritems(): if key in METRIC_KEYS: output_metric('{}.{}.{}'.format(args.scheme, hostname, key), value)
def get_openstack_client(): """Creates client object instance from openstack novaclient API. And returns the client object for further use. The following environment variables affect this command: USERNAME The username of an openstack project to login. PASSWORD The password of an openstack project to login. AUTH_URL The authentication url of the project. PROJECT_ID Project ID of an openstack project. """ username = os.environ.get('USERNAME') if username is None: print('The USERNAME environment variable should be defined.') password = os.environ.get('PASSWORD') if password is None: print('The PASSWORD environment variable should be defined.') auth_url = os.environ.get('AUTH_URL') if auth_url is None: print('The AUTH_URL environment variable should be defined.') project_id = os.environ.get('PROJECT_ID') if project_id is None: print('The PROJECT_ID environment variable should be defined.') with Client(version=2, username=username, api_key=password, auth_url=auth_url, project_id=project_id) as openstack_client: openstack_client.authenticate() return openstack_client
def setup(self): from novaclient.client import Client (options, args) = self.nova.parser.parse_known_args(self.base_argv) if options.help: options.command = None self.nova.do_help(options) sys.exit(2) auth_token = getattr(args, 'os_token', None) api_version = '2.1' try: nova_client = Client( api_version, options.os_username, options.os_password, getattr( options, 'os_project_name', getattr( options, 'os_tenant_name', None ) ), tenant_id=getattr( options, 'os_project_id', getattr( options, 'os_tenant_id', None ) ), auth_token=auth_token, auth_url=options.os_auth_url, region_name=options.os_region_name, cacert=options.os_cacert, insecure=options.insecure, timeout=options.timeout) except Exception as ex: critical(ex) return options, args, nova_client
def create_connection(auth_url=None, project_name=None, project_domain_name="default", user_domain_name="default", project_domain_id="default", user_domain_id="default", username=None, password=None): """Method return a glance client.""" if auth_url.endswith("/v3/"): auth_url = auth_url[-1] elif auth_url.endswith("/v3"): pass else: auth_url = "{}/v3".format(auth_url) auth = v3.Password(auth_url=auth_url, project_name=project_name, project_domain_name=project_domain_name, user_domain_name=user_domain_name, project_domain_id=project_domain_id, user_domain_id=user_domain_id, username=username, password=password) return Client("2", auth_url=CONF.user.endpoint, session=session.Session(auth=auth))
def ra_nova_connect(host=None, project='demo'): cfgfile = get_openstack_file(host, project) params = load_params(cfgfile) nova = Client(2, params['OS_USERNAME'], params['OS_PASSWORD'], project, params['OS_AUTH_URL']) return nova
def createServer(name): print "Enter createServer" nova_credentials = auth.get_nova_credentials_v2() nova = Client(**nova_credentials) serversList = nova.servers.list() print("List of VMs: %s" % serversList) for s in serversList: if s.name == name: print "server %s exists" % name exist = True break else: print "server %s does not exist" % name exist = False if (not exist): image = nova.images.find(name="TestVM") flavor = nova.flavors.find(name="VRCS") net = nova.networks.find(label="KI10_rcs_oam") nics = [{'net-id': net.id}] print "creating server %s" % name instance = nova.servers.create(name=name, image=image, flavor=flavor, nics=nics) print("Sleeping for 5s after create command") time.sleep(5) print("List of VMs: %s" % nova.servers.list()) print "Return createServer"
def _get_nova_client(self): novaclient = Client(username=self.auth['username'], api_key=self.auth['api_key'], project_id=self.auth['project_id'], auth_url=self.auth['auth_url'], version=self.auth['version']) return novaclient
def get_resource_utilization(vim: vims.OpenStackVim): try: nova = Client( version="2", session=Session( auth=get_plugin_loader("password").load_from_options( auth_url="http://{}/identity".format(vim.address), username=vim.username, password=vim.password, user_domain_id="default", project_id=vim.tenant.id, ), timeout=5, ), ) limits = nova.limits.get(tenant_id=vim.tenant.id).to_dict()["absolute"] return { "cores": { "used": limits["totalCoresUsed"], "total": limits["maxTotalCores"], }, "memory": { "used": limits["totalRAMUsed"], "total": limits["maxTotalRAMSize"], }, } except Unauthorized: raise VimConnectionError( "Authorization error. Please check the tenant id, username, and password." ) except Exception as e: raise VimConnectionError(str(e))
def get_nova_admin(request): auth = v2.Password(auth_url=settings.AUTH_URL, username=settings.ADMIN_NAME, password=settings.ADMIN_PASS, tenant_name=settings.ADMIN_TENANT_NAME) sess = session.Session(auth=auth) novaClient = Client(settings.NOVA_VERSION, session=sess) return novaClient
def __init__(self, applicationConfig): self.applicationConfig = applicationConfig self.novaConfig = self.NovaConfiguration() if (not self.novaConfig.check()): return credentials = self._retrieveCredentials() if (credentials == None): return self.client = Client(**credentials)
def _get_name_from_id(self, mess, type_, id_): # Return the name of a nova client resource for a given person given # the type and id of the resource. try: nova_client = Client(**self.USER_CONF[mess.frm.person]) resource = getattr(nova_client, type_)[id_] return resource.name except Exception: return 'Error fetching name'
def __init__(self, config, db_name): WorkerManager.__init__(self) self._db_name = db_name DBUtil.execute_command( db_name, "CREATE TABLE IF NOT EXISTS Workers " + "(id text PRIMARY KEY, name text, initialized boolean, started DATETIME, starttime float, heartbeat DATETIME, active DATETIME)" ) self._config = config self._nc = Client('2', **config.nova_config)
def get_nova_admin(instance): auth = v2.Password(auth_url=settings.AUTH_URL, username=settings.ADMIN_NAME, password=settings.ADMIN_PASS, tenant_name=settings.ADMIN_TENANT_NAME) sess = session.Session(auth=auth) #this should read from settings novaClient = Client(settings.NOVA_VERSION, session=sess) return novaClient
def _setup(self, cf): auth = v3.Password(auth_url=cf['auth_url'], user_domain_name=cf['user_domain_name'], username=cf['username'], password=cf['password'], project_domain_name=cf['project_domain_name'], project_name=cf['project_name']) sess = session.Session(auth=auth) self.client = Client(cf['nova_version'], session=sess)
def _setup(self): auth = v3.Password(auth_url=self.auth_url, user_domain_name=self.user_domain_name, username=self.username, password=self.password, project_domain_name=self.project_domain_name, project_name=self.project_name) sess = session.Session(auth=auth) self.client = Client(self.client_version, session=sess) self.quota = OpenstackQuota(self.client, self.tenant_id, self.limit)
def _setup(self): auth = v3.Password(auth_url=self.auth_url, user_domain_name=self.user_domain_name, username=self.username, password=self.password, project_domain_name=self.project_domain_name, project_name=self.project_name) sess = session.Session(auth=auth) self.client = Client(self.client_version, session=sess) self.neutron_client = Neutron_Client(session=sess)
def openstack_report(**kwargs): username = os.environ['OS_USERNAME'] password = os.environ['OS_PASSWORD'] auth_url = os.environ['OS_AUTH_URL'] tenant_id = os.environ['OS_TENANT_ID'] os_client = Client('2', username=username, password=password, auth_url=auth_url, project_id=tenant_id) all_servers = os_client.servers.list() server_names = { 'servers': [x.name for x in all_servers]} print(json.dumps(server_names, indent=True))
def auth_client(auth_url, password): """ Authorization for server evacuate. """ auth = v2.Password(auth_url=auth_url, username='******', password=password, tenant_name='admin') sess = session.Session(auth=auth) nova_evacuate = Client(CONF.client_version, session=sess) return nova_evacuate
#!/usr/bin/env python # example.py # ========== # # This shows how to authenticate to HP Cloud's REST API with a user's access # key ID and secret key instead of their username and password. This could be # used to authenticate to any OpenStack implementation that also uses # ``apiAccessKeyCredentials`` in the JSON body of the authentication request. from novaclient.client import Client ACCESS_KEY_ID = 'FIBVLEKFOSIFJS68FI8L' SECRET_KEY = 'Mu8E/fsleibv8f2j7G97pzqKusive8ofieFkeNs1' TENANT_NAME = '[email protected]' AUTH_URL = 'https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/' REGION_NAME = 'az-3.region-a.geo-1' nova = Client('2', 'dummyvalue', 'dummyvalue', TENANT_NAME, auth_system='secretkey', auth_url=AUTH_URL, region_name=REGION_NAME) # the constructor does not accept the plugin values, so the plugin just # looks for them as attributes of the nova.client object nova.client.os_access_key_id = ACCESS_KEY_ID nova.client.os_secret_key = SECRET_KEY nova.authenticate() print nova.servers.list()