示例#1
0
def create(context, conf, **kwargs):
    conf.register_opts(cinder_client_opts, group=CONFIG_GROUP)

    client_config = conf[CONFIG_GROUP]
    url = utils.get_url(SERVICE,
                        context,
                        client_config,
                        append_project_fmt='%(url)s/%(project)s',
                        **kwargs)
    LOG.debug('Creating cinder client with url %s.', url)

    if kwargs.get('session'):
        return cc.Client(CINDERCLIENT_VERSION,
                         session=kwargs.get('session'),
                         endpoint_override=url)

    args = {
        'project_id': context.project_id,
        'cacert': client_config.cinder_ca_cert_file,
        'insecure': client_config.cinder_auth_insecure,
    }
    client = cc.Client(CINDERCLIENT_VERSION, **args)
    client.client.auth_token = context.auth_token
    client.client.management_url = url
    return client
 def initiate_client(self):
     os_auth_url = self.configs['Authentication']['os_auth_url']
     os_version = self.configs['Authentication']['os_version']
     os_username = self.configs['Authentication']['os_username']
     os_password = self.configs['Authentication']['os_password']
     os_tenant_id = self.configs['Authentication']['os_tenant_id']
     os_tenant_name = self.configs['Authentication']['os_tenant_name']
     if os_tenant_id:
         self.nova = nclient.Client(os_version,
                                    os_username,
                                    os_password,
                                    tenant_id=os_tenant_id,
                                    auth_url=os_auth_url)
         self.cinder = cclient.Client(version=os_version,
                                      username=os_username,
                                      api_key=os_password,
                                      tenant_id=os_tenant_id,
                                      auth_url=os_auth_url)
     else:
         self.nova = nclient.Client(os_version,
                                    os_username,
                                    os_password,
                                    project_id=os_tenant_name,
                                    auth_url=os_auth_url)
         self.cinder = cclient.Client(version=os_version,
                                      username=os_username,
                                      api_key=os_password,
                                      project_id=os_tenant_name,
                                      auth_url=os_auth_url)
     # Authenticate client.
     # Raise exception as it is
     self.nova.authenticate()
     self.cinder.authenticate()
示例#3
0
def set_quotas():
    conn = os_client_config.make_sdk()
    project_id = conn.session.get_project_id()

    nova = nova_client.Client("2", session=conn.session)
    try:
        cinder = cinder_client.Client("2", session=conn.session)
        cinder.quotas.update(
            project_id,
            gigabytes=-1,
            snapshots=-1,
            volumes=-1,
        )
    except exceptions.SDKException:
        cinder = cinder_client.Client("1", session=conn.session)
        cinder.quotas.update(
            project_id,
            gigabytes=-1,
            snapshots=-1,
            volumes=-1,
        )

    nova.quotas.update(
        project_id,
        cores=-1,
        fixed_ips=-1,
        floating_ips=-1,
        injected_file_content_bytes=-1,
        injected_file_path_bytes=-1,
        injected_files=-1,
        instances=-1,
        key_pairs=-1,
        metadata_items=-1,
        ram=-1,
        security_group_rules=-1,
        security_groups=-1,
        server_groups=-1,
        server_group_members=-1,
    )
    conn.network.update_quota(
        project_id,
        floatingip=-1,
        network=-1,
        port=-1,
        router=-1,
        security_group=-1,
        security_group_rule=-1,
        subnet=-1,
    )
