Example #1
0
    def __init__(self, configfile):
        """Object that will manage the connections to openstack. You need to give the path to the file that
        contains the openstack RC."""

        abs_fname = abspath(expanduser(configfile))

        with tempfile.TemporaryDirectory() as tmpdirname:
            authfile = join(tmpdirname, 'authenticate')
            with open(authfile, 'w') as f:
                f.write(f'source {abs_fname}\n')
                f.write('echo OS_AUTH_URL=$OS_AUTH_URL\n')
                f.write('echo OS_USERNAME=$OS_USERNAME\n')
                f.write('echo OS_PASSWORD=$OS_PASSWORD\n')
                f.write('echo OS_PROJECT_ID=$OS_PROJECT_ID\n')
                f.write('echo OS_USER_DOMAIN_NAME=$OS_USER_DOMAIN_NAME\n')
            proc = subprocess.Popen(['bash', '-c', f'source {authfile}'],
                                    stdout=subprocess.PIPE)
            env = {
                tup[0].strip(): tup[1].strip()
                for tup in map(
                    lambda s: s.decode('utf-8').strip().split('=', 1),
                    proc.stdout)
            }
            auth = v3.Password(auth_url=env['OS_AUTH_URL'],
                               username=env['OS_USERNAME'],
                               password=env['OS_PASSWORD'],
                               project_id=env['OS_PROJECT_ID'],
                               user_domain_name=env['OS_USER_DOMAIN_NAME'])

        self.session = session.Session(auth=auth)
        self.nova = nova_client('2.1', session=self.session)
        logger.info(
            f"Project is: user: {env['OS_USERNAME']}, project: {env['OS_PROJECT_ID']}, domain: {env['OS_USER_DOMAIN_NAME']}"
        )
Example #2
0
def check_nova_service(token, tenant_id, username, password, hostname,
                       keystone_port):
    print "ok"
    print token
    nova_service = []
    status = {}
    compute_endpoint = get_endpoint('admin', 'nova', username, password,
                                    hostname, keystone_port)
    print compute_endpoint
    try:
        nova = nova_client('3', auth_token=token, bypass_url=compute_endpoint)
        services = nova.services.list()
        print services
        for service in services:
            status['type-name'] = service.binary
            status['status'] = service.status
            status['hostname'] = service.host
            status['state'] = service.state
            status['updated_at'] = service.updated_at
            status['zone'] = service.zone
            nova_service.append(status)
            status = {}
            print status
        return nova_service
    except Exception as e:
        error = str(e)
        print error
    return nova_service
Example #3
0
    def get_compute_client(self, context):
        security_ctx = context.security

        conf = keystone_utils.get_session_and_auth(security_ctx,
                                                   service_type='compute')

        return nova_client(2, **conf)
def check_nova_service(token, tenant_id, username, password, hostname, keystone_port):
    print "ok"
    print token
    nova_service = []
    status = {}
    compute_endpoint = get_endpoint('admin', 'nova', username, password, hostname, keystone_port)
    print compute_endpoint
    try:
        nova = nova_client('3', auth_token=token, bypass_url=compute_endpoint)
        services = nova.services.list()
        print services
        for service in services:
            status['type-name'] = service.binary
            status['status'] = service.status
            status['hostname'] = service.host
            status['state'] = service.state
            status['updated_at'] = service.updated_at
            status['zone'] = service.zone
            nova_service.append(status)
            status = {}
            print status
        return nova_service
    except Exception as e:
        error = str(e)
        print error
    return nova_service
Example #5
0
 def create_nova(self):
     """
     Use pre-initialized session to create an instance of nova client.
     :return: novaclient instance
     """
     self.nova = nova_client(self.compute_version, session=self.sess,
                             **self.client_kwargs)
     return self.nova
    def admin_list_instances(self, instance_data=None):
        os_settings = settings[self.cloud]

        client = nova_client('1.1', os_settings["os_admin_user"],
            os_settings["os_admin_pass"], os_settings["os_admin_tenant"],
            auth_url=settings["tukey_keystone_url"] + "/v2.0")

        return self._list(client.servers,
            search_opts={"all_tenants": "True"})
