Пример #1
0
    def main(self, argv):
        parsed = self.parse_args(argv)
        if parsed == 0:
            return 0

        print(parsed)
        api_version, args = parsed

        # Short-circuit and deal with help command 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

        if not ((self.auth_plugin.opts.get('token')
                 or self.auth_plugin.opts.get('auth_token'))
                and self.auth_plugin.opts['endpoint']):
            if not self.auth_plugin.opts['username']:
                raise exc.CommandError("You must provide a username via "
                                       "either --os-username or via "
                                       "env[OS_USERNAME]")

            if not self.auth_plugin.opts['password']:
                raise exc.CommandError("You must provide a password via "
                                       "either --os-password or via "
                                       "env[OS_PASSWORD]")

            if self.no_project_and_domain_set(args):
                # steer users towards Keystone V3 API
                raise exc.CommandError("You must provide a project_id via "
                                       "either --os-project-id or via "
                                       "env[OS_PROJECT_ID] and "
                                       "a domain_name via either "
                                       "--os-user-domain-name or via "
                                       "env[OS_USER_DOMAIN_NAME] or "
                                       "a domain_id via either "
                                       "--os-user-domain-id or via "
                                       "env[OS_USER_DOMAIN_ID]")

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

        client_kwargs = vars(args)
        client_kwargs.update(self.auth_plugin.opts)
        client_kwargs['auth_plugin'] = self.auth_plugin

        client = asclient.get_client(api_version, **client_kwargs)
        # call whatever callback was selected
        try:
            args.func(client, args)
        except exc.HTTPUnauthorized:
            raise exc.CommandError("Invalid OpenStack Identity credentials.")
Пример #2
0
def _discover_auth_versions(session, auth_url):
    # discover the API versions the server is supporting based on the
    # given URL
    v2_auth_url = None
    v3_auth_url = None
    try:
        ks_discover = discover.Discover(session=session, auth_url=auth_url)
        v2_auth_url = ks_discover.url_for('2.0')
        v3_auth_url = ks_discover.url_for('3.0')
    except ks_exc.DiscoveryFailure:
        raise
    except exceptions.ClientException:
        # Identity service may not support discovery. In that case,
        # try to determine version from auth_url
        url_parts = urlparse.urlparse(auth_url)
        (scheme, netloc, path, params, query, fragment) = url_parts
        path = path.lower()
        if path.startswith('/v3'):
            v3_auth_url = auth_url
        elif path.startswith('/v2'):
            v2_auth_url = auth_url
        else:
            raise exc.CommandError('Unable to determine the Keystone '
                                   'version to authenticate with '
                                   'using the given auth_url.')
    return v2_auth_url, v3_auth_url
Пример #3
0
def _get_token_auth_ks_session(**kwargs):

    cacert = kwargs.pop('cacert', None)
    cert = kwargs.pop('cert', None)
    key = kwargs.pop('key', None)
    insecure = kwargs.pop('insecure', False)
    auth_url = kwargs.pop('auth_url', None)
    project_id = kwargs.pop('project_id', None)
    project_name = kwargs.pop('project_name', None)
    timeout = kwargs.get('timeout')
    token = kwargs['token']

    if insecure:
        verify = False
    else:
        verify = cacert or True

    if cert and key:
        # passing cert and key together is deprecated in favour of the
        # requests lib form of having the cert and key as a tuple
        cert = (cert, key)

    # create the keystone client session
    ks_session = session.Session(verify=verify, cert=cert, timeout=timeout)
    v2_auth_url, v3_auth_url = _discover_auth_versions(ks_session, auth_url)

    user_domain_name = kwargs.pop('user_domain_name', None)
    user_domain_id = kwargs.pop('user_domain_id', None)
    project_domain_name = kwargs.pop('project_domain_name', None)
    project_domain_id = kwargs.pop('project_domain_id', None)
    auth = None

    use_domain = (user_domain_id or user_domain_name or project_domain_id
                  or project_domain_name)
    use_v3 = v3_auth_url and (use_domain or (not v2_auth_url))
    use_v2 = v2_auth_url and not use_domain

    if use_v3:
        auth = v3_auth.Token(v3_auth_url,
                             token=token,
                             project_name=project_name,
                             project_id=project_id,
                             project_domain_name=project_domain_name,
                             project_domain_id=project_domain_id)
    elif use_v2:
        auth = v2_auth.Token(v2_auth_url,
                             token=token,
                             tenant_id=project_id,
                             tenant_name=project_name)
    else:
        raise exc.CommandError('Unable to determine the Keystone version '
                               'to authenticate with using the given '
                               'auth_url.')

    ks_session.auth = auth
    return ks_session