示例#4
0
    def __init__(self, authurl, tenant_name, username, password):
        from keystoneclient.auth.identity import v2
        from keystoneclient import session
        from keystoneclient.v2_0 import client as ksclient
        from novaclient import client
        from neutronclient.neutron import client as nclient
        from cinderclient import client as cclient
        auth = v2.Password(auth_url=authurl,
                           user_id=username,
                           password=password,
                           tenant_name=tenant_name)
        sess = session.Session(auth=auth)

        self.__auth = auth
        self.__sess = sess
        __nova = client.Client('2', session=sess)
        __cinder = cclient.Client('2', session=sess)
        __neutron = nclient.Client('2.0', session=sess)
        __keystone = ksclient.Client(session=sess)
        self.__conn = ConnectionWrapper(__nova, __cinder, __neutron,
                                        __keystone)
        self.conn = ConnectionWrapper(__nova, __cinder, __neutron, __keystone)

        self.userid = self.__conn.nova.client.get_user_id()
        self.user_is_project_admin = self.__conn.user_is_project_admin = bool(
            self.get_user_roles().count('admin'))

        # FIXME Retain these lines during testing only
        self.nova = self.__conn.nova
        self.cinder = self.__conn.cinder
        self.neutron = self.__conn.neutron
        self.auth = auth
        self.sess = sess
        self.keystone = self.__conn.keystone
示例#5
0
    def get_cinder_client(previous_tries=0):
        if previous_tries > 3:
            return None
        # right now, cinderclient does not accept a previously derived token
        # or endpoint url. So we have to pass it creds and let it do it's own
        # auth each time it's called.
        # NOTE: (mancdaz) update when https://review.openstack.org/#/c/74602/
        # lands

        auth_details = get_auth_details()
        cinder = c_client.Client('2',
                                 auth_details['OS_USERNAME'],
                                 auth_details['OS_PASSWORD'],
                                 auth_details['OS_TENANT_NAME'],
                                 auth_details['OS_AUTH_URL'])

        try:
            # Do something just to ensure we actually have auth'd ok
            volumes = cinder.volumes.list()
            # Exceptions are only thrown when we iterate over volumes
            [i.id for i in volumes]
        except (c_exc.Unauthorized, c_exc.AuthorizationFailure) as e:
            cinder = get_cinder_client(previous_tries + 1)
        except Exception as e:
            status_err(str(e))

        return cinder
示例#6
0
    def get_cinder_client(previous_tries=0):
        if previous_tries > 3:
            return None
        # right now, cinderclient does not accept a previously derived token
        # or endpoint url. So we have to pass it creds and let it do it's own
        # auth each time it's called.

        auth_details = get_auth_details()
        cinder = c_client.Client(
            '2',
            auth_details['OS_USERNAME'],
            auth_details['OS_PASSWORD'],
            auth_details['OS_TENANT_NAME'],
            auth_details['OS_AUTH_URL'],
            insecure=auth_details['OS_API_INSECURE'],
            endpoint_type=auth_details['OS_ENDPOINT_TYPE'])

        try:
            # Do something just to ensure we actually have auth'd ok
            volumes = cinder.volumes.list()
            # Exceptions are only thrown when we iterate over volumes
            [i.id for i in volumes]
        except (c_exc.Unauthorized, c_exc.AuthorizationFailure) as e:
            cinder = get_cinder_client(previous_tries + 1)
        except Exception as e:
            metric_bool('client_success', False, m_name='maas_cinder')
            status_err(str(e), m_name='maas_cinder')

        return cinder
示例#7
0
    def _discover_client(self, current_client, os_api_version,
                         os_endpoint_type, os_service_type, os_username,
                         os_password, os_project_name, os_auth_url,
                         client_args):

        if (os_api_version.get_major_version()
                in api_versions.DEPRECATED_VERSIONS):
            discovered_version = api_versions.DEPRECATED_VERSION
            os_service_type = 'volume'
        else:
            discovered_version = api_versions.discover_version(
                current_client, os_api_version)

        if not os_endpoint_type:
            os_endpoint_type = DEFAULT_CINDER_ENDPOINT_TYPE

        if not os_service_type:
            os_service_type = self._discover_service_type(discovered_version)

        API_MAX_VERSION = api_versions.APIVersion(api_versions.MAX_VERSION)

        if (discovered_version != API_MAX_VERSION
                or os_service_type != 'volume'
                or os_endpoint_type != DEFAULT_CINDER_ENDPOINT_TYPE):
            client_args['service_type'] = os_service_type
            client_args['endpoint_type'] = os_endpoint_type

            return (client.Client(discovered_version, os_username, os_password,
                                  os_project_name, os_auth_url,
                                  **client_args), discovered_version)
        else:
            return current_client, discovered_version
