Exemplo n.º 1
0
 def get_parser(self, prog_name):
     parser = super(StackHookClear, self).get_parser(prog_name)
     parser.add_argument(
         'stack',
         metavar='<stack>',
         help=_('Stack to display (name or ID)')
     )
     parser.add_argument(
         '--pre-create',
         action='store_true',
         help=_('Clear the pre-create hooks')
     )
     parser.add_argument(
         '--pre-update',
         action='store_true',
         help=_('Clear the pre-update hooks')
     )
     parser.add_argument(
         '--pre-delete',
         action='store_true',
         help=_('Clear the pre-delete hooks')
     )
     parser.add_argument(
         'hook',
         metavar='<resource>',
         nargs='+',
         help=_('Resource names with hooks to clear. Resources '
                'in nested stacks can be set using slash as a separator: '
                'nested_stack/another/my_resource. You can use wildcards '
                'to match multiple stacks or resources: '
                'nested_stack/an*/*_resource')
     )
     return parser
Exemplo n.º 2
0
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        hc = self.app.client_manager.orchestration
        failure_count = 0

        for deploy_id in parsed_args.id:
            try:
                sd = hc.software_deployments.get(deployment_id=deploy_id)
                hc.software_deployments.delete(
                    deployment_id=deploy_id)
            except Exception as e:
                if isinstance(e, heat_exc.HTTPNotFound):
                    print(_('Deployment with ID %s not found') % deploy_id)
                else:
                    print(_('Deployment with ID %s failed to delete')
                          % deploy_id)
                failure_count += 1
                continue
            # just try best to delete the corresponding config
            try:
                config_id = getattr(sd, 'config_id')
                hc.software_configs.delete(config_id=config_id)
            except Exception:
                print(_('Failed to delete the correlative config'
                        ' %(config_id)s of deployment %(deploy_id)s') %
                      {'config_id': config_id, 'deploy_id': deploy_id})

        if failure_count:
            raise exc.CommandError(_('Unable to delete %(count)s of the '
                                     '%(total)s deployments.') %
                                   {'count': failure_count,
                                   'total': len(parsed_args.id)})
Exemplo n.º 3
0
def _stack_action(parsed_args, heat_client, action, good_status, bad_status):
    rows = []
    for stack in parsed_args.stack:
        try:
            action(stack)
        except heat_exc.HTTPNotFound:
            msg = _('Stack not found: %s') % stack
            raise exc.CommandError(msg)

        if parsed_args.wait:
            if not utils.wait_for_status(heat_client.stacks.get, stack,
                                         status_field='stack_status',
                                         success_status=good_status,
                                         error_status=bad_status):
                err = _("Error waiting for status from stack %s") % stack
                raise exc.CommandError(err)

        data = heat_client.stacks.get(stack)
        columns = [
            'ID',
            'Stack Name',
            'Stack Status',
            'Creation Time',
            'Updated Time'
        ]
        rows += [utils.get_dict_properties(data.to_dict(), columns)]

    return (columns, rows)
Exemplo n.º 4
0
 def get_parser(self, prog_name):
     parser = super(Validate, self).get_parser(prog_name)
     parser.add_argument(
         '-e', '--environment',
         metavar='<environment>',
         action='append',
         help=_('Path to the environment. Can be specified multiple times')
     )
     parser.add_argument(
         '--show-nested',
         action='store_true',
         help=_('Resolve parameters from nested templates as well')
     )
     parser.add_argument(
         '--parameter',
         metavar='<key=value>',
         action='append',
         help=_('Parameter values used to create the stack. This can be '
                'specified multiple times')
     )
     parser.add_argument(
         '--ignore-errors',
         metavar='<error1,error2,...>',
         help=_('List of heat errors to ignore')
     )
     parser.add_argument(
         '-t', '--template',
         metavar='<template>',
         required=True,
         help=_('Path to the template')
     )
     return parser
Exemplo n.º 5
0
 def __str__(self):
     self.details = _("Requested version of Heat API is not" "available.")
     return (_("%(name)s (HTTP %(code)s) %(details)s") % {
         'name': reflection.get_class_name(self, fully_qualified=False),
         'code': self.code,
         'details': self.details
     })
