Пример #1
0
 def take_action(self, parsed_args):
     client = getattr(self.app.client_manager, "infra-optim")
     allowed_type = ['compute', 'storage', 'baremetal']
     params = {}
     if parsed_args.audit:
         params["audit"] = parsed_args.audit
     if parsed_args.type:
         if parsed_args.type not in allowed_type:
             raise exceptions.CommandError('Type %s error, '
                                           'Please check the valid type!' %
                                           parsed_args.type)
         params["data_model_type"] = parsed_args.type
     try:
         data_model = client.data_model.list(**params)
     except exceptions.HTTPNotFound as exc:
         raise exceptions.CommandError(str(exc))
     # TODO(chenker) Add Storage MODEL_FIELDS when using Storage Datamodel.
     if parsed_args.detail:
         fields = res_fields.COMPUTE_MODEL_LIST_FIELDS
         field_labels = res_fields.COMPUTE_MODEL_LIST_FIELD_LABELS
     else:
         fields = res_fields.COMPUTE_MODEL_SHORT_LIST_FIELDS
         field_labels = res_fields.COMPUTE_MODEL_SHORT_LIST_FIELD_LABELS
     return (field_labels, (self.get_tuple(item, fields)
                            for item in data_model.context))
Пример #2
0
def check_api_version(check_version):
    """Validate version supplied by user

    Returns:
    * True if version is OK
    * False if the version has not been checked and the previous plugin
    check should be performed
    * throws an exception if the version is no good
    """

    infra_api_version = api_versioning.get_api_version(check_version)

    # Bypass X.latest format microversion
    if not infra_api_version.is_latest():
        if infra_api_version > api_versioning.APIVersion("2.0"):
            if not infra_api_version.matches(
                    watcherclient.API_MIN_VERSION,
                    watcherclient.API_MAX_VERSION,
            ):
                msg = "versions supported by client: %(min)s - %(max)s" % {
                    "min": watcherclient.API_MIN_VERSION.get_string(),
                    "max": watcherclient.API_MAX_VERSION.get_string(),
                }
                raise exceptions.CommandError(msg)
    return True
Пример #3
0
    def take_action(self, parsed_args):
        client = getattr(self.app.client_manager, "infra-optim")

        if parsed_args.detail:
            fields = res_fields.GOAL_FIELDS
            field_labels = res_fields.GOAL_FIELD_LABELS
        else:
            fields = res_fields.GOAL_SHORT_LIST_FIELDS
            field_labels = res_fields.GOAL_SHORT_LIST_FIELD_LABELS

        params = {}
        params.update(
            common_utils.common_params_for_list(
                parsed_args, fields, field_labels))

        try:
            data = client.goal.list(**params)
        except exceptions.HTTPNotFound as ex:
            raise exceptions.CommandError(str(ex))

        if parsed_args.formatter == 'table':
            for goal in data:
                # Update the raw efficacy specs with the formatted one
                goal.efficacy_specification = (
                    self._format_indicator_spec_table(goal, parsed_args))

        return (field_labels,
                (utils.get_item_properties(item, fields) for item in data))
Пример #4
0
    def take_action(self, parsed_args):
        client = getattr(self.app.client_manager, "infra-optim")

        params = {}

        # Optional
        if parsed_args.goal:
            params['goal'] = parsed_args.goal

        # Optional
        if parsed_args.strategy:
            params['strategy'] = parsed_args.strategy

        if parsed_args.detail:
            fields = res_fields.AUDIT_FIELDS
            field_labels = res_fields.AUDIT_FIELD_LABELS
        else:
            fields = res_fields.AUDIT_SHORT_LIST_FIELDS
            field_labels = res_fields.AUDIT_SHORT_LIST_FIELD_LABELS

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

        try:
            data = client.audit.list(**params)
            for audit in data:
                if audit.strategy_name is None:
                    audit.strategy_name = 'auto'
        except exceptions.HTTPNotFound as ex:
            raise exceptions.CommandError(str(ex))

        return (field_labels, (utils.get_item_properties(item, fields)
                               for item in data))
Пример #5
0
    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)
Пример #6
0
    def take_action(self, parsed_args):
        client = getattr(self.app.client_manager, "infra-optim")

        params = {}
        if parsed_args.action_plan is not None:
            params['action_plan'] = parsed_args.action_plan
        if parsed_args.audit is not None:
            params['audit'] = parsed_args.audit
        if parsed_args.detail:
            fields = res_fields.ACTION_FIELDS
            field_labels = res_fields.ACTION_FIELD_LABELS
        else:
            fields = res_fields.ACTION_SHORT_LIST_FIELDS
            field_labels = res_fields.ACTION_SHORT_LIST_FIELD_LABELS

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

        try:
            data = client.action.list(**params)
        except exceptions.HTTPNotFound as ex:
            raise exceptions.CommandError(str(ex))

        return (field_labels, (utils.get_item_properties(item, fields)
                               for item in data))
Пример #7
0
    def take_action(self, parsed_args):
        client = getattr(self.app.client_manager, "infra-optim")

        params = {}
        if parsed_args.detail:
            fields = res_fields.STRATEGY_FIELDS
            field_labels = res_fields.STRATEGY_FIELD_LABELS
        else:
            fields = res_fields.STRATEGY_SHORT_LIST_FIELDS
            field_labels = res_fields.STRATEGY_SHORT_LIST_FIELD_LABELS

        if parsed_args.goal:
            params["goal"] = parsed_args.goal

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

        try:
            data = client.strategy.list(**params)
        except exceptions.HTTPNotFound as ex:
            raise exceptions.CommandError(str(ex))

        return (field_labels,
                (utils.get_item_properties(item, fields) for item in data))
