def take_action(self, parsed_args):
        LOG.debug("take_action({0})".format(parsed_args))
        client = self.app.client_manager.application_catalog
        filter_args = {
            "include_disabled": getattr(parsed_args,
                                        'include_disabled', False),
            "owned": getattr(parsed_args, 'owned', False),
        }
        if parsed_args:
            if parsed_args.limit < 0:
                raise exceptions.CommandError(
                    '--limit parameter must be non-negative')
            if parsed_args.limit != 0:
                filter_args['limit'] = parsed_args.limit
            if parsed_args.marker:
                filter_args['marker'] = parsed_args.marker
            if parsed_args.search:
                filter_args['search'] = parsed_args.search
            if parsed_args.name:
                filter_args['name'] = parsed_args.name
            if parsed_args.fqn:
                filter_args['fqn'] = parsed_args.fqn
            if parsed_args.type:
                filter_args['type'] = parsed_args.type
            if parsed_args.category:
                filter_args['category'] = parsed_args.category
            if parsed_args.class_name:
                filter_args['class_name'] = parsed_args.class_name
            if parsed_args.tag:
                filter_args['tag'] = parsed_args.tag

        data = client.packages.filter(**filter_args)

        columns = ('id', 'name', 'fully_qualified_name', 'author', 'active',
                   'is public', 'type', 'version')
        column_headers = [c.capitalize() for c in columns]
        if not parsed_args or parsed_args.limit == 0:
            return (
                column_headers,
                list(utils.get_item_properties(
                    s,
                    columns,
                ) for s in data)
            )
        else:
            return (
                column_headers,
                list(utils.get_item_properties(
                    s,
                    columns,
                ) for s in itertools.islice(data, parsed_args.limit))
            )
    def take_action(self, parsed_args):

        compute_client = self.app.client_manager.compute
        volume_client = self.app.client_manager.volume

        project_id = None
        if parsed_args.project is not None:
            identity_client = self.app.client_manager.identity
            if parsed_args.domain is not None:
                domain = identity_common.find_domain(identity_client,
                                                     parsed_args.domain)
                project_id = utils.find_resource(identity_client.projects,
                                                 parsed_args.project,
                                                 domain_id=domain.id).id
            else:
                project_id = utils.find_resource(identity_client.projects,
                                                 parsed_args.project).id

        compute_limits = None
        volume_limits = None

        if self.app.client_manager.is_compute_endpoint_enabled():
            compute_limits = compute_client.limits.get(parsed_args.is_reserved,
                                                       tenant_id=project_id)

        if self.app.client_manager.is_volume_endpoint_enabled(volume_client):
            volume_limits = volume_client.limits.get()

        data = []
        if parsed_args.is_absolute:
            if compute_limits:
                data.append(compute_limits.absolute)
            if volume_limits:
                data.append(volume_limits.absolute)
            columns = ["Name", "Value"]
            return (columns, (utils.get_item_properties(s, columns)
                              for s in itertools.chain(*data)))

        elif parsed_args.is_rate:
            if compute_limits:
                data.append(compute_limits.rate)
            if volume_limits:
                data.append(volume_limits.rate)
            columns = ["Verb", "URI", "Value", "Remain", "Unit",
                       "Next Available"]
            return (columns, (utils.get_item_properties(s, columns)
                              for s in itertools.chain(*data)))
        else:
            return {}, {}
    def take_action_network(self, client, parsed_args):
        filters = {}
        if parsed_args.project:
            identity_client = self.app.client_manager.identity
            project_id = identity_common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            ).id
            filters['tenant_id'] = project_id
            filters['project_id'] = project_id

        _tag.get_tag_filtering_args(parsed_args, filters)
        data = client.security_groups(**filters)

        columns = (
            "ID",
            "Name",
            "Description",
            "Project ID",
            "tags"
        )
        column_headers = (
            "ID",
            "Name",
            "Description",
            "Project",
            "Tags"
        )
        return (column_headers,
                (utils.get_item_properties(
                    s, columns,
                ) for s in data))
Exemple #4
0
 def take_action(self, parsed_args):
     client = self.app.client_manager.network
     attrs = _get_attrs(self.app.client_manager, parsed_args)
     obj = client.create_subnet(**attrs)
     display_columns, columns = _get_columns(obj)
     data = utils.get_item_properties(obj, columns, formatters=_formatters)
     return (display_columns, data)