示例#8
0
 def __init__(self,
              host='127.0.0.1',
              version='2',
              port=None,
              user='******',
              password=None,
              debug=False,
              project=None,
              domain='Default',
              auth_url=None):
     self.debug = debug
     self.host = host
     loader = loading.get_plugin_loader('password')
     auth = loader.load_from_options(auth_url=auth_url,
                                     username=user,
                                     password=password,
                                     project_name=project,
                                     user_domain_name=domain,
                                     project_domain_name=domain)
     sess = session.Session(auth=auth)
     self.nova = novaclient.Client(version, session=sess)
     self.glance = glanceclient(version, session=sess)
     self.cinder = cinderclient.Client(version, session=sess)
     self.neutron = neutronclient(session=sess)
     self.conn = self.nova
     self.project = project
     return
示例#9
0
 def __init__(self,
              host='127.0.0.1',
              version='2',
              port=None,
              user='******',
              password=None,
              debug=False,
              project=None,
              domain='Default',
              auth_url=None,
              ca_file=None,
              external_network=None):
     self.debug = debug
     self.host = host
     loader = loading.get_plugin_loader('password')
     auth = loader.load_from_options(auth_url=auth_url,
                                     username=user,
                                     password=password,
                                     project_name=project,
                                     user_domain_name=domain,
                                     project_domain_name=domain)
     if ca_file is not None:
         sess = session.Session(auth=auth,
                                verify=os.path.expanduser(ca_file))
     else:
         sess = session.Session(auth=auth)
     self.nova = novaclient.Client(version, session=sess)
     self.glance = glanceclient(version, session=sess)
     self.cinder = cinderclient.Client(version, session=sess)
     self.neutron = neutronclient(session=sess)
     self.conn = self.nova
     self.project = project
     self.external_network = external_network
     return
示例#10
0
    def __init__(self, deploy):
        # type: (Deploy) -> None
        """
        Constructor for Openstack
        :param deploy: 
        """
        self.deploy = deploy

        # Create auth session fail if no auth
        self.ost_auth_session = Openstack.create_ost_auth_session(deploy)

        self.cinder = cinderclient.Client("2",
                                          session=self.ost_auth_session,
                                          region_name=deploy.region)
        self.neutron = neutronclient.Client(session=self.ost_auth_session,
                                            region_name=deploy.region)
        self.nova = novaclient.Client("2",
                                      session=self.ost_auth_session,
                                      region_name=deploy.region)
        self.heat = heatclient.Client("1",
                                      session=self.ost_auth_session,
                                      region_name=deploy.region)

        # Retries for certain features
        self.retries = 5

        # Sleep backoff for certain features
        self.sleep = 30
        self.short_sleep = 5

        # run retries on these exceptions, as a tuple
        self.retry_exceptions = (
            keystoneauth1_exceptions.connection.ConnectFailure, IndexError)

        self.thread_exception = False
    def cinder(self):
        if cinderclient is None:
            return self.nova('volume')
        if self._cinder:
            return self._cinder

        con = self.context
        if self.auth_token is None:
            logger.error("Cinder connection failed, no auth_token!")
            return None

        args = {
            'service_type': 'volume',
            'auth_url': con.auth_url,
            'project_id': con.tenant_id,
            'username': None,
            'api_key': None
        }

        self._cinder = cinderclient.Client('1', **args)
        management_url = self.url_for(service_type='volume')
        self._cinder.client.auth_token = self.auth_token
        self._cinder.client.management_url = management_url

        return self._cinder