Пример #4
0
def do_user_billing_type_list(cc, args):
    '''List all User Plans'''
    try:
        user_billing_types = cc.user_billing_types.list()
    except exc.HTTPNotFound():
        raise exc.CommandError('Error: No User Billing Types Found!')
    else:
        field_labels = ['Id', 'User', 'Billing Type', 'Extra Fields']
        fields = ['id', 'user', 'billing_type', 'extra_fields']
        utils.print_list(user_billing_types, fields, field_labels, sortby=0)
Пример #5
0
def do_plan_list(cc, args):
    '''List all the available plans'''
    try:
        plans = cc.plans.list()
    except exc.HTTPNotFound():
        raise exc.CommandError('Error:No Plans Found!')
    else:
        field_labels = ['Id', 'Status', 'Code', 'Name', 'Billing Type', 'Rate']
        fields = ['id', 'status', 'code', 'name', 'billing_type', 'rate']
        utils.print_list(plans, fields, field_labels, sortby=0)
Пример #6
0
def do_service_types_list(cc, args):
    '''List all service types'''
    try:
        service_types = cc.service_types.list()
    except exc.HTTPNotFound():
        raise exc.CommandError('Error: No Service Types Found!')
    else:
        field_labels = ['Id', 'Name', 'Code', 'Units', 'Status']
        fields = ['id', 'name', 'code', 'units', 'status']
        utils.print_list(service_types, fields, field_labels, sortby=0)
Пример #7
0
def do_discount_type_list(cc, args):
    '''List all Discount Types'''
    try:
        discount_types = cc.discount_types.list()
    except exc.HTTPNotFound():
        raise exc.CommandError('Error: No Discount Types Found!')
    else:
        field_labels = ['Id', 'Status', 'Code', 'Name']
        fields = ['id', 'status', 'code', 'name']
        utils.print_list(discount_types, fields, field_labels, sortby=0)
Пример #8
0
 def do_help(self, args):
     """Display help about this program or one of its subcommands."""
     if getattr(args, 'command', None):
         if args.command in self.subcommands:
             self.subcommands[args.command].print_help()
         else:
             raise exc.CommandError("'%s' is not a valid subcommand" %
                                    args.command)
     else:
         self.parser.print_help()
Пример #9
0
def args_array_to_dict(kwargs, key_to_convert):
    values_to_convert = kwargs.get(key_to_convert)
    if values_to_convert:
        try:
            kwargs[key_to_convert] = dict(v.split("=", 1)
                                          for v in values_to_convert)
        except ValueError:
            raise exc.CommandError(
                '%s must be a list of key=value not "%s"' % (
                    key_to_convert, values_to_convert))
    return kwargs
Пример #10
0
def do_billing_type_get(cc, args):
    '''Display details of a billing type'''
    try:
        billing_type = cc.billing_types.get(args.billing_type_id)
    except exc.HTTPNotFound:
        raise exc.CommandError('Billing Type Not Found : %s' %
                               args.billing_type_id)
    else:
        field_labels = ['Id', 'Name', 'Status', 'Code']
        fields = ['id', 'name', 'status', 'code']
        data = dict((f, getattr(billing_type, f, '')) for f in fields)
        utils.print_dict(data, wrap=72)
Пример #11
0
def do_discount_type_get(cc, args):
    '''Get the details of a discount type'''
    try:
        discount_type = cc.discount_types.get(args.discount_type_id)
    except exc.HTTPNotFound:
        raise exc.CommandError('Discount Type Not Found : %s' %
                               args.discount_type_id)
    else:
        field_labels = ['Id', 'Status', 'Code', 'Name']
        fields = ['id', 'status', 'code', 'name']
        data = dict((f, getattr(discount_type, f, '')) for f in fields)
        utils.print_dict(data, wrap=72)