Exemplo n.º 6
0
def parse(env_str):
    """Takes a string and returns a dict containing the parsed structure.

    This includes determination of whether the string is using the
    YAML format.
    """
    try:
        env = yaml.load(env_str, Loader=template_format.yaml_loader)
    except yaml.YAMLError:
        # NOTE(prazumovsky): we need to return more informative error for
        # user, so use SafeLoader, which return error message with template
        # snippet where error has been occurred.
        try:
            env = yaml.load(env_str, Loader=yaml.SafeLoader)
        except yaml.YAMLError as yea:
            raise ValueError(yea)
    else:
        if env is None:
            env = {}
        elif not isinstance(env, dict):
            raise ValueError(
                _('The environment is not a valid '
                  'YAML mapping data type.'))

    for param in env:
        if param not in SECTIONS:
            raise ValueError(_('environment has wrong section "%s"') % param)

    return env
Exemplo n.º 7
0
 def get_parser(self, prog_name):
     parser = super(Validate, self).get_parser(prog_name)
     parser.add_argument('-t',
                         '--template',
                         metavar='<template>',
                         required=True,
                         help=_('Path to the template'))
     parser.add_argument(
         '-e',
         '--environment',
         metavar='<environment>',
         action='append',
         help=_('Path to the environment. Can be specified multiple times'))
     parser.add_argument(
         '--show-nested',
         action='store_true',
         help=_('Resolve parameters from nested templates as well'))
     parser.add_argument(
         '--parameter',
         metavar='<key=value>',
         action='append',
         help=_('Parameter values used to create the stack. This can be '
                'specified multiple times'))
     parser.add_argument('--ignore-errors',
                         metavar='<error1,error2,...>',
                         help=_('List of heat errors to ignore'))
     return parser
Exemplo n.º 8
0
 def get_parser(self, prog_name):
     parser = super(CreateConfig, self).get_parser(prog_name)
     parser.add_argument(
         'name',
         metavar='<config-name>',
         help=_('Name of the software config to create')
     )
     parser.add_argument(
         '--config-file',
         metavar='<config-file>',
         help=_('Path to JSON/YAML containing map defining '
                '<inputs>, <outputs>, and <options>')
     )
     parser.add_argument(
         '--definition-file',
         metavar='<destination-file>',
         help=_('Path to software config script/data')
     )
     parser.add_argument(
         '--group',
         metavar='<group>',
         default='Heat::Ungrouped',
         help=_('Group name of tool expected by the software config')
     )
     return parser
Exemplo n.º 9
0
 def __str__(self):
     self.details = _("Requested version of Heat API is not" "available.")
     return (_("%(name)s (HTTP %(code)s) %(details)s") % {
         'name': self.__class__.__name__,
         'code': self.code,
         'details': self.details
     })
def parse(env_str):
    """Takes a string and returns a dict containing the parsed structure.

    This includes determination of whether the string is using the
    YAML format.
    """
    try:
        env = yaml.load(env_str, Loader=template_format.yaml_loader)
    except yaml.YAMLError:
        # NOTE(prazumovsky): we need to return more informative error for
        # user, so use SafeLoader, which return error message with template
        # snippet where error has been occurred.
        try:
            env = yaml.load(env_str, Loader=yaml.SafeLoader)
        except yaml.YAMLError as yea:
            raise ValueError(yea)
    else:
        if env is None:
            env = {}
        elif not isinstance(env, dict):
            raise ValueError(_('The environment is not a valid '
                             'YAML mapping data type.'))

    for param in env:
        if param not in SECTIONS:
            raise ValueError(_('environment has wrong section "%s"') % param)

    return env
Exemplo n.º 11
0
def do_resource_signal(hc, args):
    '''Send a signal to a resource.'''
    fields = {'stack_id': args.id,
              'resource_name': args.resource}
    data = args.data
    data_file = args.data_file
    if data and data_file:
        raise exc.CommandError(_('Can only specify one of data and data-file'))
    if data_file:
        data_url = utils.normalise_file_path_to_url(data_file)
        data = request.urlopen(data_url).read()
    if data:
        if isinstance(data, six.binary_type):
            data = data.decode('utf-8')
        try:
            data = jsonutils.loads(data)
        except ValueError as ex:
            raise exc.CommandError(_('Data should be in JSON format: %s') % ex)
        if not isinstance(data, dict):
            raise exc.CommandError(_('Data should be a JSON dict'))
        fields['data'] = data
    try:
        hc.resources.signal(**fields)
    except exc.HTTPNotFound:
        raise exc.CommandError(_('Stack or resource not found: '
                                 '%(id)s %(resource)s') %
                               {'id': args.id, 'resource': args.resource})