Exemple #5
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity

        domain = None
        if parsed_args.domain:
            domain = common.find_domain(identity_client,
                                        parsed_args.domain).id

        if parsed_args.user:
            user = common.find_user(
                identity_client,
                parsed_args.user,
                parsed_args.user_domain,
            ).id
        else:
            user = None

        # List groups
        if parsed_args.long:
            columns = ('ID', 'Name', 'Domain ID', 'Description')
        else:
            columns = ('ID', 'Name')
        data = identity_client.groups.list(
            domain=domain,
            user=user,
        )

        return (
            columns,
            (utils.get_item_properties(
                s, columns,
                formatters={},
            ) for s in data)
        )
 def take_action(self, parsed_args):
     client = self.app.client_manager.network
     attrs = _get_attrs(self.app.client_manager, parsed_args)
     obj = client.create_qos_policy(**attrs)
     columns = _get_columns(obj)
     data = utils.get_item_properties(obj, columns, formatters={})
     return columns, data
    def take_action(self, parsed_args):
        LOG.debug("take_action({0})".format(parsed_args))
        client = self.app.client_manager.application_catalog

        failure_count = 0
        for category_id in parsed_args.id:
            try:
                client.categories.delete(category_id)
            except Exception:
                failure_count += 1
                print("Failed to delete '{0}'; category not found".
                      format(category_id))
        if failure_count == len(parsed_args.id):
            raise exceptions.CommandError("Unable to find and delete any of "
                                          "the specified categories.")
        data = client.categories.list()

        fields = ["id", "name"]
        field_labels = ["ID", "Name"]

        return (
            field_labels,
            list(utils.get_item_properties(
                s,
                fields,
            ) for s in data)
        )
    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.compute
        data = compute_client.server_groups.list(parsed_args.all_projects)

        if parsed_args.long:
            column_headers = columns = (
                'ID',
                'Name',
                'Policies',
                'Members',
                'Project Id',
                'User Id',
            )
        else:
            column_headers = columns = (
                'ID',
                'Name',
                'Policies',
            )

        return (column_headers,
                (utils.get_item_properties(
                    s, columns,
                    formatters={
                        'Policies': utils.format_list,
                        'Members': utils.format_list,
                    }
                ) for s in data))
 def take_action(self, parsed_args):
     client = self.app.client_manager.network
     obj = client.find_qos_policy(parsed_args.policy,
                                  ignore_missing=False)
     columns = _get_columns(obj)
     data = utils.get_item_properties(obj, columns)
     return columns, data
 def take_action(self, parsed_args):
     compute_client = self.app.client_manager.compute
     if parsed_args.long:
         columns = (
             "ID",
             "Binary",
             "Host",
             "Zone",
             "Status",
             "State",
             "Updated At",
             "Disabled Reason"
         )
     else:
         columns = (
             "ID",
             "Binary",
             "Host",
             "Zone",
             "Status",
             "State",
             "Updated At"
         )
     data = compute_client.services.list(parsed_args.host,
                                         parsed_args.service)
     return (columns,
             (utils.get_item_properties(
                 s, columns,
             ) for s in data))
    def take_action(self, parsed_args):
        client = self.app.client_manager.network

        columns = (
            'network_id',
            'network_name',
            'total_ips',
            'used_ips',
        )
        column_headers = (
            'Network ID',
            'Network Name',
            'Total IPs',
            'Used IPs',
        )

        filters = {}
        if parsed_args.ip_version:
            filters['ip_version'] = parsed_args.ip_version

        if parsed_args.project:
            identity_client = self.app.client_manager.identity
            project_id = identity_common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            ).id
            filters['tenant_id'] = project_id
            filters['project_id'] = project_id
        data = client.network_ip_availabilities(**filters)
        return (column_headers,
                (utils.get_item_properties(
                    s, columns,
                ) for s in data))
    def take_action(self, parsed_args):
        network_client = self.app.client_manager.network
        try:
            # Verify that the extension exists.
            network_client.find_extension('network-segment-range',
                                          ignore_missing=False)
        except Exception as e:
            msg = (_('Network segment range create not supported by '
                     'Network API: %(e)s') % {'e': e})
            raise exceptions.CommandError(msg)

        identity_client = self.app.client_manager.identity

        if not parsed_args.private and parsed_args.project:
            msg = _("--project is only allowed with --private")
            raise exceptions.CommandError(msg)

        if (parsed_args.network_type.lower() != 'vlan' and
                parsed_args.physical_network):
            msg = _("--physical-network is only allowed with --network-type "
                    "vlan")
            raise exceptions.CommandError(msg)

        attrs = {}
        if parsed_args.shared or parsed_args.private:
            attrs['shared'] = parsed_args.shared
        else:
            # default to be ``shared`` if not specified
            attrs['shared'] = True
        attrs['network_type'] = parsed_args.network_type
        attrs['minimum'] = parsed_args.minimum
        attrs['maximum'] = parsed_args.maximum
        if parsed_args.name:
            attrs['name'] = parsed_args.name

        if parsed_args.project:
            project_id = identity_common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            ).id
            if project_id:
                attrs['project_id'] = project_id
            else:
                msg = (_("Failed to create the network segment range for "
                         "project %(project_id)s") % parsed_args.project_id)
                raise exceptions.CommandError(msg)
        elif not attrs['shared']:
            # default to the current project if no project specified and shared
            # is not specified.
            # Get the project id from the current auth.
            attrs['project_id'] = self.app.client_manager.auth_ref.project_id

        if parsed_args.physical_network:
            attrs['physical_network'] = parsed_args.physical_network
        obj = network_client.create_network_segment_range(**attrs)
        display_columns, columns = _get_columns(obj)
        data = utils.get_item_properties(obj, columns)
        data = _update_additional_fields_from_props(columns, props=data)
        return (display_columns, data)
    def take_action(self, parsed_args):
        LOG.debug("take_action({0})".format(parsed_args))
        client = self.app.client_manager.application_catalog

        abandon = getattr(parsed_args, 'abandon', False)
        failure_count = 0
        for environment_id in parsed_args.id:
            try:
                environment = murano_utils.find_resource(client.environments,
                                                         environment_id)
                client.environments.delete(environment.id, abandon)
            except exceptions.NotFound:
                failure_count += 1
                print("Failed to delete '{0}'; environment not found".
                      format(environment_id))

        if failure_count == len(parsed_args.id):
            raise exceptions.CommandError("Unable to find and delete any of "
                                          "the specified environments.")

        data = client.environments.list()

        columns = ('id', 'name', 'status', 'created', 'updated')
        column_headers = [c.capitalize() for c in columns]

        return (
            column_headers,
            list(utils.get_item_properties(
                s,
                columns,
            ) for s in data)
        )
 def take_action(self, parsed_args):
     client = self.app.client_manager.network
     obj = client.find_metering_label(parsed_args.meter,
                                      ignore_missing=False)
     display_columns, columns = _get_columns(obj)
     data = utils.get_item_properties(obj, columns)
     return display_columns, data
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)" % parsed_args)
        client = self.app.client_manager.data_processing
        search_opts = {'type': parsed_args.type} if parsed_args.type else {}

        data = client.jobs.list(search_opts=search_opts)

        if parsed_args.name:
            data = utils.get_by_name_substring(data, parsed_args.name)

        if parsed_args.long:
            columns = ('name', 'id', 'type', 'description', 'is_public',
                       'is_protected')
            column_headers = utils.prepare_column_headers(columns)

        else:
            columns = ('name', 'id', 'type')
            column_headers = utils.prepare_column_headers(columns)

        return (
            column_headers,
            (osc_utils.get_item_properties(
                s,
                columns
            ) for s in data)
        )
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        client = self.app.client_manager.baremetal

        columns = res_fields.CHASSIS_RESOURCE.fields
        labels = res_fields.CHASSIS_RESOURCE.labels

        params = {}
        if parsed_args.limit is not None and parsed_args.limit < 0:
            raise exc.CommandError(
                _('Expected non-negative --limit, got %s') %
                parsed_args.limit)
        params['limit'] = parsed_args.limit
        params['marker'] = parsed_args.marker
        if parsed_args.long:
            params['detail'] = parsed_args.long
            columns = res_fields.CHASSIS_DETAILED_RESOURCE.fields
            labels = res_fields.CHASSIS_DETAILED_RESOURCE.labels
        elif parsed_args.fields:
            params['detail'] = False
            fields = itertools.chain.from_iterable(parsed_args.fields)
            resource = res_fields.Resource(list(fields))
            columns = resource.fields
            labels = resource.labels
            params['fields'] = columns

        self.log.debug("params(%s)", params)
        data = client.chassis.list(**params)

        data = oscutils.sort_items(data, parsed_args.sort)

        return (labels,
                (oscutils.get_item_properties(s, columns, formatters={
                    'Properties': oscutils.format_dict},) for s in data))
    def take_action_compute(self, client, parsed_args):
        column_headers = self._get_column_headers(parsed_args)
        columns = (
            "ID",
            "IP Protocol",
            "IP Range",
            "Port Range",
            "Remote Security Group",
        )

        rules_to_list = []
        if parsed_args.group is not None:
            group = utils.find_resource(
                client.security_groups,
                parsed_args.group,
            )
            rules_to_list = group.rules
        else:
            columns = columns + ('parent_group_id',)
            search = {'all_tenants': parsed_args.all_projects}
            for group in client.security_groups.list(search_opts=search):
                rules_to_list.extend(group.rules)

        # NOTE(rtheis): Turn the raw rules into resources.
        rules = []
        for rule in rules_to_list:
            rules.append(compute_secgroup_rules.SecurityGroupRule(
                client.security_group_rules,
                network_utils.transform_compute_security_group_rule(rule),
            ))

        return (column_headers,
                (utils.get_item_properties(
                    s, columns,
                ) for s in rules))
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        data_protection_client = self.app.client_manager.data_protection
        all_projects = bool(parsed_args.project) or parsed_args.all_projects

        search_opts = {
            'all_tenants': all_projects,
            'project_id': parsed_args.project,
            'name': parsed_args.name,
            'operation_type': parsed_args.operation_type,
            'trigger_id': parsed_args.trigger_id,
            'operation_definition': parsed_args.operation_definition,
        }

        data = data_protection_client.scheduled_operations.list(
            search_opts=search_opts, marker=parsed_args.marker,
            limit=parsed_args.limit, sort=parsed_args.sort)

        column_headers = ['Id', 'Name', 'Operation Type', 'Trigger Id',
                          'Operation Definition']

        json_dumps = functools.partial(jsonutils.dumps,
                                       indent=2,
                                       sort_keys=True)
        formatters = {
            "Operation Definition": json_dumps,
        }
        return (column_headers,
                list(osc_utils.get_item_properties(
                    s, column_headers, formatters=formatters,
                ) for s in data))
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        data_protection_client = self.app.client_manager.data_protection
        all_projects = bool(parsed_args.project) or parsed_args.all_projects

        search_opts = {
            'all_tenants': all_projects,
            'project_id': parsed_args.project,
            'status': parsed_args.status,
        }

        data = data_protection_client.verifications.list(
            search_opts=search_opts, marker=parsed_args.marker,
            limit=parsed_args.limit, sort=parsed_args.sort)

        column_headers = ['Id', 'Project id', 'Provider id', 'Checkpoint id',
                          'Parameters', 'Status']

        json_dumps = functools.partial(jsonutils.dumps,
                                       indent=2,
                                       sort_keys=True)
        formatters = {
            "Parameters": json_dumps,
        }
        return (column_headers,
                (osc_utils.get_item_properties(
                    s, column_headers, formatters=formatters,
                ) for s in data))
    def take_action(self, parsed_args):
        LOG.debug("take_action({0})".format(parsed_args))
        client = self.app.client_manager.application_catalog

        all_environments = getattr(parsed_args, 'all_environments', False)
        env_id = getattr(parsed_args, 'id', None)

        if env_id and all_environments:
            raise exceptions.CommandError(
                'Environment ID and all-environments flag cannot both be set.')
        elif not env_id and not all_environments:
            raise exceptions.CommandError(
                'Either environment ID or all-environments flag must be set.')

        if all_environments:
            data = client.deployments.list(None, all_environments)
        else:
            environment = utils.find_resource(client.environments,
                                              env_id)
            data = client.deployments.list(environment.id)

        columns = ('id', 'state', 'created', 'updated', 'finished')
        column_headers = [c.capitalize() for c in columns]
        return (
            column_headers,
            list(utils.get_item_properties(
                s,
                columns,
            ) for s in data)
        )
def _show_cluster_template(cluster_template):
    del cluster_template._info['links']
    for field in cluster_template._info:
        if cluster_template._info[field] is None:
            setattr(cluster_template, field, '-')
    columns = CLUSTER_TEMPLATE_ATTRIBUTES
    return columns, osc_utils.get_item_properties(cluster_template, columns)
Exemple #22
0
    def take_action(self, parsed_args):
        self.log.debug('take_action(%s)', parsed_args)

        client = self.app.client_manager.orchestration

        fields = {
            'stack_id': parsed_args.stack,
            'resource_name': parsed_args.resource,
            'event_id': parsed_args.event
        }

        try:
            client.stacks.get(parsed_args.stack)
            client.resources.get(parsed_args.stack, parsed_args.resource)
            event = client.events.get(**fields)
        except exc.HTTPNotFound as ex:
            raise exc.CommandError(str(ex))

        formatters = {
            'links': heat_utils.link_formatter,
            'resource_properties': heat_utils.json_formatter
        }

        columns = []
        for key in event.to_dict():
            columns.append(key)

        return columns, utils.get_item_properties(event, columns,
                                                  formatters=formatters)