示例#12
0
def get_usage_from_os_client(session, regions, project_id):
    resource_usage_all = collections.defaultdict(dict)
    neutron_opts = {'tenant_id': project_id}
    cinder_opts = {'all_tenants': 1, 'project_id': project_id}
    for current_region in regions:
        resource_usage = collections.defaultdict(dict)
        nova_client = nv_client.Client(NOVA_API_VERSION,
                                       session=session,
                                       region_name=current_region)
        neutron_client = nt_client.Client(NEUTRON_API_VERSION,
                                          session=session,
                                          region_name=current_region)
        cinder_client = ci_client.Client(CINDER_API_VERSION,
                                         session=session,
                                         region_name=current_region)
        limits = nova_client.limits.get().to_dict()
        # Read nova usages
        resource_usage['ram'] = limits['absolute']['totalRAMUsed']
        resource_usage['cores'] = limits['absolute']['totalCoresUsed']
        resource_usage['instances'] = limits['absolute']['totalInstancesUsed']
        resource_usage['key_pairs'] = len(nova_client.keypairs.list())
        # Read neutron usages
        resource_usage['network'] = len(
            neutron_client.list_networks(**neutron_opts)['networks'])
        resource_usage['subnet'] = len(
            neutron_client.list_subnets(**neutron_opts)['subnets'])
        # Read cinder usages
        resource_usage['volumes'] = len(
            cinder_client.volumes.list(search_opts=cinder_opts))
        resource_usage_all[current_region] = resource_usage
    return resource_usage_all
示例#13
0
    def __init__(self):
        self.db = sqlite3.connect(':memory:')
        self.cur = self.db.cursor()
        self.init_db()
        self.user = CONF.CREDENTIALS.username
        self.pwd = CONF.CREDENTIALS.password
        self.url = CONF.CREDENTIALS.url
        self.tenant = CONF.CREDENTIALS.tenant
        self.novc = novaclient.Client(2,
                                      self.user,
                                      self.pwd,
                                      self.tenant,
                                      auth_url=self.url)
        self.cinc = cinderclient.Client('2',
                                        self.user,
                                        self.pwd,
                                        self.tenant,
                                        auth_url=self.url)

        self.auth = identity.Password(auth_url=self.url,
                                      username=self.user,
                                      password=self.pwd,
                                      project_name=self.tenant)
        self.sess = session.Session(auth=self.auth)
        self.neuc = neutronclient.Client(session=self.sess)
        self.keystone = idclient.Client(session=self.sess)
示例#14
0
    def connection_buildup(self):
        # a dict of all projects we have in openstack
        self.projects = dict()
        # openstack connection
        try:
            self.conn = connection.Connection(auth_url=os.getenv('OS_AUTH_URL'),
                                     project_name=os.getenv('OS_PROJECT_NAME'),
                                     project_domain_name=os.getenv('OS_PROJECT_DOMAIN_NAME'),
                                     username=os.getenv('OS_USERNAME'),
                                     user_domain_name=os.getenv('OS_USER_DOMAIN_NAME'),
                                     password=os.getenv('OS_PASSWORD'),
                                     identity_api_version="3")
        except Exception as e:
            log.warn("- PLEASE CHECK MANUALLY - problems connecting to openstack: %s - retrying in next loop run",
                     str(e))
        else:
            # get all openstack projects
            # no exception handling is done here as it would complicate things and we just
            # successfully created the connection, so that chance is low to fail
            for project in self.conn.identity.projects():
                self.projects[project.id] = project.name
            if not self.projects:
                raise RuntimeError('- PLEASE CHECK MANUALLY - did not get any keystone projects back from the keystone api - this should in theory never happen ...')

        if self.cindercmdline:
            # cinder client session reusing the auth from the openstacksdk connection session
            # this is needed to set the state of volumes and snapshots, which is not yet implemented in the openstacksdk
            auth = self.conn.session.auth
            sess = session.Session(auth=auth)
            self.cinder = client.Client("2.0", session=sess)