Exemplo n.º 12
0
def do_output_show(hc, args):
    '''Show a specific stack output.'''
    if (not args.all and args.output is None or
            args.all and args.output is not None):
        raise exc.CommandError(
            _('Error: either %(output)s or %(all)s argument is needed.')
            % {'output': '<OUTPUT NAME>', 'all': '--all'})
    try:
        stack = hc.stacks.get(stack_id=args.id)
    except exc.HTTPNotFound:
        raise exc.CommandError(_('Stack not found: %s') % args.id)
    else:
        if args.all:
            print(utils.json_formatter(stack.to_dict().get('outputs', [])))
        else:
            for output in stack.to_dict().get('outputs', []):
                if output['output_key'] == args.output:
                    if 'output_error' in output:
                        msg = _("Error: %s") % output['output_error']
                        raise exc.CommandError(msg)
                    else:
                        value = output['output_value']
                    break
            else:
                return

            if (args.format == 'json'
                    or isinstance(value, dict)
                    or isinstance(value, list)):
                print(utils.json_formatter(value))
            else:
                print(value)
Exemplo n.º 13
0
def do_deployment_output_show(hc, args):
    '''Show a specific stack output.'''
    if (not args.all and args.output is None or
            args.all and args.output is not None):
        raise exc.CommandError(
            _('Error: either %(output)s or %(all)s argument is needed.')
            % {'output': '<OUTPUT NAME>', 'all': '--all'})
    try:
        sd = hc.software_deployments.get(deployment_id=args.id)
    except exc.HTTPNotFound:
        raise exc.CommandError(_('Deployment not found: %s') % args.id)
    outputs = sd.to_dict().get('output_values', {})

    if args.all:
        print(utils.json_formatter(outputs))
    else:
        for output_key, value in outputs.items():
            if output_key == args.output:
                break
        else:
            return

        if (args.format == 'json'
                or isinstance(value, dict)
                or isinstance(value, list)):
            print(utils.json_formatter(value))
        else:
            print(value)
 def get_parser(self, prog_name):
     parser = super(ShowOutputDeployment, self).get_parser(prog_name)
     parser.add_argument(
         'deployment',
         metavar='<deployment>',
         help=_('ID of deployment to show the output for')
     )
     parser.add_argument(
         'output',
         metavar='<output-name>',
         nargs='?',
         default=None,
         help=_('Name of an output to display')
     )
     parser.add_argument(
         '--all',
         default=False,
         action='store_true',
         help=_('Display all deployment outputs')
     )
     parser.add_argument(
         '--long',
         action='store_true',
         default=False,
         help='Show full deployment logs in output',
     )
     return parser
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)

        heat_client = self.app.client_manager.orchestration
        if (not parsed_args.all and parsed_args.output is None or
                parsed_args.all and parsed_args.output is not None):
            raise exc.CommandError(
                _('Error: either %(output)s or %(all)s argument is needed.')
                % {'output': '<output-name>', 'all': '--all'})
        try:
            sd = heat_client.software_deployments.get(
                deployment_id=parsed_args.deployment)
        except heat_exc.HTTPNotFound:
            raise exc.CommandError(_('Deployment not found: %s')
                                   % parsed_args.deployment)
        outputs = sd.output_values
        if outputs:
            if parsed_args.all:
                print('output_values:\n')
                for k in outputs.keys():
                    format_utils.print_software_deployment_output(
                        data=outputs, name=k, long=parsed_args.long)
            else:
                if parsed_args.output not in outputs:
                    msg = (_('Output %(output)s does not exist in deployment'
                             ' %(deployment)s')
                           % {'output': parsed_args.output,
                              'deployment': parsed_args.deployment})
                    raise exc.CommandError(msg)
                else:
                    print('output_value:\n')
                    format_utils.print_software_deployment_output(
                        data=outputs, name=parsed_args.output)