Пример #8
0
def common_params_for_list(args, fields, field_labels):
    """Generate 'params' dict that is common for every 'list' command.

    :param args: arguments from command line.
    :param fields: possible fields for sorting.
    :param field_labels: possible field labels for sorting.
    :returns: a dict with params to pass to the client method.
    """
    params = {}
    if args.limit is not None:
        if args.limit < 0:
            raise exc.CommandError(
                _('Expected non-negative --limit, got %s') % args.limit)
        params['limit'] = args.limit

    if args.sort_key is not None:
        # Support using both heading and field name for sort_key
        fields_map = dict(zip(field_labels, fields))
        fields_map.update(zip(fields, fields))
        try:
            sort_key = fields_map[args.sort_key]
        except KeyError:
            raise exc.CommandError(
                _("%(sort_key)s is an invalid field for sorting, "
                  "valid values for --sort-key are: %(valid)s") % {
                      'sort_key': args.sort_key,
                      'valid': list(fields_map)
                  })
        params['sort_key'] = sort_key
    if args.sort_dir is not None:
        if args.sort_dir not in ('asc', 'desc'):
            raise exc.CommandError(
                _("%s is an invalid value for sort direction, "
                  "valid values for --sort-dir are: 'asc', 'desc'") %
                args.sort_dir)
        params['sort_dir'] = args.sort_dir

    marker = getattr(args, 'marker', None)
    if marker is not None:
        params['marker'] = marker
    params['detail'] = args.detail

    return params
Пример #9
0
    def take_action(self, parsed_args):
        client = getattr(self.app.client_manager, "infra-optim")

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

        columns = res_fields.ACTION_FIELDS
        column_headers = res_fields.ACTION_FIELD_LABELS

        return column_headers, utils.get_item_properties(action, columns)
Пример #10
0
    def take_action(self, parsed_args):
        client = getattr(self.app.client_manager, "infra-optim")

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

        strategy.parameters_spec = self._format_spec(strategy)
        columns = res_fields.STRATEGY_FIELDS
        column_headers = res_fields.STRATEGY_FIELD_LABELS

        return column_headers, utils.get_item_properties(strategy, columns)
Пример #11
0
    def take_action(self, parsed_args):
        client = getattr(self.app.client_manager, "infra-optim")

        try:
            requirements = client.strategy.state(parsed_args.strategy)
        except exceptions.HTTPNotFound as exc:
            raise exceptions.CommandError(str(exc))
        requirements = self._format_spec(requirements)
        columns = res_fields.STRATEGY_STATE_FIELDS
        column_headers = res_fields.STRATEGY_STATE_FIELD_LABELS

        return (column_headers,
                (utils.get_item_properties(item, columns)
                    for item in requirements))
Пример #12
0
    def take_action(self, parsed_args):
        client = getattr(self.app.client_manager, "infra-optim")

        try:
            audit = client.audit.get(parsed_args.audit)
            if audit.strategy_name is None:
                audit.strategy_name = 'auto'
        except exceptions.HTTPNotFound as exc:
            raise exceptions.CommandError(str(exc))

        columns = res_fields.AUDIT_FIELDS
        column_headers = res_fields.AUDIT_FIELD_LABELS

        return column_headers, utils.get_item_properties(audit, columns)
Пример #13
0
    def take_action(self, parsed_args):
        client = getattr(self.app.client_manager, "infra-optim")

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

        columns = res_fields.SCORING_ENGINE_FIELDS
        column_headers = res_fields.SCORING_ENGINE_FIELD_LABELS

        return column_headers, utils.get_item_properties(
            scoring_engine, columns)
    def take_action(self, parsed_args):
        client = getattr(self.app.client_manager, "infra-optim")

        audit_template_uuid = parsed_args.audit_template

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

        columns = res_fields.AUDIT_TEMPLATE_FIELDS
        column_headers = res_fields.AUDIT_TEMPLATE_FIELD_LABELS

        return column_headers, utils.get_item_properties(
            audit_template, columns)
Пример #15
0
def args_array_to_patch(op, attributes):
    patch = []
    for attr in attributes:
        # Sanitize
        if not attr.startswith('/'):
            attr = '/' + attr

        if op in ['add', 'replace']:
            path, value = split_and_deserialize(attr)
            patch.append({'op': op, 'path': path, 'value': value})

        elif op == "remove":
            # For remove only the key is needed
            patch.append({'op': op, 'path': attr})
        else:
            raise exc.CommandError(_('Unknown PATCH operation: %s') % op)
    return patch
Пример #16
0
def split_and_deserialize(string):
    """Split and try to JSON deserialize a string.

    Gets a string with the KEY=VALUE format, split it (using '=' as the
    separator) and try to JSON deserialize the VALUE.

    :returns: A tuple of (key, value).
    """
    try:
        key, value = string.split("=", 1)
    except ValueError:
        raise exc.CommandError(_('Attributes must be a list of '
                                 'PATH=VALUE not "%s"') % string)
    try:
        value = json.loads(value)
    except ValueError:
        pass

    return (key, value)
Пример #17
0
    def take_action(self, parsed_args):
        client = getattr(self.app.client_manager, "infra-optim")

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

        columns = res_fields.GOAL_FIELDS
        column_headers = res_fields.GOAL_FIELD_LABELS

        if parsed_args.formatter == 'table':
            indicator_specs = ''
            # Format complex data types:
            for indicator_spec in goal.efficacy_specification:
                indicator_specs += self._format_indicator_spec_table(
                    indicator_spec, parsed_args)
            # Update the raw efficacy specs with the formatted one
            goal.efficacy_specification = indicator_specs

        return column_headers, utils.get_item_properties(goal, columns)