示例#15
0
    def get_cinder_client(cls, region, service_name=None, endpoint=None,
                          endpoint_type='publicURL', insecure=False,
                          cacert=None):
        """Create cinder client object.

        :param region: The region of the service
        :param service_name: The name of the cinder service in the catalog
        :param endpoint: The endpoint of the service
        :param endpoint_type: The endpoint type of the service
        :param insecure: Turn off certificate validation
        :param cacert: CA Cert file path
        :return: a Cinder Client object
        :raise Exception: if the client cannot be created
        """
        ksession = keystone.KeystoneSession()
        if not cls.cinder_client:
            kwargs = {'region_name': region,
                      'session': ksession.get_session(),
                      'interface': endpoint_type}
            if service_name:
                kwargs['service_name'] = service_name
            if endpoint:
                kwargs['endpoint'] = endpoint
                if endpoint.startwith("https"):
                    kwargs['insecure'] = insecure
                    kwargs['cacert'] = cacert
            try:
                cls.cinder_client = cinder_client.Client(
                    CINDER_VERSION, **kwargs
                )
            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.exception("Error creating Cinder client.")
        return cls.cinder_client
示例#16
0
def get_all_volumes():
    creds = get_creds()
    ct = cinderc.Client(2, **creds)
    vol_list = ct.volumes.list()
    nt = novac.Client(2, **creds)
    ins_list = nt.servers.list()
    return render_template('volumes.html', **locals())
示例#17
0
 def _get_volume_client(self):
     return cinder_client.Client(
         self.CINDERCLIENT_VERSION,
         session=self.identity_client.session,
         endpoint_type='publicURL',
         region_name=self.conf.region,
         http_log_debug=True)
示例#18
0
    def setUp(self):
        super(ApiTestCase, self).setUp()

        neutron_patcher = mock.patch('neutronclient.v2_0.client.Client',
                                     autospec=True)
        self.neutron = neutron_patcher.start().return_value
        self.addCleanup(neutron_patcher.stop)

        nova_patcher = mock.patch('novaclient.client.Client')
        self.nova = mock.create_autospec(self.NOVACLIENT_SPEC_OBJ)
        self.novaclient_getter = nova_patcher.start()
        self.novaclient_getter.return_value = self.nova
        self.addCleanup(nova_patcher.stop)

        glance_patcher = mock.patch('glanceclient.client.Client')
        self.glance = mock.create_autospec(glanceclient.Client(endpoint='/v1'))
        glance_patcher.start().return_value = self.glance
        self.addCleanup(glance_patcher.stop)

        cinder_patcher = mock.patch('cinderclient.client.Client')
        self.cinder = mock.create_autospec(cinderclient.Client('1'))
        cinder_patcher.start().return_value = self.cinder
        self.addCleanup(cinder_patcher.stop)

        db_api_patcher = mock.patch('ec2api.db.api.IMPL',
                                    autospec=ec2api.db.sqlalchemy.api)
        self.db_api = db_api_patcher.start()
        self.addCleanup(db_api_patcher.stop)

        isotime_patcher = mock.patch('oslo_utils.timeutils.isotime')
        self.isotime = isotime_patcher.start()
        self.addCleanup(isotime_patcher.stop)

        self._conf = self.useFixture(config_fixture.Config())
        self.configure(fatal_exception_format_errors=True)
示例#19
0
def cinder(context):
    if cinderclient is None:
        return nova(context, 'volume')

    return cinderclient.Client('1',
                               session=context.session,
                               service_type='volume')
示例#20
0
    def __init__(self,
                 username,
                 api_key,
                 project_id,
                 auth_url,
                 poll_delay=None,
                 name_prefix='auto_backup_',
                 max_secs_gbi=None):
        super(BackupService, self).__init__()
        self.username = username
        self.api_key = api_key
        self.project_id = project_id
        self.auth_url = auth_url
        self.poll_delay = poll_delay or self.default_poll_deplay
        self.name_prefix = name_prefix

        # Some functionality requires API version 2
        self.client = client.Client(version=2,
                                    username=username,
                                    api_key=api_key,
                                    project_id=project_id,
                                    auth_url=auth_url)

        self.status_msg = ''
        self.max_secs_gbi = max_secs_gbi or 300

        if not self.HAS_SEARCH_OPTS:
            _LW('--all-tenants disabled, need cinderclient v%s', self.WANT_V)