Exemplo n.º 16
0
    def take_action(self, parsed_args):
        self.log.debug('take_action(%s)', parsed_args)

        client = self.app.client_manager.orchestration

        if not parsed_args.all and parsed_args.output is None:
            msg = _('Either <OUTPUT NAME> or --all must be specified.')
            raise exc.CommandError(msg)

        if parsed_args.all and parsed_args.output is not None:
            msg = _('Cannot specify both <OUTPUT NAME> and --all.')
            raise exc.CommandError(msg)

        if parsed_args.all:
            try:
                stack = client.stacks.get(parsed_args.stack)
            except heat_exc.HTTPNotFound:
                msg = _('Stack not found: %s') % parsed_args.stack
                raise exc.CommandError(msg)

            outputs = stack.to_dict().get('outputs', [])
            columns = []
            values = []
            for output in outputs:
                columns.append(output['output_key'])
                values.append(heat_utils.json_formatter(output))

            return columns, values

        try:
            output = client.stacks.output_show(parsed_args.stack,
                                               parsed_args.output)['output']
        except heat_exc.HTTPNotFound:
            msg = _('Stack %(id)s or output %(out)s not found.') % {
                'id': parsed_args.stack,
                'out': parsed_args.output
            }
            try:
                output = None
                stack = client.stacks.get(parsed_args.stack).to_dict()
                for o in stack.get('outputs', []):
                    if o['output_key'] == parsed_args.output:
                        output = o
                        break
                if output is None:
                    raise exc.CommandError(msg)
            except heat_exc.HTTPNotFound:
                raise exc.CommandError(msg)

        if 'output_error' in output:
            msg = _('Output error: %s') % output['output_error']
            raise exc.CommandError(msg)

        if (isinstance(output['output_value'], list)
                or isinstance(output['output_value'], dict)):
            output['output_value'] = heat_utils.json_formatter(
                output['output_value'])

        return self.dict2columns(output)
Exemplo n.º 17
0
 def __str__(self):
     self.details = _("Requested version of Heat API is not"
                      "available.")
     return (_("%(name)s (HTTP %(code)s) %(details)s") %
             {
             'name': reflection.get_class_name(self, fully_qualified=False),
             'code': self.code,
             'details': self.details})
Exemplo n.º 18
0
 def __str__(self):
     message = self.error['error'].get('message', 'Internal Error')
     if verbose:
         traceback = self.error['error'].get('traceback', '')
         return (_('ERROR: %(message)s\n%(traceback)s') %
                 {'message': message, 'traceback': traceback})
     else:
         return _('ERROR: %s') % message
Exemplo n.º 19
0
 def __str__(self):
     self.details = _("Requested version of Heat API is not"
                      "available.")
     return (_("%(name)s (HTTP %(code)s) %(details)s") %
             {
                 'name': self.__class__.__name__,
                 'code': self.code,
                 'details': self.details})
Exemplo n.º 20
0
    def take_action(self, parsed_args):
        self.log.debug('take_action(%s)', parsed_args)

        client = self.app.client_manager.orchestration

        if not parsed_args.all and parsed_args.output is None:
            msg = _('Either <OUTPUT NAME> or --all must be specified.')
            raise exc.CommandError(msg)

        if parsed_args.all and parsed_args.output is not None:
            msg = _('Cannot specify both <OUTPUT NAME> and --all.')
            raise exc.CommandError(msg)

        if parsed_args.all:
            try:
                stack = client.stacks.get(parsed_args.stack)
            except heat_exc.HTTPNotFound:
                msg = _('Stack not found: %s') % parsed_args.stack
                raise exc.CommandError(msg)

            outputs = stack.to_dict().get('outputs', [])
            columns = []
            values = []
            for output in outputs:
                columns.append(output['output_key'])
                values.append(heat_utils.json_formatter(output))

            return columns, values

        try:
            output = client.stacks.output_show(parsed_args.stack,
                                               parsed_args.output)['output']
        except heat_exc.HTTPNotFound:
            msg = _('Stack %(id)s or output %(out)s not found.') % {
                'id': parsed_args.stack, 'out': parsed_args.output}
            try:
                output = None
                stack = client.stacks.get(parsed_args.stack).to_dict()
                for o in stack.get('outputs', []):
                    if o['output_key'] == parsed_args.output:
                        output = o
                        break
                if output is None:
                    raise exc.CommandError(msg)
            except heat_exc.HTTPNotFound:
                raise exc.CommandError(msg)

        if 'output_error' in output:
            msg = _('Output error: %s') % output['output_error']
            raise exc.CommandError(msg)

        if (isinstance(output['output_value'], list) or
                isinstance(output['output_value'], dict)):
            output['output_value'] = heat_utils.json_formatter(
                output['output_value'])

        return self.dict2columns(output)
Exemplo n.º 21
0
 def strip_endpoint(self, location):
     if location is None:
         message = _("Location not returned with 302")
         raise exc.InvalidEndpoint(message=message)
     elif location.lower().startswith(self.endpoint.lower()):
         return location[len(self.endpoint):]
     else:
         message = _("Prohibited endpoint redirect %s") % location
         raise exc.InvalidEndpoint(message=message)
