Beispiel #1
0
    def _create_identity_server(self):
        # NOTE(jamielennox): Loading Session here should be exactly the
        # same as calling Session.load_from_conf_options(CONF, GROUP)
        # however we can't do that because we have to use _conf_get to
        # support the paste.ini options.
        sess = session_loading.Session().load_from_options(
            cert=self._conf_get('certfile'),
            key=self._conf_get('keyfile'),
            cacert=self._conf_get('cafile'),
            insecure=self._conf_get('insecure'),
            timeout=self._conf_get('http_connect_timeout'),
            user_agent=self._build_useragent_string())

        auth_plugin = self._get_auth_plugin()

        adap = adapter.Adapter(
            sess,
            auth=auth_plugin,
            service_type='identity',
            interface='admin',
            region_name=self._conf_get('region_name'),
            connect_retries=self._conf_get('http_request_max_retries'))

        auth_version = self._conf_get('auth_version')
        if auth_version is not None:
            auth_version = discover.normalize_version_number(auth_version)
        return _identity.IdentityServer(
            self.log,
            adap,
            include_service_catalog=self._include_service_catalog,
            requested_auth_version=auth_version)
Beispiel #2
0
def _create_glance_client(context, netloc, use_ssl):
    """Instantiate a new glanceclient.Client object."""
    params = {'global_request_id': context.global_id}

    if use_ssl and CONF.auth_strategy == 'noauth':
        params = {'insecure': CONF.glance_api_insecure,
                  'cacert': CONF.glance_ca_certificates_file,
                  'timeout': CONF.glance_request_timeout,
                  'split_loggers': CONF.split_loggers
                  }
    if CONF.auth_strategy == 'keystone':
        global _SESSION
        if not _SESSION:
            config_options = {'insecure': CONF.glance_api_insecure,
                              'cacert': CONF.glance_ca_certificates_file,
                              'timeout': CONF.glance_request_timeout,
                              'cert': CONF.glance_certfile,
                              'key': CONF.glance_keyfile,
                              'split_loggers': CONF.split_loggers
                              }
            _SESSION = ks_session.Session().load_from_options(**config_options)

        auth = service_auth.get_auth_plugin(context)
        params['auth'] = auth
        params['session'] = _SESSION

    scheme = 'https' if use_ssl else 'http'
    endpoint = '%s://%s' % (scheme, netloc)
    return glanceclient.Client('2', endpoint, **params)
Beispiel #3
0
    def _get_ignore_projects(self, conf):
        if 'auth_type' not in conf:
            LOG.info("'auth_type' is not set assuming ignore_projects are "
                     "only project uuid.")
            return list_from_csv(conf.get('ignore_projects'))

        if 'ignore_projects' in conf:
            ignore_projects = list_from_csv(conf.get('ignore_projects'))
        else:
            ignore_projects = self.DEFAULT_IGNORE_PROJECT_NAMES

        if not ignore_projects:
            return []

        def opt_getter(opt):
            # TODO(sileht): This method does not support deprecated opt names
            val = conf.get(opt.name)
            if val is None:
                val = conf.get(opt.dest)
            return val

        auth_type = conf.get('auth_type')
        plugin = ksa_base.get_plugin_loader(auth_type)

        auth = plugin.load_from_options_getter(opt_getter)
        session = ksa_session.Session().load_from_options_getter(
            opt_getter, auth=auth)
        client = KeystoneClientLoader().load_from_options_getter(
            opt_getter, session=session)

        projects = []
        for name_or_id in ignore_projects:
            projects.extend(self._get_keystone_projects(client, name_or_id))
        return projects
    def _create_session(self, **kwargs):
        # NOTE(jamielennox): Loading Session here should be exactly the
        # same as calling Session.load_from_conf_options(CONF, GROUP)
        # however we can't do that because we have to use _conf.get to
        # support the paste.ini options.
        kwargs.setdefault('cert', self._conf.get('certfile'))
        kwargs.setdefault('key', self._conf.get('keyfile'))
        kwargs.setdefault('cacert', self._conf.get('cafile'))
        kwargs.setdefault('insecure', self._conf.get('insecure'))
        kwargs.setdefault('timeout', self._conf.get('http_connect_timeout'))
        kwargs.setdefault('user_agent', self._conf.user_agent)

        return session_loading.Session().load_from_options(**kwargs)