Exemple #23
0
 def _test_get_item_properties_with_formatter(self, formatters):
     names = ('id', 'attr')
     item = fakes.FakeResource(info={'id': 'fake-id', 'attr': ['a', 'b']})
     res_id, res_attr = utils.get_item_properties(item, names,
                                                  formatters=formatters)
     self.assertEqual('fake-id', res_id)
     return res_attr
    def take_action(self, parsed_args):
        client = getattr(self.app.client_manager, "infra-optim")

        action_plan_uuid = parsed_args.action_plan

        if not uuidutils.is_uuid_like(action_plan_uuid):
            raise exceptions.ValidationError()

        try:
            action_plan = client.action_plan.get(action_plan_uuid)
        except exceptions.HTTPNotFound as exc:
            raise exceptions.CommandError(str(exc))

        if parsed_args.formatter == 'table':
            # Update the raw efficacy indicators with the formatted ones
            action_plan.efficacy_indicators = (
                self._format_indicators(action_plan, parsed_args))

            # Update the raw global efficacy with the formatted one
            action_plan.global_efficacy = self._format_global_efficacy(
                action_plan.global_efficacy, parsed_args)

        columns = res_fields.ACTION_PLAN_FIELDS
        column_headers = res_fields.ACTION_PLAN_FIELD_LABELS
        return column_headers, utils.get_item_properties(action_plan, columns)
Exemple #25
0
 def take_action(self, parsed_args):
     client = _get_client(self, parsed_args)
     opts = {}
     opts['id'] = parsed_args.uuid
     image = client.images.get(**opts)
     columns = _image_columns(image)
     return columns, utils.get_item_properties(image, columns)
    def take_action(self, parsed_args):
        client = getattr(self.app.client_manager, "infra-optim")

        params = {}
        if parsed_args.audit is not None:
            params['audit'] = parsed_args.audit
        if parsed_args.detail:
            fields = res_fields.ACTION_PLAN_FIELDS
            field_labels = res_fields.ACTION_PLAN_FIELD_LABELS
        else:
            fields = res_fields.ACTION_PLAN_SHORT_LIST_FIELDS
            field_labels = res_fields.ACTION_PLAN_SHORT_LIST_FIELD_LABELS

        params.update(common_utils.common_params_for_list(
            parsed_args, fields, field_labels))

        data = client.action_plan.list(**params)

        if parsed_args.formatter == 'table':
            for action_plan in data:
                # Update the raw efficacy indicators with the formatted ones
                action_plan.efficacy_indicators = (
                    self._format_indicators(action_plan, parsed_args))

                # Update the raw global efficacy with the formatted one
                action_plan.global_efficacy = self._format_global_efficacy(
                    action_plan.global_efficacy, parsed_args)

        return (field_labels,
                (utils.get_item_properties(item, fields) for item in data))
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)" % parsed_args)
        client = self.app.client_manager.data_processing
        search_opts = {}
        if parsed_args.plugin:
            search_opts['plugin_name'] = parsed_args.plugin
        if parsed_args.plugin_version:
            search_opts['hadoop_version'] = parsed_args.plugin_version

        data = client.cluster_templates.list(search_opts=search_opts)

        if parsed_args.name:
            data = utils.get_by_name_substring(data, parsed_args.name)

        if parsed_args.long:
            columns = ('name', 'id', 'plugin_name', 'hadoop_version',
                       'node_groups', 'description')
            column_headers = utils.prepare_column_headers(
                columns, {'hadoop_version': 'plugin_version'})

        else:
            columns = ('name', 'id', 'plugin_name', 'hadoop_version')
            column_headers = utils.prepare_column_headers(
                columns, {'hadoop_version': 'plugin_version'})

        return (
            column_headers,
            (osc_utils.get_item_properties(
                s,
                columns,
                formatters={
                    'node_groups': _format_node_groups_list
                }
            ) for s in data)
        )
    def take_action(self, parsed_args):
        LOG.debug("take_action({0})".format(parsed_args))

        client = self.app.client_manager.application_catalog

        failure_count = 0
        for package_id in parsed_args.id:
            try:
                client.packages.delete(package_id)
            except exceptions.NotFound:
                failure_count += 1
                print("Failed to delete '{0}'; package not found".
                      format(package_id))

        if failure_count == len(parsed_args.id):
            raise exceptions.CommandError("Unable to find and delete any of "
                                          "the specified packages.")
        data = client.packages.filter()

        columns = ('id', 'name', 'fully_qualified_name', 'author', 'active',
                   'is public', 'type', 'version')
        column_headers = [c.capitalize() for c in columns]

        return (
            column_headers,
            list(utils.get_item_properties(
                s,
                columns,
            ) for s in data)
        )
Exemple #29
0
    def take_action(self, parsed_args):
        client = self.app.client_manager.network
        obj = client.find_router(parsed_args.router, ignore_missing=False)
        display_columns, columns = _get_columns(obj)
        data = utils.get_item_properties(obj, columns, formatters=_formatters)

        return (display_columns, data)
Exemple #30
0
 def take_action(self, parsed_args):
     client = self.app.client_manager.network
     columns = (
         'id',
         'agent_type',
         'host',
         'availability_zone',
         'alive',
         'admin_state_up',
         'binary'
     )
     column_headers = (
         'ID',
         'Agent Type',
         'Host',
         'Availability Zone',
         'Alive',
         'State',
         'Binary'
     )
     data = client.agents()
     return (column_headers,
             (utils.get_item_properties(
                 s, columns, formatters=_formatters,
             ) for s in data))
Exemple #31
0
 def take_action(self, parsed_args):
     client = self.app.client_manager.network
     obj = client._get(ProjectPluginMap, parsed_args.id)
     display_columns, columns = _get_columns(obj)
     data = utils.get_item_properties(obj, columns)
     return display_columns, data
Exemple #32
0
    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.compute

        kwargs = {}

        if parsed_args.marker:
            if compute_client.api_version < api_versions.APIVersion('2.58'):
                msg = _(
                    '--os-compute-api-version 2.58 or greater is required to '
                    'support the --marker option')
                raise exceptions.CommandError(msg)
            kwargs['marker'] = parsed_args.marker

        if parsed_args.limit:
            if compute_client.api_version < api_versions.APIVersion('2.58'):
                msg = _(
                    '--os-compute-api-version 2.58 or greater is required to '
                    'support the --limit option')
                raise exceptions.CommandError(msg)
            kwargs['limit'] = parsed_args.limit

        if parsed_args.changes_since:
            if compute_client.api_version < api_versions.APIVersion('2.58'):
                msg = _(
                    '--os-compute-api-version 2.58 or greater is required to '
                    'support the --changes-since option')
                raise exceptions.CommandError(msg)

            try:
                iso8601.parse_date(parsed_args.changes_since)
            except (TypeError, iso8601.ParseError):
                msg = _('Invalid changes-since value: %s')
                raise exceptions.CommandError(msg % parsed_args.changes_since)

            kwargs['changes_since'] = parsed_args.changes_since

        if parsed_args.changes_before:
            if compute_client.api_version < api_versions.APIVersion('2.66'):
                msg = _(
                    '--os-compute-api-version 2.66 or greater is required to '
                    'support the --changes-before option')
                raise exceptions.CommandError(msg)

            try:
                iso8601.parse_date(parsed_args.changes_before)
            except (TypeError, iso8601.ParseError):
                msg = _('Invalid changes-before value: %s')
                raise exceptions.CommandError(msg % parsed_args.changes_before)

            kwargs['changes_before'] = parsed_args.changes_before

        server_id = utils.find_resource(
            compute_client.servers,
            parsed_args.server,
        ).id

        data = compute_client.instance_action.list(server_id, **kwargs)

        columns = (
            'request_id',
            'instance_uuid',
            'action',
            'start_time',
        )
        column_headers = (
            'Request ID',
            'Server ID',
            'Action',
            'Start Time',
        )

        if parsed_args.long:
            columns += (
                'message',
                'project_id',
                'user_id',
            )
            column_headers += (
                'Message',
                'Project ID',
                'User ID',
            )

        return (
            column_headers,
            (utils.get_item_properties(s, columns) for s in data),
        )
 def take_action_network(self, client, parsed_args):
     attrs = _get_attrs(self.app.client_manager, parsed_args)
     obj = client.create_ip(**attrs)
     display_columns, columns = _get_network_columns(obj)
     data = utils.get_item_properties(obj, columns)
     return (display_columns, data)