Exemplo n.º 22
0
 def strip_endpoint(self, location):
     if location is None:
         message = _("Location not returned with 302")
         raise exc.InvalidEndpoint(message=message)
     elif location.lower().startswith(self.endpoint.lower()):
         return location[len(self.endpoint):]
     else:
         message = _("Prohibited endpoint redirect %s") % location
         raise exc.InvalidEndpoint(message=message)
 def get_parser(self, prog_name):
     parser = super(ShowDeployment, self).get_parser(prog_name)
     parser.add_argument('deployment',
                         metavar='<deployment>',
                         help=_('ID of the deployment'))
     parser.add_argument('--long',
                         action='store_true',
                         help=_('Show more fields in output'))
     return parser
Exemplo n.º 24
0
 def get_parser(self, prog_name):
     parser = super(StackHookPoll, self).get_parser(prog_name)
     parser.add_argument('stack',
                         metavar='<stack>',
                         help=_('Stack to display (name or ID)'))
     parser.add_argument(
         '--nested-depth',
         metavar='<nested-depth>',
         help=_('Depth of nested stacks from which to display hooks'))
     return parser
Exemplo n.º 25
0
 def get_parser(self, prog_name):
     parser = super(ListConfig, self).get_parser(prog_name)
     parser.add_argument('--limit',
                         metavar='<limit>',
                         help=_('Limit the number of configs returned'))
     parser.add_argument(
         '--marker',
         metavar='<id>',
         help=_('Return configs that appear after the given config ID'))
     return parser
 def get_parser(self, prog_name):
     parser = super(ListDeployment, self).get_parser(prog_name)
     parser.add_argument(
         '--server',
         metavar='<server>',
         help=_('ID of the server to fetch deployments for'))
     parser.add_argument('--long',
                         action='store_true',
                         help=_('List more fields in output'))
     return parser
Exemplo n.º 27
0
 def __str__(self):
     message = self.error['error'].get('message', 'Internal Error')
     if verbose:
         traceback = self.error['error'].get('traceback', '')
         return (_('ERROR: %(message)s\n%(traceback)s') % {
             'message': message,
             'traceback': traceback
         })
     else:
         return _('ERROR: %s') % message
Exemplo n.º 28
0
    def get_parser(self, prog_name):
        parser = super(AbandonStack, self).get_parser(prog_name)
        parser.add_argument('stack',
                            metavar='<stack>',
                            help=_('Name or ID of stack to abandon'))
        parser.add_argument('--output-file',
                            metavar='<output-file>',
                            help=_('File to output abandon results'))

        return parser
Exemplo n.º 29
0
 def get_parser(self, prog_name):
     parser = super(ShowConfig, self).get_parser(prog_name)
     parser.add_argument('config',
                         metavar='<config>',
                         help=_('ID of the config'))
     parser.add_argument(
         '--config-only',
         default=False,
         action="store_true",
         help=_('Only display the value of the <config> property.'))
     return parser
Exemplo n.º 30
0
    def get_parser(self, prog_name):
        parser = super(ShowEvent, self).get_parser(prog_name)
        parser.add_argument('stack',
                            metavar='<stack>',
                            help=_('Name or ID of stack to show events for'))
        parser.add_argument('resource',
                            metavar='<resource>',
                            help=_('Name of the resource event belongs to'))
        parser.add_argument('event',
                            metavar='<event>',
                            help=_('ID of event to display details for'))

        return parser
 def get_parser(self, prog_name):
     parser = super(ShowDeployment, self).get_parser(prog_name)
     parser.add_argument(
         'deployment',
         metavar='<deployment>',
         help=_('ID of the deployment')
     )
     parser.add_argument(
         '--long',
         action='store_true',
         help=_('Show more fields in output')
     )
     return parser
Exemplo n.º 32
0
 def get_parser(self, prog_name):
     parser = super(DeleteStack, self).get_parser(prog_name)
     parser.add_argument('stack',
                         metavar='<stack>',
                         nargs='+',
                         help=_('Stack(s) to delete (name or ID)'))
     parser.add_argument('--yes',
                         action='store_true',
                         help=_('Skip yes/no prompt (assume yes)'))
     parser.add_argument('--wait',
                         action='store_true',
                         help=_('Wait for stack delete to complete'))
     return parser