Пример #12
0
def do_service_type_get(cc, args):
    '''Get details of a specific service type'''
    try:
        service_type = cc.service_types.get(args.service_type_id)
    except exc.HTTPNotFound:
        raise exc.CommandError('Error: Service Type Not Found : %s' %
                               args.service_type_id)
    else:
        field_labels = ['Id', 'Name', 'Code', 'Units', 'Status']
        fields = ['id', 'name', 'code', 'units', 'status']
        data = dict((f, getattr(service_type, f, '')) for f in fields)
        utils.print_dict(data, wrap=72)
Пример #13
0
def do_billing_type_list(cc, args):
    """
    List the billing types
    """
    try:
        billing_types = cc.billing_types.list()
    except exc.HTTPNotFound():
        raise exc.CommandError('Error:No Billing Types Found!')
    else:
        field_labels = ['Id', 'Name', 'Status', 'Code']
        fields = ['id', 'name', 'status', 'code']
        utils.print_list(billing_types, fields, field_labels, sortby=0)
Пример #14
0
def do_plan_get(cc, args):
    '''Get the details of a plan'''
    print('Get plan details')
    try:
        plan = cc.plans.get(args.plan_id)
    except exc.HTTPNotFound:
        raise exc.CommandError('Plan Not Found : %s' % args.plan_id)
    else:
        field_labels = ['Id', 'Status', 'Code', 'Name', 'Billing Type', 'Rate']
        fields = ['id', 'status', 'code', 'name', 'billing_type', 'rate']
        data = dict((f, getattr(plan, f, '')) for f in fields)
        utils.print_dict(data, wrap=72)
Пример #15
0
def do_user_billing_type_get(cc, args):
    '''Get details of a specific service type'''
    try:
        user_billing_type = cc.user_billing_types.get(
            args.user_billing_type_id)
    except exc.HTTPNotFound:
        raise exc.CommandError(
            'Error:User Billing Type Mapping Not Found : %s' %
            args.user_billing_type_id)
    else:
        field_labels = ['Id', 'User', 'Billing Type', 'Extra Fields']
        fields = ['id', 'user', 'billing_type', 'extra_fields']
        data = dict((f, getattr(user_billing_type, f, '')) for f in fields)
        utils.print_dict(data, wrap=72)
Пример #16
0
def do_discount_list(cc, args):
    '''List all discounts'''
    try:
        discounts = cc.discounts.list()
    except exc.HTTPNotFound():
        raise exc.CommandError('Error: No Discounts Found!')
    else:
        field_labels = [
            'Id', 'Code', 'Name', 'Discount_Type_Id', 'Discount_Type_Code',
            'Expiration Date', 'Amt', 'Usage Count'
        ]
        fields = [
            'id', 'code', 'name', 'discount_type_id', 'discount_type_code',
            'expiration_date', 'amt', 'usage_count'
        ]
        utils.print_list(discounts, fields, field_labels, sortby=0)
Пример #17
0
def do_discount_mappings_list(cc, args):
    '''List all Discount Mappings'''
    try:
        discount_mapping = cc.discount_mappings.list()
    except exc.HTTPNotFound():
        raise exc.CommandError('Error: No Discount Mappings Found!')
    else:
        field_labels = [
            'Discount_Type_Id', 'Code', 'Name', 'User', 'Apply Type',
            'User Plan', 'Discount Id', 'Expiration Date', 'Amt'
        ]
        fields = [
            'discount_type_id', 'code', 'name', 'user', 'apply_type',
            'user_plan', 'discount_id', 'expiration_date', 'amt'
        ]
        utils.print_list(discount_mapping, fields, field_labels, sortby=0)
Пример #18
0
def do_invoice_list(cc, args):
    '''List Invoices'''
    try:
        invoices = cc.invoices.list()
    except exc.HTTPNotFound():
        raise exc.CommandError('Error: No Invoices Found!')
    else:
        field_labels = [
            'Code', 'Date', 'From', 'To', 'User', 'Total', 'Paid Amount',
            'Balance'
        ]
        fields = [
            'inv_code', 'inv_date', 'inv_from', 'inv_to', 'user', 'total_amt',
            'amt_paid', 'balance_amt'
        ]
        utils.print_list(invoices, fields, field_labels, sortby=0)