Exemple #34
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity
        formatters = {}
        project = None
        if parsed_args.project:
            project = utils.find_resource(
                identity_client.tenants,
                parsed_args.project,
            )
            project = project.id

        if parsed_args.long:
            columns = (
                'ID',
                'Name',
                'tenantId',
                'Email',
                'Enabled',
            )
            column_headers = (
                'ID',
                'Name',
                'Project',
                'Email',
                'Enabled',
            )
            # Cache the project list
            project_cache = {}
            try:
                for p in identity_client.tenants.list():
                    project_cache[p.id] = p
            except Exception:
                # Just forget it if there's any trouble
                pass
            formatters['tenantId'] = functools.partial(
                ProjectColumn, project_cache=project_cache)
        else:
            columns = column_headers = ('ID', 'Name')
        data = identity_client.users.list(tenant_id=project)

        if parsed_args.project:
            d = {}
            for s in data:
                d[s.id] = s
            data = d.values()

        if parsed_args.long:
            # FIXME(dtroyer): Sometimes user objects have 'tenant_id' instead
            #                 of 'tenantId'.  Why?  Dunno yet, but until that
            #                 is fixed we need to handle it; auth_token.py
            #                 only looks for 'tenantId'.
            for d in data:
                if 'tenant_id' in d._info:
                    d._info['tenantId'] = d._info.pop('tenant_id')
                    d._add_details(d._info)

        return (column_headers, (utils.get_item_properties(
            s,
            columns,
            mixed_case_fields=('tenantId', ),
            formatters=formatters,
        ) for s in data))
Exemple #35
0
    def take_action(self, parsed_args):
        self.log.debug('take_action(%s)', parsed_args)

        client = self.app.client_manager.orchestration

        columns = ['id', 'resource_status', 'resource_status_reason',
                   'event_time', 'physical_resource_id']

        kwargs = {
            'resource_name': parsed_args.resource,
            'filters': heat_utils.format_parameters(parsed_args.filter),
            'sort_dir': 'asc'
        }

        if parsed_args.resource and parsed_args.nested_depth:
            msg = _('--nested-depth cannot be specified with --resource')
            raise exc.CommandError(msg)

        if parsed_args.nested_depth:
            columns.append('stack_name')
            nested_depth = parsed_args.nested_depth
        else:
            nested_depth = 0

        if parsed_args.sort:
            sorts = []
            sort_keys = []
            for sort in parsed_args.sort:
                if sort.startswith(":"):
                    sorts.append(":".join(["event_time", sort.lstrip(":")]))
                else:
                    sorts.append(sort)
                    sort_keys.append(sort.split(":")[0])
            kwargs['sort_keys'] = sort_keys

            if ":" in parsed_args.sort[0]:
                kwargs['sort_dir'] = parsed_args.sort[0].split(":")[1]

        if parsed_args.follow:
            if parsed_args.formatter != 'log':
                msg = _('--follow can only be specified with --format log')
                raise exc.CommandError(msg)

            marker = parsed_args.marker
            try:
                event_log_context = heat_utils.EventLogContext()
                while True:
                    events = event_utils.get_events(
                        client,
                        stack_id=parsed_args.stack,
                        event_args=kwargs,
                        nested_depth=nested_depth,
                        marker=marker)
                    if events:
                        marker = getattr(events[-1], 'id', None)
                        events_log = heat_utils.event_log_formatter(
                            events, event_log_context)
                        self.app.stdout.write(events_log)
                        self.app.stdout.write('\n')
                    time.sleep(5)
                    # this loop never exits
            except (KeyboardInterrupt, EOFError):  # ctrl-c, ctrl-d
                return [], []

        events = event_utils.get_events(
            client, stack_id=parsed_args.stack, event_args=kwargs,
            nested_depth=nested_depth, marker=parsed_args.marker,
            limit=parsed_args.limit)

        if parsed_args.sort:
            events = utils.sort_items(events, ','.join(sorts))

        if parsed_args.formatter == 'log':
            return [], events

        if len(events):
            if hasattr(events[0], 'resource_name'):
                columns.insert(0, 'resource_name')
                columns.append('logical_resource_id')
            else:
                columns.insert(0, 'logical_resource_id')

        return (
            columns,
            (utils.get_item_properties(s, columns) for s in events)
        )
Exemple #36
0
 def new(self, *args, **kwargs):
     obj = func(self, *args, **kwargs)
     delattr(obj, 'location')
     display_columns, columns = _get_columns(obj)
     data = utils.get_item_properties(obj, columns)
     return (display_columns, data)
    def take_action(self, parsed_args):

        volume_client = self.app.client_manager.volume
        compute_client = self.app.client_manager.compute

        def _format_attach(attachments):
            """Return a formatted string of a volume's attached instances

            :param attachments: a volume.attachments field
            :rtype: a string of formatted instances
            """

            msg = ''
            for attachment in attachments:
                server = attachment['server_id']
                if server in server_cache.keys():
                    server = server_cache[server].name
                device = attachment['device']
                msg += 'Attached to %s on %s ' % (server, device)
            return msg

        if parsed_args.long:
            columns = (
                'ID',
                'Display Name',
                'Status',
                'Size',
                'Volume Type',
                'Bootable',
                'Attachments',
                'Metadata',
            )
            column_headers = (
                'ID',
                'Display Name',
                'Status',
                'Size',
                'Type',
                'Bootable',
                'Attached to',
                'Properties',
            )
        else:
            columns = (
                'ID',
                'Display Name',
                'Status',
                'Size',
                'Attachments',
            )
            column_headers = (
                'ID',
                'Display Name',
                'Status',
                'Size',
                'Attached to',
            )

        # Cache the server list
        server_cache = {}
        try:
            for s in compute_client.servers.list():
                server_cache[s.id] = s
        except Exception:
            # Just forget it if there's any trouble
            pass

        search_opts = {
            'all_tenants': parsed_args.all_projects,
            'display_name': parsed_args.name,
            'status': parsed_args.status,
        }

        data = volume_client.volumes.list(
            search_opts=search_opts,
            limit=parsed_args.limit,
        )

        return (column_headers, (utils.get_item_properties(
            s,
            columns,
            formatters={
                'Metadata': utils.format_dict,
                'Attachments': _format_attach
            },
        ) for s in data))
Exemple #38
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity
        client = self.app.client_manager.network

        columns = (
            'id',
            'name',
            'status',
            'is_admin_state_up',
            'project_id',
        )
        column_headers = (
            'ID',
            'Name',
            'Status',
            'State',
            'Project',
        )

        args = {}

        if parsed_args.name is not None:
            args['name'] = parsed_args.name

        if parsed_args.enable:
            args['admin_state_up'] = True
            args['is_admin_state_up'] = True
        elif parsed_args.disable:
            args['admin_state_up'] = False
            args['is_admin_state_up'] = False

        if parsed_args.project:
            project_id = identity_common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            ).id
            args['tenant_id'] = project_id
            args['project_id'] = project_id

        _tag.get_tag_filtering_args(parsed_args, args)

        if parsed_args.agent is not None:
            agent = client.get_agent(parsed_args.agent)
            data = client.agent_hosted_routers(agent)
            # NOTE: Networking API does not support filtering by parameters,
            # so we need filtering in the client side.
            data = [d for d in data if self._filter_match(d, args)]
        else:
            data = client.routers(**args)

        # check if "HA" and "Distributed" columns should be displayed also
        data = list(data)
        for d in data:
            if (d.is_distributed is not None
                    and 'is_distributed' not in columns):
                columns = columns + ('is_distributed', )
                column_headers = column_headers + ('Distributed', )
            if d.is_ha is not None and 'is_ha' not in columns:
                columns = columns + ('is_ha', )
                column_headers = column_headers + ('HA', )
        if parsed_args.long:
            columns = columns + (
                'routes',
                'external_gateway_info',
            )
            column_headers = column_headers + (
                'Routes',
                'External gateway info',
            )
            # availability zone will be available only when
            # router_availability_zone extension is enabled
            if client.find_extension("router_availability_zone"):
                columns = columns + ('availability_zones', )
                column_headers = column_headers + ('Availability zones', )
            columns = columns + ('tags', )
            column_headers = column_headers + ('Tags', )

        return (column_headers, (utils.get_item_properties(
            s,
            columns,
            formatters=_formatters,
        ) for s in data))
    def take_action_network(self, client, parsed_args):
        # Get the security group ID to hold the rule.
        security_group_id = client.find_security_group(parsed_args.group,
                                                       ignore_missing=False).id

        # Build the create attributes.
        attrs = {}
        attrs['protocol'] = self._get_protocol(parsed_args)

        if parsed_args.description is not None:
            attrs['description'] = parsed_args.description

        # NOTE(rtheis): A direction must be specified and ingress
        # is the default.
        if parsed_args.ingress or not parsed_args.egress:
            attrs['direction'] = 'ingress'
        if parsed_args.egress:
            attrs['direction'] = 'egress'

        # NOTE(rtheis): Use ethertype specified else default based
        # on IP protocol.
        attrs['ethertype'] = self._get_ethertype(parsed_args,
                                                 attrs['protocol'])

        # NOTE(rtheis): Validate the port range and ICMP type and code.
        # It would be ideal if argparse could do this.
        if parsed_args.dst_port and (parsed_args.icmp_type
                                     or parsed_args.icmp_code):
            msg = _('Argument --dst-port not allowed with arguments '
                    '--icmp-type and --icmp-code')
            raise exceptions.CommandError(msg)
        if parsed_args.icmp_type is None and parsed_args.icmp_code is not None:
            msg = _('Argument --icmp-type required with argument --icmp-code')
            raise exceptions.CommandError(msg)
        is_icmp_protocol = _is_icmp_protocol(attrs['protocol'])
        if not is_icmp_protocol and (parsed_args.icmp_type
                                     or parsed_args.icmp_code):
            msg = _('ICMP IP protocol required with arguments '
                    '--icmp-type and --icmp-code')
            raise exceptions.CommandError(msg)
        # NOTE(rtheis): For backwards compatibility, continue ignoring
        # the destination port range when an ICMP IP protocol is specified.
        if parsed_args.dst_port and not is_icmp_protocol:
            attrs['port_range_min'] = parsed_args.dst_port[0]
            attrs['port_range_max'] = parsed_args.dst_port[1]
        if parsed_args.icmp_type is not None and parsed_args.icmp_type >= 0:
            attrs['port_range_min'] = parsed_args.icmp_type
        if parsed_args.icmp_code is not None and parsed_args.icmp_code >= 0:
            attrs['port_range_max'] = parsed_args.icmp_code

        if parsed_args.remote_group is not None:
            attrs['remote_group_id'] = client.find_security_group(
                parsed_args.remote_group, ignore_missing=False).id
        elif parsed_args.remote_address_group is not None:
            attrs['remote_address_group_id'] = client.find_address_group(
                parsed_args.remote_address_group, ignore_missing=False).id
        elif parsed_args.remote_ip is not None:
            attrs['remote_ip_prefix'] = parsed_args.remote_ip
        elif attrs['ethertype'] == 'IPv4':
            attrs['remote_ip_prefix'] = '0.0.0.0/0'
        elif attrs['ethertype'] == 'IPv6':
            attrs['remote_ip_prefix'] = '::/0'
        attrs['security_group_id'] = security_group_id
        if parsed_args.project is not None:
            identity_client = self.app.client_manager.identity
            project_id = identity_common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            ).id
            attrs['project_id'] = project_id

        attrs.update(self._parse_extra_properties(
            parsed_args.extra_properties))

        # Create and show the security group rule.
        obj = client.create_security_group_rule(**attrs)
        display_columns, columns = _get_columns(obj)
        data = utils.get_item_properties(obj, columns)
        return (display_columns, data)
 def take_action_network(self, client, parsed_args):
     obj = client.find_ip(parsed_args.floating_ip, ignore_missing=False)
     display_columns, columns = _get_network_columns(obj)
     data = utils.get_item_properties(obj, columns)
     return (display_columns, data)