def main():
    cfg.CONF(args=sys.argv[1:],
             default_config_files=DEFAULT_CONFIG_FILES)
    common_config.setup_logging()
    config.register_infoblox_ipam_opts(cfg.CONF)
    grid_id = cfg.CONF.infoblox.cloud_data_center_id
    config.register_infoblox_grid_opts(cfg.CONF, grid_id)

    try:
        credentials, version = get_credentials()
    except KeyError:
        print("\nYou must provide an admin user credentials in the shell "
              "environment.\nPlease export variables such as env[OS_USERNAME],"
              " env[OS_PASSWORD], env[OS_AUTH_URL], env[OS_TENANT_NAME] or "
              "env[OS_PROJECT_NAME]\n")
        return
    password_creds = credentials.copy()
    password_creds.pop('region_name', None)

    # keystoneauth1 provides generic api to create auth object based on the
    # arguments passed.
    auth = generic.Password(**password_creds)

    # Load keystone session using the ssl options which are in environment
    session = load_session.Session().load_from_options(**get_session_options())
    session.auth = auth
    if version == '3':
        client = client_3.Client(session=session)
    else:
        client = client_2_0.Client(session=session)

    context = neutron_context.get_admin_context()
    context.auth_token = client.ec2.client.get_token()
    context.user_id = client.ec2.client.get_user_id()
    context.tenant_id = client.ec2.client.get_project_id()

    grid_manager = grid.GridManager(context)
    grid_manager.sync(force_sync=True)
    context.session.expunge_all()

    credentials['session'] = session
    for key in ('user_domain_id', 'project_domain_id'):
        credentials.pop(key, None)

    sync_neutron_to_infoblox(context, credentials, grid_manager)
Beispiel #6
0
from oslo_config import cfg
from keystoneauth1.loading import session as session_loading
from keystonemiddleware._common import config
from keystonemiddleware.auth_token import list_opts

CONF = cfg.CONF

CONF(project='test', default_config_files=['/etc/nova/nova.conf'])

conf = config.Config("auth_token", "keystone_authtoken", list_opts(), {})

group = conf.get('auth_section') or "keystone_authtoken"

plugin_name = (conf.get('auth_type', group=group)
               or conf.paste_overrides.get('auth_plugin'))

plugin_loader = loading.get_plugin_loader(plugin_name)
plugin_opts = loading.get_auth_plugin_conf_options(plugin_loader)

conf.oslo_conf_obj.register_opts(plugin_opts, group=group)
getter = lambda opt: conf.get(opt.dest, group=group)
auth = plugin_loader.load_from_options_getter(getter)

adap = adapter.Adapter(session_loading.Session().load_from_options(),
                       auth=auth,
                       service_type='identity',
                       interface='admin',
                       region_name=conf.get('region_name'),
                       connect_retries=conf.get('http_request_max_retries'))

print(adap.get_endpoint(version=(3, 0)))
Beispiel #7
0
 def _load_client(plugin, ssl_settings):
     # load client from auth settings and user plugin
     sess = session.Session().load_from_options(
         auth=plugin, **ssl_settings)
     return ks_client.Client(session=sess)
Beispiel #8
0
    def main(self, argv):

        # Parse args once to find version and debug settings
        parser = self.get_base_parser()
        (options, args) = parser.parse_known_args(argv)
        self.setup_debugging(options.debug)
        self.options = options

        # NOTE(dtroyer): Hackery to handle --endpoint_type due to argparse
        #                thinking usage-list --end is ambiguous; but it
        #                works fine with only --endpoint-type present
        #                Go figure.
        if '--endpoint_type' in argv:
            spot = argv.index('--endpoint_type')
            argv[spot] = '--endpoint-type'

        subcommand_parser = (
            self.get_subcommand_parser(options.sahara_api_version)
        )
        self.parser = subcommand_parser

        if options.help or not argv:
            subcommand_parser.print_help()
            return 0

        args = subcommand_parser.parse_args(argv)

        # Short-circuit and deal with help right away.
        if args.func == self.do_help:
            self.do_help(args)
            return 0
        elif args.func == self.do_bash_completion:
            self.do_bash_completion(args)
            return 0