Пример #19
0
def do_user_plans_list(cc, args):
    '''List all User Plans'''
    try:
        user_plans = cc.user_plans.list()
    except exc.HTTPNotFound():
        raise exc.CommandError('Error: No User Plans Found!')
    else:
        field_labels = [
            'Id', 'User', 'Plan Id', 'Status', 'Creation Date', 'Quantity',
            'Contract Period'
        ]
        fields = [
            'id', 'user', 'plan_id', 'status', 'created_on', 'qty',
            'contract_period'
        ]
        utils.print_list(user_plans, fields, field_labels, sortby=0)
Пример #20
0
def do_invoice_get(cc, args):
    '''Get details of a invoice'''
    try:
        invoice = cc.invoices.get(args.invoice_id)
    except exc.HTTPNotFound:
        raise exc.CommandError('Invoice Not Found : %s' % args.invoice_id)
    else:
        field_labels = [
            'Code', 'Date', 'From', 'To', 'User', 'Total', 'Paid Amount',
            'Balance'
        ]
        fields = [
            'inv_code', 'inv_date', 'inv_from', 'inv_to', 'user', 'total_amt',
            'amt_paid', 'balance_amt'
        ]
        data = dict((f, getattr(invoice, f, '')) for f in fields)
        utils.print_dict(data, wrap=72)
Пример #21
0
def args_array_to_list_of_dicts(kwargs, key_to_convert):
    """Converts ['a=1;b=2','c=3;d=4'] to [{a:1,b:2},{c:3,d:4}]."""
    values_to_convert = kwargs.get(key_to_convert)
    if values_to_convert:
        try:
            kwargs[key_to_convert] = []
            for lst in values_to_convert:
                pairs = lst.split(";")
                dct = dict()
                for pair in pairs:
                    kv = pair.split("=", 1)
                    dct[kv[0]] = kv[1].strip(" \"'")  # strip spaces and quotes
                kwargs[key_to_convert].append(dct)
        except Exception:
            raise exc.CommandError(
                '%s must be a list of key1=value1;key2=value2;... not "%s"' % (
                    key_to_convert, values_to_convert))
    return kwargs
Пример #22
0
def do_user_plan_get(cc, args):
    '''Get details of a specific service type'''
    try:
        user_plan = cc.user_plans.get(args.user_plan_id)
    except exc.HTTPNotFound:
        raise exc.CommandError('Error: User Plan Mapping Not Found : %s' %
                               args.user_plan_id)
    else:
        field_labels = [
            'Id', 'User', 'Plan Id', 'Status', 'Creation Date', 'Quantity',
            'Contract Period'
        ]
        fields = [
            'id', 'user', 'plan_id', 'status', 'created_on', 'qty',
            'contract_period'
        ]
        data = dict((f, getattr(user_plan, f, '')) for f in fields)
        utils.print_dict(data, wrap=72)
Пример #23
0
def do_discount_get(cc, args):
    '''Get the details of a individual discount'''
    print('Get discount details')
    try:
        discount = cc.discounts.get(args.discount_id)
    except exc.HTTPNotFound:
        raise exc.CommandError('Discount Not Found : %s' % args.discount_id)
    else:
        field_labels = [
            'Id', 'Code', 'Name', 'Discount_Type_Id', 'Discount_Type_Code',
            'Expiration Date', 'Amt', 'Usage Count'
        ]
        fields = [
            'id', 'code', 'name', 'discount_type_id', 'discount_type_code',
            'expiration_date', 'amt', 'usage_count'
        ]
        data = dict((f, getattr(discount, f, '')) for f in fields)
        utils.print_dict(data, wrap=72)
Пример #24
0
def do_discount_mapping_get(cc, args):
    '''Get the details of an individual Discount Mapping'''
    try:
        print(args)
        discount_mapping = cc.discount_mappings.get(args.discount_mapping_id)
    except exc.HTTPNotFound:
        raise exc.CommandError('Error: Discount Mapping Not Found : %s' %
                               args.discount_mapping_id)
    else:
        field_labels = [
            'Discount_Type_Id', 'Code', 'Name', 'User', 'Apply Type',
            'User Plan', 'Discount Id', 'Expiration Date', 'Amt'
        ]
        fields = [
            'discount_type_id', 'code', 'name', 'user', 'apply_type',
            'user_plan', 'discount_id', 'expiration_date', 'amt'
        ]
        data = dict((f, getattr(discount_mapping, f, '')) for f in fields)
        utils.print_dict(data, wrap=72)