Example #7
0
 def create_nova(self):
     """
     Use pre-initialized session to create an instance of nova client.
     :return: novaclient instance
     """
     self.nova = nova_client(self.compute_version,
                             session=self.sess,
                             **self.client_kwargs)
     return self.nova
Example #8
0
    def get_compute_client(self, context):
        security_ctx = context.security

        conf = keystone_utils.get_session_and_auth(
            security_ctx,
            service_type='compute'
        )

        return nova_client(2, **conf)
Example #9
0
    def admin_list_instances(self, instance_data=None):
        os_settings = settings[self.cloud]

        client = nova_client('1.1',
                             os_settings["os_admin_user"],
                             os_settings["os_admin_pass"],
                             os_settings["os_admin_tenant"],
                             auth_url=settings["tukey_keystone_url"] + "/v2.0")

        return self._list(client.servers, search_opts={"all_tenants": "True"})
Example #10
0
def desktop(request, template_name, template_data):
    """云桌面"""
    username = request.session.get("username", None)
    password = request.session.get("password", None)
    tenant_name = request.session.get("tenant_name", None)
    keystone_client_1 = template_data['keystone_client']
    auth_ref = keystone_client_1.auth_ref
    try:
        nova_client_1 = nova_client(
            2, username, password,
            tenant_name, AUTH_URL_V2)
    except Exception, e:
        return HttpResponse(e.msg)
Example #11
0
def desktop_create_server(request):
    """创建虚拟机"""
    username = request.session.get("username", None)
    password = request.session.get("password", None)
    # project_name = request.session.get("project_name", None)
    project_name = request.session.get("tenant_name", None)
    # auth_ref = request.session.get("auth_ref", None)
    try:
        c = nova_client(2, username, password,
                        project_name, AUTH_URL_V2)
    except Exception, e:
        # 返回错误对话框,点击后跳转到登陆
        print e.msg
        return HttpResponse(e.msg)
Example #12
0
def get_nova_client(username,
                    password,
                    tenant_name,
                    auth_url):
    """get nova client and catch error"""
    try:
        client = nova_client(API_VERSION, username,
                             password, tenant_name,
                             auth_url)
        return {"result": True,
                "message": "success",
                "client": client}
    except Exception, e:
        return {"result": False,
                "message": e.message}
def _get_local_active_instance_volumes():
    hostname = _get_hostname()

    local_attached_vols = []
    nova = nova_client(version=2, **CREDS)
    search_opts = {'all_tenants': True}
    for server in nova.servers.list(search_opts=search_opts):
        if getattr(server, "OS-EXT-STS:vm_state") != "active":
            continue
        server_hv = \
            getattr(server, 'OS-EXT-SRV-ATTR:hypervisor_hostname')
        attached_vols = \
            getattr(server, 'os-extended-volumes:volumes_attached')
        if server_hv == hostname and len(attached_vols):
            local_attached_vols.append([getattr(server, 'id'), attached_vols])
    return local_attached_vols
Example #14
0
    def get_compute_client(self, context):
        keystone_endpoint = keystone_utils.get_endpoint_for_project('keystone')
        nova_endpoint = keystone_utils.get_endpoint_for_project('nova')

        client = nova_client(2,
                             username=None,
                             api_key=None,
                             service_type='compute',
                             auth_token=context.auth_token,
                             tenant_id=context.project_id,
                             region_name=keystone_endpoint.region,
                             auth_url=keystone_endpoint.url,
                             insecure=context.insecure)

        client.client.management_url = keystone_utils.format_url(
            nova_endpoint.url, {'tenant_id': context.project_id})

        return client
def _get_local_active_instance_volumes():
    hostname = _get_hostname()

    local_attached_vols = []
    nova = nova_client(version=2, **CREDS)
    search_opts = {
        'all_tenants': True
    }
    for server in nova.servers.list(search_opts=search_opts):
        if getattr(server, "OS-EXT-STS:vm_state") != "active":
            continue
        server_hv = \
            getattr(server, 'OS-EXT-SRV-ATTR:hypervisor_hostname')
        attached_vols = \
            getattr(server, 'os-extended-volumes:volumes_attached')
        if server_hv == hostname and len(attached_vols):
            local_attached_vols.append([ getattr(server, 'id'), attached_vols ])
    return local_attached_vols