示例#21
0
    def cinder(self):
        if cinderclient is None:
            return self.nova('volume')
        if self._cinder:
            return self._cinder

        con = self.context
        if self.auth_token is None:
            logger.error("Cinder connection failed, no auth_token!")
            return None

        args = {
            'service_type': 'volume',
            'auth_url': con.auth_url,
            'project_id': con.tenant_id,
            'username': None,
            'api_key': None
        }

        self._cinder = cinderclient.Client('1', **args)
        if con.password is not None:
            if self.context.region_name is None:
                management_url = self.url_for(service_type='volume')
            else:
                management_url = self.url_for(
                    service_type='volume',
                    attr='region',
                    filter_value=self.context.region_name)
        else:
            management_url = con.cinder_url + '/' + con.tenant_id
        self._cinder.client.auth_token = self.auth_token
        self._cinder.client.management_url = management_url

        return self._cinder
示例#22
0
文件: cinder.py 项目: tiansen87/nova
def cinderclient(context, microversion=None, skip_version_check=False):
    """Constructs a cinder client object for making API requests.

    :param context: The nova request context for auth.
    :param microversion: Optional microversion to check against the client.
        This implies that Cinder v3 is required for any calls that require a
        microversion. If the microversion is not available, this method will
        raise an CinderAPIVersionNotAvailable exception.
    :param skip_version_check: If True and a specific microversion is
        requested, the version discovery check is skipped and the microversion
        is used directly. This should only be used if a previous check for the
        same microversion was successful.
    """
    global _SESSION

    if not _SESSION:
        _SESSION = ks_loading.load_session_from_conf_options(
            CONF, nova.conf.cinder.cinder_group.name)

    url = None
    endpoint_override = None

    auth = service_auth.get_auth_plugin(context)
    service_type, service_name, interface = CONF.cinder.catalog_info.split(':')

    service_parameters = {'service_type': service_type,
                          'service_name': service_name,
                          'interface': interface,
                          'region_name': CONF.cinder.os_region_name}

    if CONF.cinder.endpoint_template:
        url = CONF.cinder.endpoint_template % context.to_dict()
        endpoint_override = url
    else:
        url = _SESSION.get_endpoint(auth, **service_parameters)

    # TODO(jamielennox): This should be using proper version discovery from
    # the cinder service rather than just inspecting the URL for certain string
    # values.
    version = cinder_client.get_volume_api_from_url(url)

    if version != '3':
        raise exception.UnsupportedCinderAPIVersion(version=version)

    version = '3.0'
    # Check to see a specific microversion is requested and if so, can it
    # be handled by the backing server.
    if microversion is not None:
        if skip_version_check:
            version = microversion
        else:
            version = _check_microversion(url, microversion)

    return cinder_client.Client(version,
                                session=_SESSION,
                                auth=auth,
                                endpoint_override=endpoint_override,
                                connect_retries=CONF.cinder.http_retries,
                                global_request_id=context.global_id,
                                **service_parameters)
    def __init__(self, auth_url, username, password, project_name,
                 project_domain_id, user_domain_id, region_name, ssl_verify,
                 http_timeout):
        self._auth_url = auth_url
        self._username = username
        self._password = password
        self._project_name = project_name
        self._project_domain_id = project_domain_id
        self._user_domain_id = user_domain_id
        self._region_name = region_name
        self._ssl_verify = ssl_verify

        self.auth = identity.Password(
            auth_url=self._auth_url,
            username=self._username,
            password=self._password,
            project_name=self._project_name,
            project_domain_id=self._project_domain_id,
            user_domain_id=self._user_domain_id)
        self.sess = session.Session(auth=self.auth,
                                    verify=self._ssl_verify,
                                    timeout=http_timeout)
        self.cinder = client.Client(DEFAULT_CINDER_CLIENT_VERSION,
                                    session=self.sess,
                                    region_name=self._region_name)