#        (os_username, os_tenant_name, os_tenant_id, os_auth_url,
#                os_region_name, os_auth_system, endpoint_type, insecure,
#                service_type, service_name, volume_service_name,
#                bypass_url, os_cache, cacert) = ( #, timeout) = (
#                        args.os_username,
#                        args.os_tenant_name, args.os_tenant_id,
#                        args.os_auth_url,
#                        args.os_region_name,
#                        args.os_auth_system,
#                        args.endpoint_type, args.insecure,
#                        args.service_type,
#                        args.service_name, args.volume_service_name,
#                        args.bypass_url, args.os_cache,
#                        args.os_cacert, args.timeout)
        (os_username, os_tenant_name, os_tenant_id,
         os_auth_url, os_auth_system, endpoint_type,
         service_type, bypass_url, os_cacert, insecure, region_name) = (
            (args.os_username, args.os_tenant_name, args.os_tenant_id,
             args.os_auth_url, args.os_auth_system, args.endpoint_type,
             args.service_type, args.bypass_url, args.os_cacert, args.insecure,
             args.region_name)
        )

        if os_auth_system and os_auth_system != "keystone":
            auth_plugin = auth.load_plugin(os_auth_system)
        else:
            auth_plugin = None

        # Fetched and set later as needed
        os_password = None

        if not endpoint_type:
            endpoint_type = DEFAULT_ENDPOINT_TYPE

        if not service_type:
            service_type = DEFAULT_SERVICE_TYPE
# NA - there is only one service this CLI accesses
#            service_type = utils.get_service_type(args.func) or service_type

        # FIXME(usrleon): Here should be restrict for project id same as
        # for os_username or os_password but for compatibility it is not.
        if not cliutils.isunauthenticated(args.func):
            if auth_plugin:
                auth_plugin.parse_opts(args)

            if not auth_plugin or not auth_plugin.opts:
                if not os_username:
                    raise exc.CommandError("You must provide a username "
                                           "via either --os-username or "
                                           "env[OS_USERNAME]")

            if not os_auth_url:
                if os_auth_system and os_auth_system != 'keystone':
                    os_auth_url = auth_plugin.get_auth_url()

            if not os_auth_url:
                    raise exc.CommandError("You must provide an auth url "
                                           "via either --os-auth-url or "
                                           "env[OS_AUTH_URL] or specify an "
                                           "auth_system which defines a "
                                           "default url with --os-auth-system "
                                           "or env[OS_AUTH_SYSTEM]")

# NA
#        if (options.os_compute_api_version and
#                options.os_compute_api_version != '1.0'):
#            if not os_tenant_name and not os_tenant_id:
#                raise exc.CommandError("You must provide a tenant name "
#                        "or tenant id via --os-tenant-name, "
#                        "--os-tenant-id, env[OS_TENANT_NAME] "
#                        "or env[OS_TENANT_ID]")
#
#            if not os_auth_url:
#                raise exc.CommandError("You must provide an auth url "
#                        "via either --os-auth-url or env[OS_AUTH_URL]")

# NOTE: The Sahara client authenticates when you create it. So instead of
#       creating here and authenticating later, which is what the novaclient
#       does, we just create the client later.

        # Now check for the password/token of which pieces of the
        # identifying keyring key can come from the underlying client
        if not cliutils.isunauthenticated(args.func):
            # NA - Client can't be used with SecretsHelper
            # helper = SecretsHelper(args, self.cs.client)
            if (auth_plugin and auth_plugin.opts and
                    "os_password" not in auth_plugin.opts):
                use_pw = False
            else:
                use_pw = True