Exemplo n.º 33
0
 def get_parser(self, prog_name):
     parser = super(ListConfig, self).get_parser(prog_name)
     parser.add_argument(
         '--limit',
         metavar='<limit>',
         help=_('Limit the number of configs returned')
     )
     parser.add_argument(
         '--marker',
         metavar='<id>',
         help=_('Return configs that appear after the given config ID')
     )
     return parser
Exemplo n.º 34
0
 def get_parser(self, prog_name):
     parser = super(StackHookPoll, self).get_parser(prog_name)
     parser.add_argument(
         'stack',
         metavar='<stack>',
         help=_('Stack to display (name or ID)')
     )
     parser.add_argument(
         '--nested-depth',
         metavar='<nested-depth>',
         help=_('Depth of nested stacks from which to display hooks')
     )
     return parser
Exemplo n.º 35
0
 def get_parser(self, prog_name):
     parser = super(ListDeployment, self).get_parser(prog_name)
     parser.add_argument(
         '--server',
         metavar='<SERVER>',
         help=_('ID of the server to fetch deployments for')
     )
     parser.add_argument(
         '--long',
         action='store_true',
         help=_('List more fields in output')
     )
     return parser
Exemplo n.º 36
0
def get_template_contents(template_file=None,
                          template_url=None,
                          template_object=None,
                          object_request=None,
                          files=None,
                          existing=False):

    is_object = False
    # Transform a bare file path to a file:// URL.
    if template_file:
        template_url = utils.normalise_file_path_to_url(template_file)

    if template_url:
        tpl = request.urlopen(template_url).read()

    elif template_object:
        is_object = True
        template_url = template_object
        tpl = object_request and object_request('GET', template_object)
    elif existing:
        return {}, None
    else:
        raise exc.CommandError(
            _('Need to specify exactly one of '
              '%(arg1)s, %(arg2)s or %(arg3)s') % {
                  'arg1': '--template-file',
                  'arg2': '--template-url',
                  'arg3': '--template-object'
              })

    if not tpl:
        raise exc.CommandError(
            _('Could not fetch template from %s') % template_url)

    try:
        if isinstance(tpl, six.binary_type):
            tpl = tpl.decode('utf-8')
        template = template_format.parse(tpl)
    except ValueError as e:
        raise exc.CommandError(
            _('Error parsing template %(url)s %(error)s') % {
                'url': template_url,
                'error': e
            })

    tmpl_base_url = utils.base_url_for_url(template_url)
    if files is None:
        files = {}
    resolve_template_get_files(template, files, tmpl_base_url, is_object,
                               object_request)
    return files, template
Exemplo n.º 37
0
 def get_parser(self, prog_name):
     parser = super(ShowConfig, self).get_parser(prog_name)
     parser.add_argument(
         'config',
         metavar='<config>',
         help=_('ID of the config')
     )
     parser.add_argument(
         '--config-only',
         default=False,
         action="store_true",
         help=_('Only display the value of the <config> property.')
     )
     return parser
Exemplo n.º 38
0
    def get_parser(self, prog_name):
        parser = super(AbandonStack, self).get_parser(prog_name)
        parser.add_argument(
            'stack',
            metavar='<stack>',
            help=_('Name or ID of stack to abandon')
        )
        parser.add_argument(
            '--output-file',
            metavar='<output-file>',
            help=_('File to output abandon results')
        )

        return parser
Exemplo n.º 39
0
 def get_parser(self, prog_name):
     parser = super(OutputShowStack, self).get_parser(prog_name)
     parser.add_argument('stack',
                         metavar='<stack>',
                         help=_('Name or ID of stack to query'))
     parser.add_argument('output',
                         metavar='<output>',
                         nargs='?',
                         default=None,
                         help=_('Name of an output to display'))
     parser.add_argument('--all',
                         action='store_true',
                         help=_('Display all stack outputs'))
     return parser
Exemplo n.º 40
0
 def __init__(
     self, message=None, details=None, response=None, request_id=None, url=None, method=None, http_status=None
 ):
     self.http_status = http_status or self.http_status
     self.message = message or self.message
     self.details = details
     self.request_id = request_id
     self.response = response
     self.url = url
     self.method = method
     formatted_string = _("%s (HTTP %s)") % (self.message, self.http_status)
     if request_id:
         formatted_string += _(" (Request-ID: %s)") % request_id
     super(HttpError, self).__init__(formatted_string)