Exemple #41
0
 def take_action(self, parsed_args):
     client = self.app.client_manager.network
     obj = client.find_port(parsed_args.port, ignore_missing=False)
     display_columns, columns = _get_columns(obj)
     data = utils.get_item_properties(obj, columns, formatters=_formatters)
     return (display_columns, data)
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity
        client = self.app.client_manager.network
        columns = (
            'id',
            'name',
            'status',
            'is_admin_state_up',
            'is_distributed',
            'is_ha',
            'project_id',
        )
        column_headers = (
            'ID',
            'Name',
            'Status',
            'State',
            'Distributed',
            'HA',
            'Project',
        )

        args = {}

        if parsed_args.name is not None:
            args['name'] = parsed_args.name

        if parsed_args.enable:
            args['admin_state_up'] = True
            args['is_admin_state_up'] = True
        elif parsed_args.disable:
            args['admin_state_up'] = False
            args['is_admin_state_up'] = False

        if parsed_args.project:
            project_id = identity_common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            ).id
            args['tenant_id'] = project_id
            args['project_id'] = project_id
        if parsed_args.long:
            columns = columns + (
                'routes',
                'external_gateway_info',
            )
            column_headers = column_headers + (
                'Routes',
                'External gateway info',
            )
            # availability zone will be available only when
            # router_availability_zone extension is enabled
            if client.find_extension("router_availability_zone"):
                columns = columns + ('availability_zones', )
                column_headers = column_headers + ('Availability zones', )

        data = client.routers(**args)
        return (column_headers, (utils.get_item_properties(
            s,
            columns,
            formatters=_formatters,
        ) for s in data))
 def take_action_network(self, client, parsed_args):
     obj = client.find_security_group_rule(parsed_args.rule,
                                           ignore_missing=False)
     display_columns, columns = _get_columns(obj)
     data = utils.get_item_properties(obj, columns)
     return (display_columns, data)
    def take_action(self, parsed_args):
        image_client = self.app.client_manager.image

        kwargs = {}
        if parsed_args.public:
            kwargs['visibility'] = 'public'
        if parsed_args.private:
            kwargs['visibility'] = 'private'
        if parsed_args.community:
            kwargs['visibility'] = 'community'
        if parsed_args.shared:
            kwargs['visibility'] = 'shared'
        if parsed_args.limit:
            kwargs['limit'] = parsed_args.limit
        if parsed_args.marker:
            kwargs['marker'] = image_client.find_image(parsed_args.marker).id
        if parsed_args.name:
            kwargs['name'] = parsed_args.name
        if parsed_args.status:
            kwargs['status'] = parsed_args.status
        if parsed_args.member_status:
            kwargs['member_status'] = parsed_args.member_status
        if parsed_args.tag:
            kwargs['tag'] = parsed_args.tag
        if parsed_args.long:
            columns = (
                'ID',
                'Name',
                'Disk Format',
                'Container Format',
                'Size',
                'Checksum',
                'Status',
                'visibility',
                'is_protected',
                'owner_id',
                'tags',
            )
            column_headers = (
                'ID',
                'Name',
                'Disk Format',
                'Container Format',
                'Size',
                'Checksum',
                'Status',
                'Visibility',
                'Protected',
                'Project',
                'Tags',
            )
        else:
            columns = ("ID", "Name", "Status")
            column_headers = columns

        # List of image data received
        if 'limit' in kwargs:
            # Disable automatic pagination in SDK
            kwargs['paginated'] = False
        data = list(image_client.images(**kwargs))

        if parsed_args.property:
            for attr, value in parsed_args.property.items():
                api_utils.simple_filter(
                    data,
                    attr=attr,
                    value=value,
                    property_field='properties',
                )

        data = utils.sort_items(data, parsed_args.sort, str)

        return (column_headers, (utils.get_item_properties(
            s,
            columns,
            formatters=_formatters,
        ) for s in data))
Exemple #45
0
    def take_action(self, parsed_args):
        self.log.debug('take_action(%s)', parsed_args)

        client = self.app.client_manager.orchestration

        tpl_files, template = template_utils.process_template_path(
            parsed_args.template,
            object_request=http.authenticated_fetcher(client))

        env_files_list = []
        env_files, env = (
            template_utils.process_multiple_environments_and_files(
                env_paths=parsed_args.environment,
                env_list_tracker=env_files_list))

        parameters = heat_utils.format_all_parameters(
            parsed_args.parameter,
            parsed_args.parameter_file,
            parsed_args.template)

        if parsed_args.pre_create:
            template_utils.hooks_to_env(env, parsed_args.pre_create,
                                        'pre-create')

        fields = {
            'stack_name': parsed_args.name,
            'disable_rollback': not parsed_args.enable_rollback,
            'parameters': parameters,
            'template': template,
            'files': dict(list(tpl_files.items()) + list(env_files.items())),
            'environment': env
        }

        # If one or more environments is found, pass the listing to the server
        if env_files_list:
            fields['environment_files'] = env_files_list

        if parsed_args.tags:
            fields['tags'] = parsed_args.tags
        if parsed_args.timeout:
            fields['timeout_mins'] = parsed_args.timeout

        if parsed_args.dry_run:
            stack = client.stacks.preview(**fields)

            formatters = {
                'description': heat_utils.text_wrap_formatter,
                'template_description': heat_utils.text_wrap_formatter,
                'stack_status_reason': heat_utils.text_wrap_formatter,
                'parameters': heat_utils.json_formatter,
                'outputs': heat_utils.json_formatter,
                'resources': heat_utils.json_formatter,
                'links': heat_utils.link_formatter,
            }

            columns = []
            for key in stack.to_dict():
                columns.append(key)
            columns.sort()

            return (
                columns,
                utils.get_item_properties(stack, columns,
                                          formatters=formatters)
            )

        stack = client.stacks.create(**fields)['stack']
        if parsed_args.wait:
            stack_status, msg = event_utils.poll_for_events(
                client, parsed_args.name, action='CREATE')
            if stack_status == 'CREATE_FAILED':
                raise exc.CommandError(msg)

        return _show_stack(client, stack['id'], format='table', short=True)