#            tenant_id, auth_token, management_url = (helper.tenant_id,
#                                                     helper.auth_token,
#                                                     helper.management_url)
#
#            if tenant_id and auth_token and management_url:
#                self.cs.client.tenant_id = tenant_id
#                self.cs.client.auth_token = auth_token
#                self.cs.client.management_url = management_url
#                # authenticate just sets up some values in this case, no REST
#                # calls
#                self.cs.authenticate()
            if use_pw:
                # Auth using token must have failed or not happened
                # at all, so now switch to password mode and save
                # the token when its gotten... using our keyring
                # saver
                # os_password = helper.password
                os_password = args.os_password
                if not os_password:
                    raise exc.CommandError(
                        'Expecting a password provided via either '
                        '--os-password, env[OS_PASSWORD], or '
                        'prompted response')
#                self.cs.client.password = os_password
#                self.cs.client.keyring_saver = helper

        # V3 stuff
        project_info_provided = (self.options.os_tenant_name or
                                 self.options.os_tenant_id or
                                 (self.options.os_project_name and
                                  (self.options.os_project_domain_name or
                                   self.options.os_project_domain_id)) or
                                 self.options.os_project_id)

        if (not project_info_provided):
            raise exc.CommandError(
                ("You must provide a tenant_name, tenant_id, "
                 "project_id or project_name (with "
                 "project_domain_name or project_domain_id) via "
                 "  --os-tenant-name (env[OS_TENANT_NAME]),"
                 "  --os-tenant-id (env[OS_TENANT_ID]),"
                 "  --os-project-id (env[OS_PROJECT_ID])"
                 "  --os-project-name (env[OS_PROJECT_NAME]),"
                 "  --os-project-domain-id "
                 "(env[OS_PROJECT_DOMAIN_ID])"
                 "  --os-project-domain-name "
                 "(env[OS_PROJECT_DOMAIN_NAME])"))

        if not os_auth_url:
            raise exc.CommandError(
                "You must provide an auth url "
                "via either --os-auth-url or env[OS_AUTH_URL]")

        keystone_session = None
        keystone_auth = None
        if not auth_plugin:
            project_id = args.os_project_id or args.os_tenant_id
            project_name = args.os_project_name or args.os_tenant_name

            keystone_session = (session.Session().
                                load_from_argparse_arguments(args))
            keystone_auth = self._get_keystone_auth(
                keystone_session,
                args.os_auth_url,
                username=args.os_username,
                user_id=args.os_user_id,
                user_domain_id=args.os_user_domain_id,
                user_domain_name=args.os_user_domain_name,
                password=args.os_password,
                auth_token=args.os_auth_token,
                project_id=project_id,
                project_name=project_name,
                project_domain_id=args.os_project_domain_id,
                project_domain_name=args.os_project_domain_name)

        self.cs = client.Client(username=os_username,
                                api_key=os_password,
                                project_id=os_tenant_id,
                                project_name=os_tenant_name,
                                auth_url=os_auth_url,
                                sahara_url=bypass_url,
                                endpoint_type=endpoint_type,
                                session=keystone_session,
                                auth=keystone_auth,
                                cacert=os_cacert,
                                insecure=insecure,
                                service_type=service_type,
                                region_name=region_name)

        args.func(self.cs, args)
Beispiel #9
0
    def get_base_parser(self):
        parser = SaharaClientArgumentParser(
            prog='sahara',
            description=__doc__.strip(),
            epilog='See "sahara help COMMAND" '
                   'for help on a specific command.',
            add_help=False,
            formatter_class=OpenStackHelpFormatter,
        )

        # Global arguments
        parser.add_argument('-h', '--help',
                            action='store_true',
                            help=argparse.SUPPRESS)

        parser.add_argument('--version',
                            action='version',
                            version=version.version_info.version_string())

        parser.add_argument('--debug',
                            default=False,
                            action='store_true',
                            help="Print debugging output.")

        parser.add_argument('--os-cache',
                            default=strutils.bool_from_string(
                                cliutils.env('OS_CACHE', default=False)),
                            action='store_true',
                            help="Use the auth token cache. Defaults to False "
                            "if env[OS_CACHE] is not set.")