Пример #25
0
def find_resource(manager, name_or_id):
    """Helper for the _find_* methods."""
    # first try to get entity as integer id
    try:
        if isinstance(name_or_id, int) or name_or_id.isdigit():
            return manager.get(int(name_or_id))
    except exc.HTTPNotFound:
        pass

    # now try to get entity as uuid
    try:
        uuid.UUID(str(name_or_id))
        return manager.get(name_or_id)
    except (ValueError, exc.HTTPNotFound):
        pass

    # finally try to find entity by name
    try:
        return manager.find(name=name_or_id)
    except exc.HTTPNotFound:
        msg = "No %s with a name or ID of '%s' exists." % \
              (manager.resource_class.__name__.lower(), name_or_id)
        raise exc.CommandError(msg)
Пример #26
0
def _get_keystone_session(**kwargs):
    # TODO(fabgia): the heavy lifting here should be really done by Keystone.
    # Unfortunately Keystone does not support a richer method to perform
    # discovery and return a single viable URL. A bug against Keystone has
    # been filed: https://bugs.launchpad.net/python-keystoneclient/+bug/1330677

    # first create a Keystone session
    cacert = kwargs.pop('cacert', None)
    cert = kwargs.pop('cert', None)
    key = kwargs.pop('key', None)
    insecure = kwargs.pop('insecure', False)
    auth_url = kwargs.pop('auth_url', None)
    project_id = kwargs.pop('project_id', None)
    project_name = kwargs.pop('project_name', None)
    timeout = kwargs.get('timeout')

    if insecure:
        verify = False
    else:
        verify = cacert or True

    if cert and key:
        # passing cert and key together is deprecated in favour of the
        # requests lib form of having the cert and key as a tuple
        cert = (cert, key)

    # create the keystone client session
    ks_session = session.Session(verify=verify, cert=cert, timeout=timeout)
    v2_auth_url, v3_auth_url = _discover_auth_versions(ks_session, auth_url)

    username = kwargs.pop('username', None)
    user_id = kwargs.pop('user_id', None)
    user_domain_name = kwargs.pop('user_domain_name', None)
    user_domain_id = kwargs.pop('user_domain_id', None)
    project_domain_name = kwargs.pop('project_domain_name', None)
    project_domain_id = kwargs.pop('project_domain_id', None)
    auth = None

    use_domain = (user_domain_id or user_domain_name or project_domain_id
                  or project_domain_name)
    use_v3 = v3_auth_url and (use_domain or (not v2_auth_url))
    use_v2 = v2_auth_url and not use_domain

    if use_v3:
        # the auth_url as v3 specified
        # e.g. http://no.where:5000/v3
        # Keystone will return only v3 as viable option
        auth = v3_auth.Password(v3_auth_url,
                                username=username,
                                password=kwargs.pop('password', None),
                                user_id=user_id,
                                user_domain_name=user_domain_name,
                                user_domain_id=user_domain_id,
                                project_name=project_name,
                                project_id=project_id,
                                project_domain_name=project_domain_name,
                                project_domain_id=project_domain_id)
    elif use_v2:
        # the auth_url as v2 specified
        # e.g. http://no.where:5000/v2.0
        # Keystone will return only v2 as viable option
        auth = v2_auth.Password(v2_auth_url,
                                username,
                                kwargs.pop('password', None),
                                tenant_id=project_id,
                                tenant_name=project_name)
    else:
        raise exc.CommandError('Unable to determine the Keystone version '
                               'to authenticate with using the given '
                               'auth_url.')

    ks_session.auth = auth
    return ks_session
Пример #27
0
 def __call__(self, parser, namespace, values, option_string=None):
     values = values or getattr(namespace, self.dest)
     if not values or values.isspace():
         raise exc.CommandError('%s should not be empty' % self.dest)
     setattr(namespace, self.dest, values)