Exemplo n.º 41
0
def format_parameters(params, parse_semicolon=True):
    """Reformat parameters into dict of format expected by the API."""

    if not params:
        return {}

    if parse_semicolon:
        # expect multiple invocations of --parameters but fall back
        # to ; delimited if only one --parameters is specified
        if len(params) == 1:
            params = params[0].split(";")

    parameters = {}
    for p in params:
        try:
            (n, v) = p.split(("="), 1)
        except ValueError:
            msg = _("Malformed parameter(%s). Use the key=value format.") % p
            raise exc.CommandError(msg)

        if n not in parameters:
            parameters[n] = v
        else:
            if not isinstance(parameters[n], list):
                parameters[n] = [parameters[n]]
            parameters[n].append(v)

    return parameters
Exemplo n.º 42
0
    def _discover_auth_versions(self, session, auth_url):
        # discover the API versions the server is supporting base on the
        # given URL
        v2_auth_url = None
        v3_auth_url = None
        try:
            ks_discover = discover.Discover(session=session, auth_url=auth_url)
            v2_auth_url = ks_discover.url_for('2.0')
            v3_auth_url = ks_discover.url_for('3.0')
        except ks_exc.ClientException:
            # Identity service may not support discover API version.
            # Lets trying to figure out the API version from the original URL.
            url_parts = urlparse.urlparse(auth_url)
            (scheme, netloc, path, params, query, fragment) = url_parts
            path = path.lower()
            if path.startswith('/v3'):
                v3_auth_url = auth_url
            elif path.startswith('/v2'):
                v2_auth_url = auth_url
            else:
                # not enough information to determine the auth version
                msg = _('Unable to determine the Keystone version '
                        'to authenticate with using the given '
                        'auth_url. Identity service may not support API '
                        'version discovery. Please provide a versioned '
                        'auth_url instead.')
                raise exc.CommandError(msg)

        return (v2_auth_url, v3_auth_url)
    def take_action(self, parsed_args):
        self.log.debug('take_action(%s)', parsed_args)

        client = self.app.client_manager.orchestration

        config = {}
        if parsed_args.config:
            try:
                config = client.software_configs.get(parsed_args.config)
            except heat_exc.HTTPNotFound:
                msg = (_('Software configuration not found: %s') %
                       parsed_args.config)
                raise exc.CommandError(msg)

        derived_params = deployment_utils.build_derived_config_params(
            parsed_args.action,
            config,
            parsed_args.name,
            heat_utils.format_parameters(parsed_args.input_value, False),
            parsed_args.server,
            parsed_args.signal_transport,
            signal_id=deployment_utils.build_signal_id(client, parsed_args)
        )
        derived_config = client.software_configs.create(**derived_params)

        sd = client.software_deployments.create(
            config_id=derived_config.id,
            server_id=parsed_args.server,
            action=parsed_args.action,
            status='IN_PROGRESS'
        )

        return zip(*sorted(sd.to_dict().items()))
Exemplo n.º 44
0
class HttpVersionNotSupported(HttpServerError):
    """HTTP 505 - HttpVersion Not Supported.

    The server does not support the HTTP protocol version used in the request.
    """
    http_status = 505
    message = _("HTTP Version Not Supported")
Exemplo n.º 45
0
class HttpServerError(HttpError):
    """Server-side HTTP error.

    Exception for cases in which the server is aware that it has
    erred or is incapable of performing the request.
    """
    message = _("HTTP Server Error")
Exemplo n.º 46
0
def _show_config(heat_client, config_id, config_only):
    try:
        sc = heat_client.software_configs.get(config_id=config_id)
    except heat_exc.HTTPNotFound:
        raise exc.CommandError(_('Configuration not found: %s') % config_id)

    columns = None
    rows = None

    if config_only:
        print(sc.config)
    else:
        columns = (
            'id',
            'name',
            'group',
            'config',
            'inputs',
            'outputs',
            'options',
            'creation_time',
        )
        rows = utils.get_dict_properties(sc.to_dict(), columns)

    return columns, rows
Exemplo n.º 47
0
class RequestTimeout(HTTPClientError):
    """HTTP 408 - Request Timeout.

    The server timed out waiting for the request.
    """
    http_status = 408
    message = _("Request Timeout")
Exemplo n.º 48
0
class RequestUriTooLong(HTTPClientError):
    """HTTP 414 - Request-URI Too Long.

    The URI provided was too long for the server to process.
    """
    http_status = 414
    message = _("Request-URI Too Long")
Exemplo n.º 49
0
class ProxyAuthenticationRequired(HTTPClientError):
    """HTTP 407 - Proxy Authentication Required.

    The client must first authenticate itself with the proxy.
    """
    http_status = 407
    message = _("Proxy Authentication Required")