Exemple #46
0
    def take_action(self, parsed_args):
        network_client = self.app.client_manager.network
        identity_client = self.app.client_manager.identity

        columns = (
            'id',
            'name',
            'mac_address',
            'fixed_ips',
            'status',
        )
        column_headers = (
            'ID',
            'Name',
            'MAC Address',
            'Fixed IP Addresses',
            'Status',
        )

        filters = {}
        if parsed_args.long:
            columns += ('security_group_ids', 'device_owner', 'tags')
            column_headers += ('Security Groups', 'Device Owner', 'Tags')
        if parsed_args.device_owner is not None:
            filters['device_owner'] = parsed_args.device_owner
        if parsed_args.device_id is not None:
            filters['device_id'] = parsed_args.device_id
        if parsed_args.router:
            _router = network_client.find_router(parsed_args.router,
                                                 ignore_missing=False)
            filters['device_id'] = _router.id
        if parsed_args.server:
            compute_client = self.app.client_manager.compute
            server = utils.find_resource(compute_client.servers,
                                         parsed_args.server)
            filters['device_id'] = server.id
        if parsed_args.network:
            network = network_client.find_network(parsed_args.network,
                                                  ignore_missing=False)
            filters['network_id'] = network.id
        if parsed_args.mac_address:
            filters['mac_address'] = parsed_args.mac_address
        if parsed_args.project:
            project_id = identity_common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            ).id
            filters['tenant_id'] = project_id
            filters['project_id'] = project_id
        if parsed_args.fixed_ip:
            filters['fixed_ips'] = _prepare_filter_fixed_ips(
                self.app.client_manager, parsed_args)

        _tag.get_tag_filtering_args(parsed_args, filters)

        data = network_client.ports(**filters)

        headers, attrs = utils.calculate_header_and_attrs(
            column_headers, columns, parsed_args)
        return (headers, (utils.get_item_properties(
            s,
            attrs,
            formatters=_formatters,
        ) for s in data))
Exemple #47
0
    def take_action(self, parsed_args):

        def _format_project(project):
            if not project:
                return ""
            if project in project_cache.keys():
                return project_cache[project].name
            else:
                return project

        compute_client = self.app.client_manager.compute
        columns = (
            "tenant_id",
            "server_usages",
            "total_memory_mb_usage",
            "total_vcpus_usage",
            "total_local_gb_usage"
        )
        column_headers = (
            "Project",
            "Servers",
            "RAM MB-Hours",
            "CPU Hours",
            "Disk GB-Hours"
        )

        dateformat = "%Y-%m-%d"
        now = datetime.datetime.utcnow()

        if parsed_args.start:
            start = datetime.datetime.strptime(parsed_args.start, dateformat)
        else:
            start = now - datetime.timedelta(weeks=4)

        if parsed_args.end:
            end = datetime.datetime.strptime(parsed_args.end, dateformat)
        else:
            end = now + datetime.timedelta(days=1)

        if compute_client.api_version < api_versions.APIVersion("2.40"):
            usage_list = compute_client.usage.list(start, end, detailed=True)
        else:
            # If the number of instances used to calculate the usage is greater
            # than CONF.api.max_limit, the usage will be split across multiple
            # requests and the responses will need to be merged back together.
            usages = collections.OrderedDict()
            usage_list = compute_client.usage.list(start, end, detailed=True)
            _merge_usage_list(usages, usage_list)
            marker = _get_usage_list_marker(usage_list)
            while marker:
                next_usage_list = compute_client.usage.list(
                    start, end, detailed=True, marker=marker)
                marker = _get_usage_list_marker(next_usage_list)
                if marker:
                    _merge_usage_list(usages, next_usage_list)
            usage_list = list(usages.values())

        # Cache the project list
        project_cache = {}
        try:
            for p in self.app.client_manager.identity.projects.list():
                project_cache[p.id] = p
        except Exception:
            # Just forget it if there's any trouble
            pass

        if parsed_args.formatter == 'table' and len(usage_list) > 0:
            self.app.stdout.write(_("Usage from %(start)s to %(end)s: \n") % {
                "start": start.strftime(dateformat),
                "end": end.strftime(dateformat),
            })

        return (
            column_headers,
            (
                utils.get_item_properties(
                    s, columns,
                    formatters=_formatters(project_cache),
                ) for s in usage_list
            ),
        )
    def take_action_network(self, client, parsed_args):
        # Get the security group ID to hold the rule.
        security_group_id = client.find_security_group(
            parsed_args.group,
            ignore_missing=False
        ).id

        # Build the create attributes.
        attrs = {}
        attrs['protocol'] = self._get_protocol(parsed_args)

        if parsed_args.description is not None:
            attrs['description'] = parsed_args.description

        # NOTE(rtheis): A direction must be specified and ingress
        # is the default.
        if parsed_args.ingress or not parsed_args.egress:
            attrs['direction'] = 'ingress'
        if parsed_args.egress:
            attrs['direction'] = 'egress'

        # NOTE(rtheis): Use ethertype specified else default based
        # on IP protocol.
        if parsed_args.ethertype:
            attrs['ethertype'] = parsed_args.ethertype
        elif self._is_ipv6_protocol(attrs['protocol']):
            attrs['ethertype'] = 'IPv6'
        else:
            attrs['ethertype'] = 'IPv4'

        # NOTE(rtheis): Validate the port range and ICMP type and code.
        # It would be ideal if argparse could do this.
        if parsed_args.dst_port and (parsed_args.icmp_type or
                                     parsed_args.icmp_code):
            msg = _('Argument --dst-port not allowed with arguments '
                    '--icmp-type and --icmp-code')
            raise exceptions.CommandError(msg)
        if parsed_args.icmp_type is None and parsed_args.icmp_code is not None:
            msg = _('Argument --icmp-type required with argument --icmp-code')
            raise exceptions.CommandError(msg)
        is_icmp_protocol = _is_icmp_protocol(attrs['protocol'])
        if not is_icmp_protocol and (parsed_args.icmp_type or
                                     parsed_args.icmp_code):
            msg = _('ICMP IP protocol required with arguments '
                    '--icmp-type and --icmp-code')
            raise exceptions.CommandError(msg)
        # NOTE(rtheis): For backwards compatibility, continue ignoring
        # the destination port range when an ICMP IP protocol is specified.
        if parsed_args.dst_port and not is_icmp_protocol:
            attrs['port_range_min'] = parsed_args.dst_port[0]
            attrs['port_range_max'] = parsed_args.dst_port[1]
        if parsed_args.icmp_type:
            attrs['port_range_min'] = parsed_args.icmp_type
        if parsed_args.icmp_code:
            attrs['port_range_max'] = parsed_args.icmp_code

        # NOTE(dtroyer): --src-ip and --src-group were deprecated in Nov 2016.
        #                Do not remove before 4.x release or Nov 2017.
        if not (parsed_args.remote_group is None and
                parsed_args.src_group is None):
            attrs['remote_group_id'] = client.find_security_group(
                parsed_args.remote_group or parsed_args.src_group,
                ignore_missing=False
            ).id
            if parsed_args.src_group:
                LOG.warning(
                    _("The %(old)s option is deprecated, "
                      "please use %(new)s instead."),
                    {'old': '--src-group', 'new': '--remote-group'},
                )
        elif not (parsed_args.remote_ip is None and
                  parsed_args.src_ip is None):
            attrs['remote_ip_prefix'] = (
                parsed_args.remote_ip or parsed_args.src_ip
            )
            if parsed_args.src_ip:
                LOG.warning(
                    _("The %(old)s option is deprecated, "
                      "please use %(new)s instead."),
                    {'old': '--src-ip', 'new': '--remote-ip'},
                )
        elif attrs['ethertype'] == 'IPv4':
            attrs['remote_ip_prefix'] = '0.0.0.0/0'
        attrs['security_group_id'] = security_group_id
        if parsed_args.project is not None:
            identity_client = self.app.client_manager.identity
            project_id = identity_common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            ).id
            attrs['tenant_id'] = project_id

        # Create and show the security group rule.
        obj = client.create_security_group_rule(**attrs)
        display_columns, columns = _get_columns(obj)
        data = utils.get_item_properties(obj, columns)
        return (display_columns, data)