示例#24
0
    def __init__(self):
        auth = v2.Password(auth_url=env['OS_AUTH_URL'],
                           username=env['OS_USERNAME'],
                           password=env['OS_PASSWORD'],
                           tenant_id=env['OS_TENANT_ID'])
        sess = session.Session(auth=auth)
        self.keystone_client = keystone.Client(
            username=env['OS_USERNAME'],
            password=env['OS_PASSWORD'],
            tenant_id=env['OS_TENANT_ID'],
            auth_url=env['OS_AUTH_URL'],
            region_name=env['OS_REGION_NAME'])

        heat_url = self.keystone_client \
            .service_catalog.url_for(service_type='orchestration',
                                     endpoint_type='publicURL')

        self.nova_client = nova.Client('2.1',
                                       region_name=env['OS_REGION_NAME'],
                                       session=sess)
        self.cinder_client = cinder.Client('2',
                                           region_name=env['OS_REGION_NAME'],
                                           session=sess)
        self.glance_client = glance.Client('2',
                                           region_name=env['OS_REGION_NAME'],
                                           session=sess)
        self.neutron_client = neutron.Client(region_name=env['OS_REGION_NAME'],
                                             session=sess)
        self.heat_client = heat.Client('1',
                                       region_name=env['OS_REGION_NAME'],
                                       endpoint=heat_url,
                                       session=sess)
示例#25
0
    def cinder(self):
        if cinderclient is None:
            return None
        if self._cinder:
            return self._cinder

        con = self.context
        endpoint_type = self._get_client_option('cinder', 'endpoint_type')
        args = {
            'service_type': 'volume',
            'auth_url': con.auth_url,
            'project_id': con.tenant,
            'username': None,
            'api_key': None,
            'endpoint_type': endpoint_type,
            'cacert': self._get_client_option('cinder', 'ca_file'),
            'insecure': self._get_client_option('cinder', 'insecure')
        }

        self._cinder = cinderclient.Client('1', **args)
        management_url = self.url_for(service_type='volume',
                                      endpoint_type=endpoint_type)
        self._cinder.client.auth_token = self.auth_token
        self._cinder.client.management_url = management_url

        return self._cinder
def get_volume_list(project_to_migrate, cred, version = "new"):
    
    if version == "new":
        auth_url = cred["auth_url_2.5"]
        username = cred["username_2.5"]
        password = cred["password_2.5"]
        project_id = cred["project_id_2.5"]
        cert_loc = cred["openstack_cert_location_2.5"]
    else:
        auth_url = cred["auth_url_2.0"]
        username = cred["username_2.0"]
        password = cred["password_2.0"]
        project_id = cred["project_id_2.0"]
        cert_loc = ""
    
    
    auth = v3.Password(auth_url=auth_url, username=username, password=password, project_id=project_id, user_domain_id='default')
    sess = session.Session(auth=auth, verify=cert_loc)
    
    cinder = client.Client(2,session=sess)
    
    volumes = cinder.volumes.list(search_opts={'all_tenants': 1},detailed = True)
    
    
    volumes_to_migrate = []
    for volume in volumes:
        if project_to_migrate == volume.to_dict()['os-vol-tenant-attr:tenant_id']:
            volumes_to_migrate.append(volume)
    
  
    return volumes_to_migrate