# TODO(mattf) - add get_timings support to Client
#        parser.add_argument('--timings',
#            default=False,
#            action='store_true',
#            help="Print call timing info")

# TODO(mattf) - use timeout
#        parser.add_argument('--timeout',
#            default=600,
#            metavar='<seconds>',
#            type=positive_non_zero_float,
#            help="Set HTTP call timeout (in seconds)")

        parser.add_argument('--region-name',
                            metavar='<region-name>',
                            default=cliutils.env('SAHARA_REGION_NAME',
                                                 'OS_REGION_NAME'),
                            help='Defaults to env[OS_REGION_NAME].')
        parser.add_argument('--region_name',
                            help=argparse.SUPPRESS)

        parser.add_argument('--service-type',
                            metavar='<service-type>',
                            help='Defaults to data-processing for all '
                                 'actions.')
        parser.add_argument('--service_type',
                            help=argparse.SUPPRESS)

# NA
#        parser.add_argument('--service-name',
#            metavar='<service-name>',
#            default=utils.env('SAHARA_SERVICE_NAME'),
#            help='Defaults to env[SAHARA_SERVICE_NAME]')
#        parser.add_argument('--service_name',
#            help=argparse.SUPPRESS)

# NA
#        parser.add_argument('--volume-service-name',
#            metavar='<volume-service-name>',
#            default=utils.env('NOVA_VOLUME_SERVICE_NAME'),
#            help='Defaults to env[NOVA_VOLUME_SERVICE_NAME]')
#        parser.add_argument('--volume_service_name',
#            help=argparse.SUPPRESS)

        parser.add_argument('--endpoint-type',
                            metavar='<endpoint-type>',
                            default=cliutils.env(
                                'SAHARA_ENDPOINT_TYPE',
                                'OS_ENDPOINT_TYPE',
                                default=DEFAULT_ENDPOINT_TYPE),
                            help=('Defaults to env[SAHARA_ENDPOINT_TYPE] or'
                                  ' env[OS_ENDPOINT_TYPE] or ')
                            + DEFAULT_ENDPOINT_TYPE + '.')
        # NOTE(dtroyer): We can't add --endpoint_type here due to argparse
        #                thinking usage-list --end is ambiguous; but it
        #                works fine with only --endpoint-type present
        #                Go figure.  I'm leaving this here for doc purposes.
        # parser.add_argument('--endpoint_type',
        #    help=argparse.SUPPRESS)

        parser.add_argument('--sahara-api-version',
                            metavar='<sahara-api-ver>',
                            default=cliutils.env(
                                'SAHARA_API_VERSION',
                                default=DEFAULT_API_VERSION),
                            help='Accepts "api", '
                                 'defaults to env[SAHARA_API_VERSION].')
        parser.add_argument('--sahara_api_version',
                            help=argparse.SUPPRESS)

        parser.add_argument('--bypass-url',
                            metavar='<bypass-url>',
                            default=cliutils.env('BYPASS_URL', default=None),
                            dest='bypass_url',
                            help="Use this API endpoint instead of the "
                            "Service Catalog.")
        parser.add_argument('--bypass_url',
                            help=argparse.SUPPRESS)

        parser.add_argument('--os-tenant-name',
                            default=cliutils.env('OS_TENANT_NAME'),
                            help='Defaults to env[OS_TENANT_NAME].')

        parser.add_argument('--os-tenant-id',
                            default=cliutils.env('OS_TENANT_ID'),
                            help='Defaults to env[OS_TENANT_ID].')

        parser.add_argument('--os-auth-system',
                            default=cliutils.env('OS_AUTH_SYSTEM'),
                            help='Defaults to env[OS_AUTH_SYSTEM].')

        parser.add_argument('--os-auth-token',
                            default=cliutils.env('OS_AUTH_TOKEN'),
                            help='Defaults to env[OS_AUTH_TOKEN].')

        # Use Keystoneclient/Keystoneauth API to parse authentication arguments
        session.Session().register_argparse_arguments(parser)
        identity.Password.register_argparse_arguments(parser)

        return parser