Exemplo n.º 50
0
class PaymentRequired(HTTPClientError):
    """HTTP 402 - Payment Required.

    Reserved for future use.
    """
    http_status = 402
    message = _("Payment Required")
Exemplo n.º 51
0
class BadRequest(HTTPClientError):
    """HTTP 400 - Bad Request.

    The request cannot be fulfilled due to bad syntax.
    """
    http_status = 400
    message = _("Bad Request")
Exemplo n.º 52
0
def format_parameters(params, parse_semicolon=True):
    '''Reformat parameters into dict of format expected by the API.'''

    if not params:
        return {}

    if parse_semicolon:
        # expect multiple invocations of --parameters but fall back
        # to ; delimited if only one --parameters is specified
        if len(params) == 1:
            params = params[0].split(';')

    parameters = {}
    for p in params:
        try:
            (n, v) = p.split(('='), 1)
        except ValueError:
            msg = _('Malformed parameter(%s). Use the key=value format.') % p
            raise exc.CommandError(msg)

        if n not in parameters:
            parameters[n] = v
        else:
            if not isinstance(parameters[n], list):
                parameters[n] = [parameters[n]]
            parameters[n].append(v)

    return parameters
Exemplo n.º 53
0
def format_output(output, format="yaml"):
    """Format the supplied dict as specified."""
    output_format = format.lower()
    try:
        return supported_formats[output_format](output)
    except KeyError:
        raise exc.HTTPUnsupported(_("The format(%s) is unsupported.") % output_format)
Exemplo n.º 54
0
def find_resource(manager, name_or_id):
    """Helper for the _find_* methods."""
    # first try to get entity as integer id
    try:
        if isinstance(name_or_id, int) or name_or_id.isdigit():
            return manager.get(int(name_or_id))
    except exc.NotFound:
        pass

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

    # finally try to find entity by name
    try:
        return manager.find(name=name_or_id)
    except exc.NotFound:
        msg = _("No %(name)s with a name or ID of "
                "'%(name_or_id)s' exists.") % \
            {
                'name': manager.resource_class.__name__.lower(),
                'name_or_id': name_or_id
            }
        raise exc.CommandError(msg)
Exemplo n.º 55
0
class ServiceUnavailable(HttpServerError):
    """HTTP 503 - Service Unavailable.

    The server is currently unavailable.
    """
    http_status = 503
    message = _("Service Unavailable")
Exemplo n.º 56
0
class ExpectationFailed(HTTPClientError):
    """HTTP 417 - Expectation Failed.

    The server cannot meet the requirements of the Expect request-header field.
    """
    http_status = 417
    message = _("Expectation Failed")
Exemplo n.º 57
0
def find_resource(manager, name_or_id):
    """Helper for the _find_* methods."""
    # first try to get entity as integer id
    try:
        if isinstance(name_or_id, int) or name_or_id.isdigit():
            return manager.get(int(name_or_id))
    except exc.NotFound:
        pass

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

    # finally try to find entity by name
    try:
        return manager.find(name=name_or_id)
    except exc.NotFound:
        msg = _("No %(name)s with a name or ID of " "'%(name_or_id)s' exists.") % {
            "name": manager.resource_class.__name__.lower(),
            "name_or_id": name_or_id,
        }
        raise exc.CommandError(msg)
Exemplo n.º 58
0
class InternalServerError(HttpServerError):
    """HTTP 500 - Internal Server Error.

    A generic error message, given when no more specific message is suitable.
    """
    http_status = 500
    message = _("Internal Server Error")
Exemplo n.º 59
0
def event_log_formatter(events):
    """Return the events in log format."""
    event_log = []
    log_format = _(
        "%(event_date)s  %(event_time)s  %(event_id)s " "[%(rsrc_name)s]: %(rsrc_status)s  %(rsrc_status_reason)s"
    )
    for event in events:
        event_time = getattr(event, "event_time", "")
        time_date = event_time.split("T")
        try:
            event_time = time_date[0]
            event_date = time_date[1][:-1]
        except IndexError:
            event_time = event_date = ""

        log = log_format % {
            "event_date": event_date,
            "event_time": event_time,
            "event_id": getattr(event, "id", ""),
            "rsrc_name": getattr(event, "resource_name", ""),
            "rsrc_status": getattr(event, "resource_status", ""),
            "rsrc_status_reason": getattr(event, "resource_status_reason", ""),
        }
        event_log.append(log)

    return "\n".join(event_log)