Exemple #49
0
    def take_action(self, parsed_args):
        def _deprecated():
            # NOTE(henry-nash): Deprecated as of Newton, so we should remove
            # this in the 'P' release.
            self.log.warning(
                _('Listing assignments using role list is '
                  'deprecated as of the Newton release. Use role '
                  'assignment list --user <user-name> --project '
                  '<project-name> --names instead.'))

        identity_client = self.app.client_manager.identity
        auth_ref = self.app.client_manager.auth_ref

        # No user or project specified, list all roles in the system
        if not parsed_args.user and not parsed_args.project:
            columns = ('ID', 'Name')
            data = identity_client.roles.list()
        elif parsed_args.user and parsed_args.project:
            user = utils.find_resource(
                identity_client.users,
                parsed_args.user,
            )
            project = utils.find_resource(
                identity_client.projects,
                parsed_args.project,
            )
            _deprecated()
            data = identity_client.roles.roles_for_user(user.id, project.id)

        elif parsed_args.user:
            user = utils.find_resource(
                identity_client.users,
                parsed_args.user,
            )
            if self.app.client_manager.auth_ref:
                project = utils.find_resource(identity_client.projects,
                                              auth_ref.project_id)
            else:
                msg = _("Project must be specified")
                raise exceptions.CommandError(msg)
            _deprecated()
            data = identity_client.roles.roles_for_user(user.id, project.id)
        elif parsed_args.project:
            project = utils.find_resource(
                identity_client.projects,
                parsed_args.project,
            )
            if self.app.client_manager.auth_ref:
                user = utils.find_resource(identity_client.users,
                                           auth_ref.user_id)
            else:
                msg = _("User must be specified")
                raise exceptions.CommandError(msg)
            _deprecated()
            data = identity_client.roles.roles_for_user(user.id, project.id)

        if parsed_args.user or parsed_args.project:
            columns = ('ID', 'Name', 'Project', 'User')
            for user_role in data:
                user_role.user = user.name
                user_role.project = project.name

        return (columns, (utils.get_item_properties(
            s,
            columns,
            formatters={},
        ) for s in data))
Exemple #50
0
    def take_action_network(self, client, parsed_args):
        network_client = self.app.client_manager.network
        identity_client = self.app.client_manager.identity

        columns = (
            'id',
            'floating_ip_address',
            'fixed_ip_address',
            'port_id',
            'floating_network_id',
            'project_id',
        )
        headers = (
            'ID',
            'Floating IP Address',
            'Fixed IP Address',
            'Port',
            'Floating Network',
            'Project',
        )
        if parsed_args.long:
            columns = columns + (
                'router_id',
                'status',
                'description',
                'tags',
                'dns_name',
                'dns_domain',
            )
            headers = headers + (
                'Router',
                'Status',
                'Description',
                'Tags',
                'DNS Name',
                'DNS Domain',
            )

        query = {}

        if parsed_args.network is not None:
            network = network_client.find_network(parsed_args.network,
                                                  ignore_missing=False)
            query['floating_network_id'] = network.id
        if parsed_args.port is not None:
            port = network_client.find_port(parsed_args.port,
                                            ignore_missing=False)
            query['port_id'] = port.id
        if parsed_args.fixed_ip_address is not None:
            query['fixed_ip_address'] = parsed_args.fixed_ip_address
        if parsed_args.floating_ip_address is not None:
            query['floating_ip_address'] = parsed_args.floating_ip_address
        if parsed_args.status:
            query['status'] = parsed_args.status
        if parsed_args.project is not None:
            project = identity_common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            )
            query['tenant_id'] = project.id
            query['project_id'] = project.id
        if parsed_args.router is not None:
            router = network_client.find_router(parsed_args.router,
                                                ignore_missing=False)
            query['router_id'] = router.id

        _tag.get_tag_filtering_args(parsed_args, query)

        data = client.ips(**query)

        return (headers, (utils.get_item_properties(
            s,
            columns,
            formatters={},
        ) for s in data))
Exemple #51
0
    def take_action_network(self, client, parsed_args):
        identity_client = self.app.client_manager.identity
        if parsed_args.long:
            columns = (
                'id',
                'name',
                'status',
                'project_id',
                'is_admin_state_up',
                'is_shared',
                'subnet_ids',
                'provider_network_type',
                'is_router_external',
                'availability_zones',
            )
            column_headers = (
                'ID',
                'Name',
                'Status',
                'Project',
                'State',
                'Shared',
                'Subnets',
                'Network Type',
                'Router Type',
                'Availability Zones',
            )
        else:
            columns = ('id', 'name', 'subnet_ids')
            column_headers = (
                'ID',
                'Name',
                'Subnets',
            )

        args = {}

        if parsed_args.external:
            args['router:external'] = True
            args['is_router_external'] = True
        elif parsed_args.internal:
            args['router:external'] = False
            args['is_router_external'] = False

        if parsed_args.name is not None:
            args['name'] = parsed_args.name

        if parsed_args.enable:
            args['admin_state_up'] = True
            args['is_admin_state_up'] = True
        elif parsed_args.disable:
            args['admin_state_up'] = False
            args['is_admin_state_up'] = False

        if parsed_args.project:
            project = identity_common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            )
            args['tenant_id'] = project.id
            args['project_id'] = project.id

        if parsed_args.share:
            args['shared'] = True
            args['is_shared'] = True
        elif parsed_args.no_share:
            args['shared'] = False
            args['is_shared'] = False

        if parsed_args.status:
            args['status'] = parsed_args.status

        if parsed_args.provider_network_type:
            args['provider:network_type'] = parsed_args.provider_network_type
            args['provider_network_type'] = parsed_args.provider_network_type
        if parsed_args.physical_network:
            args['provider:physical_network'] = parsed_args.physical_network
            args['provider_physical_network'] = parsed_args.physical_network
        if parsed_args.segmentation_id:
            args['provider:segmentation_id'] = parsed_args.segmentation_id
            args['provider_segmentation_id'] = parsed_args.segmentation_id

        data = client.networks(**args)

        return (column_headers, (utils.get_item_properties(
            s,
            columns,
            formatters=_formatters,
        ) for s in data))
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity

        if parsed_args.user:
            user = common.find_user(
                identity_client,
                parsed_args.user,
                parsed_args.user_domain,
            )
        elif parsed_args.group:
            group = common.find_group(
                identity_client,
                parsed_args.group,
                parsed_args.group_domain,
            )

        if parsed_args.domain:
            domain = common.find_domain(
                identity_client,
                parsed_args.domain,
            )
        elif parsed_args.project:
            project = common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain,
            )

        # no user or group specified, list all roles in the system
        if not parsed_args.user and not parsed_args.group:
            if not parsed_args.domain:
                columns = ('ID', 'Name')
                data = identity_client.roles.list()
            else:
                columns = ('ID', 'Name', 'Domain')
                data = identity_client.roles.list(domain_id=domain.id)
                for role in data:
                    role.domain = domain.name
        elif parsed_args.user and parsed_args.domain:
            columns = ('ID', 'Name', 'Domain', 'User')
            data = identity_client.roles.list(
                user=user,
                domain=domain,
                os_inherit_extension_inherited=parsed_args.inherited)
            for user_role in data:
                user_role.user = user.name
                user_role.domain = domain.name
            self.log.warning(
                _('Listing assignments using role list is '
                  'deprecated. Use role assignment list --user '
                  '<user-name> --domain <domain-name> --names '
                  'instead.'))
        elif parsed_args.user and parsed_args.project:
            columns = ('ID', 'Name', 'Project', 'User')
            data = identity_client.roles.list(
                user=user,
                project=project,
                os_inherit_extension_inherited=parsed_args.inherited)
            for user_role in data:
                user_role.user = user.name
                user_role.project = project.name
            self.log.warning(
                _('Listing assignments using role list is '
                  'deprecated. Use role assignment list --user '
                  '<user-name> --project <project-name> --names '
                  'instead.'))
        elif parsed_args.user:
            columns = ('ID', 'Name')
            data = identity_client.roles.list(
                user=user,
                domain='default',
                os_inherit_extension_inherited=parsed_args.inherited)
            self.log.warning(
                _('Listing assignments using role list is '
                  'deprecated. Use role assignment list --user '
                  '<user-name> --domain default --names '
                  'instead.'))
        elif parsed_args.group and parsed_args.domain:
            columns = ('ID', 'Name', 'Domain', 'Group')
            data = identity_client.roles.list(
                group=group,
                domain=domain,
                os_inherit_extension_inherited=parsed_args.inherited)
            for group_role in data:
                group_role.group = group.name
                group_role.domain = domain.name
            self.log.warning(
                _('Listing assignments using role list is '
                  'deprecated. Use role assignment list --group '
                  '<group-name> --domain <domain-name> --names '
                  'instead.'))
        elif parsed_args.group and parsed_args.project:
            columns = ('ID', 'Name', 'Project', 'Group')
            data = identity_client.roles.list(
                group=group,
                project=project,
                os_inherit_extension_inherited=parsed_args.inherited)
            for group_role in data:
                group_role.group = group.name
                group_role.project = project.name
            self.log.warning(
                _('Listing assignments using role list is '
                  'deprecated. Use role assignment list --group '
                  '<group-name> --project <project-name> --names '
                  'instead.'))
        else:
            msg = _("Error: If a user or group is specified, "
                    "either --domain or --project must also be "
                    "specified to list role grants.")
            raise exceptions.CommandError(msg)

        return (columns, (utils.get_item_properties(
            s,
            columns,
            formatters={},
        ) for s in data))
 def take_action_network(self, client, parsed_args):
     attrs = _get_attrs(self.app.client_manager, parsed_args)
     obj = client.create_network(**attrs)
     columns = _get_columns(obj)
     data = utils.get_item_properties(obj, columns, formatters=_formatters)
     return (columns, data)
Exemple #54
0
 def take_action(self, parsed_args):
     datastore_client = self.app.client_manager.database.datastores
     datastores = datastore_client.list()
     ds = [utils.get_item_properties(d, self.columns) for d in datastores]
     return self.columns, ds