Example #16
0
    def get_nova_client(auth_token=None, bypass_url=None, previous_tries=0):
        if previous_tries > 3:
            return None

        # first try to use auth details from auth_ref so we
        # don't need to auth with keystone every time
        auth_ref = get_auth_ref()

        if not auth_token:
            auth_token = auth_ref['token']['id']
        if not bypass_url:
            bypass_url = get_endpoint_url_for_service(
                'compute',
                auth_ref['serviceCatalog'])

        nova = nova_client('3', auth_token=auth_token, bypass_url=bypass_url)

        try:
            flavors = nova.flavors.list()
            # Exceptions are only thrown when we try and do something
            [flavor.id for flavor in flavors]

        # except (nova_exc.Unauthorized, nova_exc.AuthorizationFailure) as e:
        # NOTE(mancdaz)nova doesn't properly pass back unauth errors, but
        # in fact tries to re-auth, all by itself. But we didn't pass it
        # an auth_url, so it bombs out horribly with an
        # Attribute error. This is a bug, to be filed...

        except AttributeError:
            auth_ref = force_reauth()
            auth_token = auth_ref['token']['id']

            nova = get_nova_client(auth_token, bypass_url, previous_tries + 1)

        # we only want to pass ClientException back to the calling poller
        # since this encapsulates all of our actual API failures. Other
        # exceptions will be treated as script/environmental issues and
        # sent to status_err
        except nova_exc.ClientException:
            raise
        except Exception as e:
            status_err(str(e))

        return nova
Example #17
0
	def __init__(topo,info):
		topo.info=info
		topo.subnet_route_route = len(info['link']['route_route'])
		topo.subnet_route_host = len(info['link']['route_host'])
		topo.subnet_num = topo.subnet_route_route+topo.subnet_route_host
		topo.router_num = info['routes']
		topo.network_id = u'' 
		topo.subnet_id = {}
		topo.subnet_cidr = {}
		topo.router_cidr = {}
		topo.ports_id = {}
		topo.router_id = {}
		topo.route_ip = {}
		topo.neutron_credentials = get_credentials()
		topo.nova_credentials = get_nova_credentials_v2()
		topo.neutron = neutron_client(**topo.neutron_credentials)
		topo.nova = nova_client(**topo.nova_credentials)
		for tmp in range(topo.subnet_num):
			topo.ports_id[tmp] = {}
		for tmp in range(topo.subnet_num):
			topo.route_ip[tmp] = {}
Example #18
0
def desktop_delete_server(request):
    # print "desktop delete server"
    if request.method == "POST":

        username = request.session.get("username", None)
        password = request.session.get("password", None)
        # project_name = request.session.get("project_name", None)
        project_name = request.session.get("tenant_name", None)
        # auth_ref = request.session.get("auth_ref", None)
        delete_server_list = request.POST.getlist("selectuser")
        print delete_server_list
        try:
            c = nova_client(
                2, username, password, project_name, AUTH_URL_V2)
            #c.servers.delete()
            print c.servers.list()
        except Exception, e:
            print e.message
            pass

        retval = {'retval': 'success', 'data': 'ok'}

        return HttpResponse(json.dumps(retval, ensure_ascii=False))
Example #19
0
    def get_compute_client(self, context):
        keystone_endpoint = keystone_utils.get_endpoint_for_project(
            context, 'keystone')
        nova_endpoint = keystone_utils.get_endpoint_for_project(
            context, 'nova')

        client = nova_client(
            2,
            username=None,
            api_key=None,
            service_type='compute',
            auth_token=context.auth_token,
            tenant_id=context.project_id,
            region_name=keystone_endpoint.region,
            auth_url=keystone_endpoint.url,
            insecure=context.insecure
        )

        client.client.management_url = keystone_utils.format_url(
            nova_endpoint.url,
            {'tenant_id': context.project_id}
        )

        return client
Example #20
0
    def get_compute_client(self, context):

        conf = keystone_utils.get_session_and_auth(context,
                                                   service_type='compute')

        return nova_client(2, **conf)