示例#27
0
    def cinder(self):
        if cinderclient is None:
            return self.nova('volume')
        if self._cinder:
            return self._cinder

        con = self.context
        args = {
            'service_type': 'volume',
            'auth_url': con.auth_url,
            'project_id': con.tenant
        }

        if con.password is not None:
            args['username'] = con.username
            args['api_key'] = con.password
        elif con.auth_token is not None:
            args['username'] = None
            args['api_key'] = None
        else:
            logger.error("Cinder connection failed, "
                         "no password or auth_token!")
            return None
        logger.debug('cinder args %s', args)

        self._cinder = cinderclient.Client('1', **args)
        if con.password is None and con.auth_token is not None:
            management_url = self.url_for(service_type='volume')
            self._cinder.client.auth_token = con.auth_token
            self._cinder.client.management_url = management_url

        return self._cinder
示例#28
0
def killWorker(instanceId, volumeId):
    loader = loading.get_plugin_loader('password')

    auth = loader.load_from_options(
        auth_url=env['OS_AUTH_URL'],
        username=env['OS_USERNAME'],
        password=env['OS_PASSWORD'],
        project_name=env['OS_PROJECT_NAME'],
        project_domain_name=env['OS_USER_DOMAIN_NAME'],
        project_id=env['OS_PROJECT_ID'],
        user_domain_name=env['OS_USER_DOMAIN_NAME'])

    sess = session.Session(auth=auth)
    nova = client.Client('2.1', session=sess)
    cinder = ciclient.Client(
        '2', session=sess
    )  #user, pswd, project_name, keystone_link, region_name = region_name)
    print("deleting instance....")
    nova.servers.delete(instanceId)
    volume = cinder.volumes.get(volumeId)
    print(volume.status)
    while (str(volume.status) == 'migrating'
           or str(volume.status) == 'attached'
           or str(volume.status) == 'in-use'):
        volume = cinder.volumes.get(volume.id)
        time.sleep(0.5)
    print("deleting volume....")
    cinder.volumes.delete(volumeId)
示例#29
0
文件: openstack.py 项目: kjylmr/guts
    def do_setup(self, context):
        """Any initialization the destination driver does while starting."""
        super(OpenStackDestinationDriver, self).do_setup(context)
        auth_url = self.configuration.auth_url
        if auth_url is None:
            raise ValueError(_("Cannot authenticate without an auth_url"))
        username = self.configuration.username
        password = self.configuration.password
        tenant_name = self.configuration.tenant_name
        project_id = self.configuration.project_id
        user_domain_name = self.configuration.user_domain_name
        nova_api_version = self.configuration.nova_api_version
        cinder_api_version = self.configuration.cinder_api_version
        glance_api_version = self.configuration.glance_api_version
        keystone_version = self.configuration.keystone_version

        if keystone_version == 'v3':
            auth = v3.Password(auth_url=auth_url, username=username,
                               password=password, project_id=project_id,
                               user_domain_name=user_domain_name)
            sess = v3_session.Session(auth=auth)
        elif keystone_version == 'v2':
            auth = v2.Password(auth_url, username=username,
                               password=password, tenant_name=tenant_name)
            sess = v2_session.Session(auth=auth)

        self.nova = nova_client.Client(nova_api_version, session=sess)
        self.cinder = cinder_client.Client(cinder_api_version, session=sess)
        self.glance = glance_client.Client(glance_api_version, session=sess)
        self._initialized = True
示例#30
0
    def __init__(
        self,
        auth_url,
        username,
        password,
        project_name,
        project_domain_id,
        user_domain_id
    ):
        self._auth_url = auth_url
        self._username = username
        self._password = password
        self._project_name = project_name
        self._project_domain_id = project_domain_id
        self._user_domain_id = user_domain_id

        self.auth = identity.v3.Password(
            auth_url=self._auth_url,
            username=self._username,
            password=self._password,
            project_name=self._project_name,
            project_domain_id=self._project_domain_id,
            user_domain_id=self._user_domain_id
        )
        self.sess = session.Session(auth=self.auth)
        self.cinder = client.Client(
            DEFAULT_CINDER_CLIENT_VERSION,
            session=self.sess
        )