Exemple #55
0
    def take_action(self, parsed_args):

        volume_client = self.app.client_manager.volume
        compute_client = self.app.client_manager.compute
        identity_client = self.app.client_manager.identity

        def _format_attach(attachments):
            """Return a formatted string of a volume's attached instances

            :param attachments: a volume.attachments field
            :rtype: a string of formatted instances
            """

            msg = ''
            for attachment in attachments:
                server = attachment['server_id']
                if server in server_cache:
                    server = server_cache[server].name
                device = attachment['device']
                msg += 'Attached to %s on %s ' % (server, device)
            return msg

        if parsed_args.long:
            columns = [
                'ID',
                'Name',
                'Status',
                'Size',
                'Volume Type',
                'Bootable',
                'Attachments',
                'Metadata',
            ]
            column_headers = copy.deepcopy(columns)
            column_headers[4] = 'Type'
            column_headers[6] = 'Attached to'
            column_headers[7] = 'Properties'
        else:
            columns = [
                'ID',
                'Name',
                'Status',
                'Size',
                'Attachments',
            ]
            column_headers = copy.deepcopy(columns)
            column_headers[4] = 'Attached to'

        # Cache the server list
        server_cache = {}
        try:
            for s in compute_client.servers.list():
                server_cache[s.id] = s
        except Exception:
            # Just forget it if there's any trouble
            pass

        project_id = None
        if parsed_args.project:
            project_id = identity_common.find_project(
                identity_client,
                parsed_args.project,
                parsed_args.project_domain).id

        user_id = None
        if parsed_args.user:
            user_id = identity_common.find_user(identity_client,
                                                parsed_args.user,
                                                parsed_args.user_domain).id

        # set value of 'all_tenants' when using project option
        all_projects = bool(parsed_args.project) or parsed_args.all_projects

        search_opts = {
            'all_tenants': all_projects,
            'project_id': project_id,
            'user_id': user_id,
            'name': parsed_args.name,
            'status': parsed_args.status,
        }

        data = volume_client.volumes.list(
            search_opts=search_opts,
            marker=parsed_args.marker,
            limit=parsed_args.limit,
        )
        column_headers = utils.backward_compat_col_lister(
            column_headers, parsed_args.columns, {'Display Name': 'Name'})

        return (column_headers,
                (utils.get_item_properties(
                    s, columns,
                    formatters={'Metadata': utils.format_dict,
                                'Attachments': _format_attach},
                ) for s in data))
 def take_action_network(self, client, parsed_args):
     obj = client.find_network(parsed_args.network, ignore_missing=False)
     columns = _get_columns(obj)
     data = utils.get_item_properties(obj, columns, formatters=_formatters)
     return (columns, data)
Exemple #57
0
    def take_action(self, parsed_args):
        identity_client = self.app.client_manager.identity

        domain = None
        if parsed_args.domain:
            domain = common.find_domain(identity_client, parsed_args.domain).id

        group = None
        if parsed_args.group:
            group = common.find_group(identity_client, parsed_args.group,
                                      parsed_args.domain).id

        if parsed_args.project:
            if domain is not None:
                project = utils.find_resource(identity_client.projects,
                                              parsed_args.project,
                                              domain_id=domain).id
            else:
                project = utils.find_resource(
                    identity_client.projects,
                    parsed_args.project,
                ).id

            assignments = identity_client.role_assignments.list(
                project=project)

            # NOTE(stevemar): If a user has more than one role on a project
            # then they will have two entries in the returned data. Since we
            # are looking for any role, let's just track unique user IDs.
            user_ids = set()
            for assignment in assignments:
                if hasattr(assignment, 'user'):
                    user_ids.add(assignment.user['id'])

            # NOTE(stevemar): Call find_resource once we have unique IDs, so
            # it's fewer trips to the Identity API, then collect the data.
            data = []
            for user_id in user_ids:
                user = utils.find_resource(identity_client.users, user_id)
                data.append(user)

        else:
            data = identity_client.users.list(
                domain=domain,
                group=group,
            )

        # Column handling
        if parsed_args.long:
            columns = [
                'ID', 'Name', 'Default Project Id', 'Domain Id', 'Description',
                'Email', 'Enabled'
            ]
            column_headers = copy.deepcopy(columns)
            column_headers[2] = 'Project'
            column_headers[3] = 'Domain'
        else:
            columns = ['ID', 'Name']
            column_headers = columns

        return (column_headers, (utils.get_item_properties(
            s,
            columns,
            formatters={},
        ) for s in data))
Exemple #58
0
    def take_action(self, parsed_args):

        client = self.app.client_manager.ces

        attrs = {}

        attrs['name'] = parsed_args.name
        if parsed_args.enabled:
            attrs['alarm_enabled'] = parsed_args.enabled
        if parsed_args.description:
            attrs['alarm_description'] = parsed_args.description
        attrs['alarm_action_enabled'] = parsed_args.action_enabled
        if parsed_args.level:
            attrs['alarm_level'] = parsed_args.level

        ok_actions = []
        alarm_actions = []

        if parsed_args.action_enabled:
            if (parsed_args.ok_action_type
                    and parsed_args.ok_action_notification_list):
                nl = parsed_args.ok_action_notification_list
                ok_actions.append({
                    'type': parsed_args.ok_action_type,
                    'notificationList': nl
                })
                attrs['ok_actions'] = ok_actions

            if (parsed_args.alarm_action_type
                    and parsed_args.alarm_action_notification_list):

                nl = parsed_args.alarm_action_notification_list
                alarm_actions.append({
                    'type': parsed_args.alarm_action_type,
                    'notificationList': nl
                })
                attrs['alarm_actions'] = alarm_actions

        condition = {
            'comparison_operator': parsed_args.comparison_operator,
            'count': parsed_args.count,
            'filter': parsed_args.filter,
            'period': parsed_args.period,
            'value': parsed_args.value
        }
        if parsed_args.unit:
            condition['unit'] = parsed_args.unit
        attrs['condition'] = condition

        metric = {
            'dimensions': parsed_args.dimensions,
            'metric_name': parsed_args.metric_name,
            'namespace': parsed_args.namespace
        }
        attrs['metric'] = metric

        obj = client.create_alarm(**attrs)

        display_columns, columns = _get_columns(obj)
        data = utils.get_item_properties(obj, columns)

        return (display_columns, data)
Exemple #59
0
    def take_action(self, parsed_args):
        compute_client = self.app.client_manager.sdk_connection.compute
        identity_client = self.app.client_manager.identity

        kwargs = {'name': parsed_args.name}

        public_key = parsed_args.public_key
        if public_key:
            try:
                with io.open(os.path.expanduser(parsed_args.public_key)) as p:
                    public_key = p.read()
            except IOError as e:
                msg = _("Key file %(public_key)s not found: %(exception)s")
                raise exceptions.CommandError(msg % {
                    "public_key": parsed_args.public_key,
                    "exception": e
                })

            kwargs['public_key'] = public_key

        if parsed_args.type:
            if not sdk_utils.supports_microversion(compute_client, '2.2'):
                msg = _(
                    '--os-compute-api-version 2.2 or greater is required to '
                    'support the --type option')
                raise exceptions.CommandError(msg)

            kwargs['key_type'] = parsed_args.type

        if parsed_args.user:
            if not sdk_utils.supports_microversion(compute_client, '2.10'):
                msg = _(
                    '--os-compute-api-version 2.10 or greater is required to '
                    'support the --user option')
                raise exceptions.CommandError(msg)

            kwargs['user_id'] = identity_common.find_user(
                identity_client,
                parsed_args.user,
                parsed_args.user_domain,
            ).id

        keypair = compute_client.create_keypair(**kwargs)

        private_key = parsed_args.private_key
        # Save private key into specified file
        if private_key:
            try:
                with io.open(os.path.expanduser(parsed_args.private_key),
                             'w+') as p:
                    p.write(keypair.private_key)
            except IOError as e:
                msg = _("Key file %(private_key)s can not be saved: "
                        "%(exception)s")
                raise exceptions.CommandError(msg % {
                    "private_key": parsed_args.private_key,
                    "exception": e
                })
        # NOTE(dtroyer): how do we want to handle the display of the private
        #                key when it needs to be communicated back to the user
        #                For now, duplicate nova keypair-add command output
        if public_key or private_key:
            display_columns, columns = _get_keypair_columns(keypair,
                                                            hide_pub_key=True,
                                                            hide_priv_key=True)
            data = utils.get_item_properties(keypair, columns)

            return (display_columns, data)
        else:
            sys.stdout.write(keypair.private_key)
            return ({}, {})
 def take_action(self, parsed_args):
     obj = self.app.client_manager.network.find_subnet(parsed_args.subnet,
                                                       ignore_missing=False)
     columns = _get_columns(obj)
     data = utils.get_item_properties(obj, columns, formatters=_formatters)
     return (columns, data)