Example #21
0
def overview(request, template_name, template_data):
    """overview页面"""
    password = request.session.get("password", None)
    username = template_data["username"]
    tenant_name = template_data["tenant_name"]
    keystone_client_1 = template_data["keystone_client"]

    try:
        # 获取主机数量
        nova_client_1 = nova_client(
            2, username, password, tenant_name, AUTH_URL_V2)
        servers_sum = len(nova_client_1.servers.list())
        template_data['servers_sum'] = servers_sum

        # 获取volume数量
        cinder_client_1 = cinder_client(
            username, password, tenant_name,
            AUTH_URL_V2, service_type="volume")
        volumes_sum = len(cinder_client_1.volumes.list())
        template_data['volumes_sum'] = volumes_sum

        # volume_snapshot数量
        volume_snapshots_sum = len(cinder_client_1.volume_snapshots.list())
        template_data['volume_snapshots_sum'] = volume_snapshots_sum

        # 获取私有网络数量
        # FIXME 如果使用普通的网络,而非使用neutron
        neutron_client_1 = neutron_client(
            username=username,
            password=password,
            tenant_name=tenant_name,
            auth_url=AUTH_URL_V2)
        networks_1 = neutron_client_1.list_networks()
        private_network_sum = 0
        for net in networks_1['networks']:
            if net['tenant_id'] == keystone_client_1.tenant_id:
                private_network_sum = private_network_sum + 1
        template_data['private_network_sum'] = private_network_sum

        # floating ip 数量
        floating_ip_sum = \
            len(neutron_client_1.list_floatingips()['floatingips'])
        template_data['floating_ip_sum'] = floating_ip_sum

        # 获取该组中的用户个数
        group1 = Group.objects.get(
            tenantid=keystone_client_1.tenant_id, enable=1)
        group_users = User.objects.filter(groupid=group1.id, enable=1)
        group_users_sum = len(group_users)
        template_data['group_users_sum'] = group_users_sum

        # 获取防火墙数
        # TODO

        # 获取映像数
        glance = glance_client(
            keystone_client_1.service_catalog.url_for(service_type="image"),
            token=keystone_client_1.auth_token)
        images_sum = len(list(glance.images.list()))
        template_data['images_sum'] = images_sum

    except Exception as exc:
        print exc.message
        django_messages.add_message(
            request, 50, "nova client error: %s" % exc.message,
            extra_tags="danger")
        template_data['servers_sum'] = 0
        return render(request, "project/overview.html", template_data)
    return render(request, "project/overview.html", template_data)
Example #22
0
 def __init__(self):
     self.sess = self.create_admin_session()
     self.neutron = neutron_client.Client(session=self.sess)
     self.nova = nova_client('2', session=self.sess)
Example #23
0
def get_nova_credentials_v2():
    d = {}
    d['version'] = '2'
    d['username'] = os.environ['OS_USERNAME']
    d['api_key'] = os.environ['OS_PASSWORD']
    d['auth_url'] = os.environ['OS_AUTH_URL']
    d['project_id'] = os.environ['OS_TENANT_NAME']
    return d

public_network_name_in_network_node = "public"

neutron_credentials = get_neutron_credentials()
neutron = neutron_client.Client(**neutron_credentials)
nova_credentials = get_nova_credentials_v2()
nova = nova_client(**nova_credentials)

nova_image_list = nova.images.list()
expected_ubuntu_image_found = False

for image in nova_image_list:
    if image.name == "Ubuntu-14.04":
        expected_ubuntu_image_found = True
        break

if expected_ubuntu_image_found is False:
    print "\n Ubuntu-14.04 image not found."
    print " Run the command below to create it."
    print "\n glance image-create --name Ubuntu-14.04 --disk-format=qcow2 --container-format=bare --is-public=True < trusty-server-cloudimg-amd64-disk1.img\n"
    sys.exit(0)
Example #24
0
def get_nova_client():
    creds = get_nova_credentials()
    nc = nova_client(**creds)
    return nc
Example #25
0
def get_nova_client():
    creds = get_nova_credentials()
    nc = nova_client(**creds)
    return nc