コード例 #1
0
ファイル: stack.py プロジェクト: bopopescu/OpenStack-Ocata
 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
コード例 #2
0
 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
コード例 #3
0
    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)
コード例 #4
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
     })
コード例 #5
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
コード例 #6
0
ファイル: stack.py プロジェクト: openstack/python-heatclient
 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
コード例 #7
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
コード例 #8
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
コード例 #9
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
コード例 #10
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
コード例 #11
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.deployment:
            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.deployment)})
コード例 #12
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)
コード例 #13
0
ファイル: stack.py プロジェクト: openstack/python-heatclient
 def get_parser(self, prog_name):
     parser = self._get_parser(prog_name,
                               _('Stack(s) to cancel (name or ID)'),
                               _('Wait for cancel to complete'))
     parser.add_argument('--no-rollback',
                         action='store_true',
                         help=_('Cancel without rollback'))
     return parser
コード例 #14
0
ファイル: exc.py プロジェクト: openstack/python-heatclient
 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})
コード例 #15
0
ファイル: exc.py プロジェクト: openstack/python-heatclient
 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
コード例 #16
0
 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
コード例 #17
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
コード例 #18
0
ファイル: stack.py プロジェクト: openstack/python-heatclient
    def get_parser(self, prog_name):
        parser = super(ExportStack, self).get_parser(prog_name)
        parser.add_argument('stack',
                            metavar='<stack>',
                            help=_('Name or ID of stack to export'))
        parser.add_argument('--output-file',
                            metavar='<output-file>',
                            help=_('File to output export data'))

        return parser
コード例 #19
0
ファイル: stack.py プロジェクト: openstack/python-heatclient
    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
コード例 #20
0
ファイル: stack.py プロジェクト: openstack/python-heatclient
 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
コード例 #21
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
コード例 #22
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
コード例 #23
0
def get_template_contents(template_file=None,
                          template_url=None,
                          template_object=None,
                          object_request=None,
                          files=None,
                          existing=False,
                          fetch_child=True):

    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]'
              ' or %(arg4)s') % {
                  'arg1': '--template-file',
                  'arg2': '--template-url',
                  'arg3': '--template-object',
                  'arg4': '--existing'
              })

    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
            })
    if files is None:
        files = {}

    if fetch_child:
        tmpl_base_url = utils.base_url_for_url(template_url)
        resolve_template_get_files(template, files, tmpl_base_url, is_object,
                                   object_request)
    return files, template
コード例 #24
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
コード例 #25
0
ファイル: stack.py プロジェクト: openstack/python-heatclient
 def get_parser(self, prog_name):
     parser = self._get_parser(
         prog_name,
         _('Stack(s) to cancel (name or ID)'),
         _('Wait for cancel to complete')
     )
     parser.add_argument(
         '--no-rollback',
         action='store_true',
         help=_('Cancel without rollback')
     )
     return parser
コード例 #26
0
    def get_parser(self, prog_name):
        parser = super(FunctionList, self).get_parser(prog_name)
        parser.add_argument(
            'template_version',
            metavar='<template-version>',
            help=_('Template version to get the functions for'))
        parser.add_argument('--with_conditions',
                            default=False,
                            action='store_true',
                            help=_('Show condition functions for template.'))

        return parser
コード例 #27
0
ファイル: stack.py プロジェクト: openstack/python-heatclient
    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)

        return self.dict2columns(output)
コード例 #28
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
コード例 #29
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
コード例 #30
0
ファイル: stack.py プロジェクト: openstack/python-heatclient
 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
コード例 #31
0
 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
コード例 #32
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
コード例 #33
0
ファイル: stack_failures.py プロジェクト: numvc/LuxoftBot
 def get_parser(self, prog_name):
     parser = super(ListStackFailures, self).get_parser(prog_name)
     parser.add_argument(
         'stack',
         metavar='<stack>',
         help=_('Stack to display (name or ID)'),
     )
     parser.add_argument(
         '--long',
         action='store_true',
         default=False,
         help=_('Show full deployment logs in output'),
     )
     return parser
コード例 #34
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
コード例 #35
0
ファイル: stack.py プロジェクト: openstack/python-heatclient
 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('-y',
                         '--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
コード例 #36
0
ファイル: stack.py プロジェクト: openstack/python-heatclient
    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
コード例 #37
0
ファイル: stack.py プロジェクト: openstack/python-heatclient
 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
コード例 #38
0
 def get_parser(self, prog_name):
     parser = super(ListStackFailures, self).get_parser(prog_name)
     parser.add_argument(
         'stack',
         metavar='<stack>',
         help=_('Stack to display (name or ID)'),
     )
     parser.add_argument(
         '--long',
         action='store_true',
         default=False,
         help=_('Show full deployment logs in output'),
     )
     return parser
コード例 #39
0
ファイル: stack.py プロジェクト: openstack/python-heatclient
    def get_parser(self, prog_name):
        parser = super(ExportStack, self).get_parser(prog_name)
        parser.add_argument(
            'stack',
            metavar='<stack>',
            help=_('Name or ID of stack to export')
        )
        parser.add_argument(
            '--output-file',
            metavar='<output-file>',
            help=_('File to output export data')
        )

        return parser
コード例 #40
0
    def get_parser(self, prog_name):
        parser = super(FunctionList, self).get_parser(prog_name)
        parser.add_argument(
            'template_version',
            metavar='<template-version>',
            help=_('Template version to get the functions for')
        )
        parser.add_argument(
            '--with_conditions',
            default=False,
            action='store_true',
            help=_('Show condition functions for template.')
        )

        return parser
コード例 #41
0
ファイル: base.py プロジェクト: openstack/python-heatclient
    def find(self, base_url=None, **kwargs):
        """Find a single item with attributes matching ``**kwargs``.

        :param base_url: if provided, the generated URL will be appended to it
        """
        kwargs = self._filter_kwargs(kwargs)

        rl = self._list(
            '%(base_url)s%(query)s' % {
                'base_url': self.build_url(base_url=base_url, **kwargs),
                'query': '?%s' % parse.urlencode(kwargs) if kwargs else '',
            },
            self.collection_key)
        num = len(rl)

        if num == 0:
            msg = _("No %(name)s matching %(args)s.") % {
                'name': self.resource_class.__name__,
                'args': kwargs
            }
            raise exceptions.NotFound(msg)
        elif num > 1:
            raise exceptions.NoUniqueMatch
        else:
            return rl[0]
コード例 #42
0
def parse(tmpl_str):
    """Takes a string and returns a dict containing the parsed structure.

    This includes determination of whether the string is using the
    JSON or YAML format.
    """
    # strip any whitespace before the check
    tmpl_str = tmpl_str.strip()
    if tmpl_str.startswith('{'):
        tpl = json.loads(tmpl_str)
    else:
        try:
            tpl = yaml.load(tmpl_str, Loader=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:
                tpl = yaml.load(tmpl_str, Loader=yaml.SafeLoader)
            except yaml.YAMLError as yea:
                raise ValueError(yea)
        else:
            if tpl is None:
                tpl = {}
    # Looking for supported version keys in the loaded template
    if not ('HeatTemplateFormatVersion' in tpl
            or 'heat_template_version' in tpl
            or 'AWSTemplateFormatVersion' in tpl):
        raise ValueError(_("Template format version not found."))
    return tpl
コード例 #43
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
コード例 #44
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)
コード例 #45
0
ファイル: stack.py プロジェクト: openstack/python-heatclient
def _stack_action(stack, parsed_args, heat_client, action, action_name=None):
    if parsed_args.wait:
        # find the last event to use as the marker
        events = event_utils.get_events(heat_client,
                                        stack_id=stack,
                                        event_args={'sort_dir': 'desc'},
                                        limit=1)
        marker = events[0].id if events else None

    try:
        action(stack)
    except heat_exc.HTTPNotFound:
        msg = _('Stack not found: %s') % stack
        raise exc.CommandError(msg)

    if parsed_args.wait:
        s = heat_client.stacks.get(stack)
        stack_status, msg = event_utils.poll_for_events(
            heat_client, s.stack_name, action=action_name, marker=marker)
        if action_name:
            if stack_status == '%s_FAILED' % action_name:
                raise exc.CommandError(msg)
        else:
            if stack_status.endswith('_FAILED'):
                raise exc.CommandError(msg)

    return heat_client.stacks.get(stack)
コード例 #46
0
 def get_parser(self, prog_name):
     parser = super(DeleteConfig, self).get_parser(prog_name)
     parser.add_argument('config',
                         metavar='<config>',
                         nargs='+',
                         help=_('IDs of the software configs to delete'))
     return parser
コード例 #47
0
    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()))
コード例 #48
0
 def get_parser(self, prog_name):
     parser = super(DeleteDeployment, self).get_parser(prog_name)
     parser.add_argument('deployment',
                         metavar='<deployment>',
                         nargs='+',
                         help=_('ID of the deployment(s) to delete.'))
     return parser
コード例 #49
0
ファイル: utils.py プロジェクト: openstack/python-heatclient
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
コード例 #50
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
コード例 #51
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
コード例 #52
0
def parse(tmpl_str):
    """Takes a string and returns a dict containing the parsed structure.

    This includes determination of whether the string is using the
    JSON or YAML format.
    """
    # strip any whitespace before the check
    tmpl_str = tmpl_str.strip()
    if tmpl_str.startswith('{'):
        tpl = json.loads(tmpl_str)
    else:
        try:
            tpl = yaml.load(tmpl_str, Loader=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:
                tpl = yaml.load(tmpl_str, Loader=yaml.SafeLoader)
            except yaml.YAMLError as yea:
                raise ValueError(yea)
        else:
            if tpl is None:
                tpl = {}
    # Looking for supported version keys in the loaded template
    if not ('HeatTemplateFormatVersion' in tpl or 'heat_template_version'
            in tpl or 'AWSTemplateFormatVersion' in tpl):
        raise ValueError(_("Template format version not found."))
    return tpl
コード例 #53
0
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)

        heat_client = self.app.client_manager.orchestration
        try:
            data = heat_client.software_deployments.get(
                deployment_id=parsed_args.deployment)
        except heat_exc.HTTPNotFound:
            raise exc.CommandError(
                _('Software Deployment not found: %s')
                % parsed_args.deployment)
        else:
            columns = [
                'id',
                'server_id',
                'config_id',
                'creation_time',
                'updated_time',
                'status',
                'status_reason',
                'input_values',
                'action',
            ]
            if parsed_args.long:
                columns.append('output_values')
            return columns, utils.get_item_properties(data, columns)
コード例 #54
0
    def find(self, base_url=None, **kwargs):
        """Find a single item with attributes matching ``**kwargs``.

        :param base_url: if provided, the generated URL will be appended to it
        """
        kwargs = self._filter_kwargs(kwargs)

        rl = self._list(
            '%(base_url)s%(query)s' % {
                'base_url': self.build_url(base_url=base_url, **kwargs),
                'query': '?%s' % parse.urlencode(kwargs) if kwargs else '',
            },
            self.collection_key)
        num = len(rl)

        if num == 0:
            msg = _("No %(name)s matching %(args)s.") % {
                'name': self.resource_class.__name__,
                'args': kwargs
            }
            raise exceptions.NotFound(msg)
        elif num > 1:
            raise exceptions.NoUniqueMatch
        else:
            return rl[0]
コード例 #55
0
ファイル: utils.py プロジェクト: openstack/python-heatclient
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)
コード例 #56
0
    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()))
コード例 #57
0
 def get_parser(self, prog_name):
     parser = super(ShowMetadataDeployment, self).get_parser(prog_name)
     parser.add_argument(
         'server',
         metavar='<server>',
         help=_('ID of the server to fetch deployments for'))
     return parser
コード例 #58
0
    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)

        heat_client = self.app.client_manager.orchestration
        try:
            data = heat_client.software_deployments.get(
                deployment_id=parsed_args.deployment)
        except heat_exc.HTTPNotFound:
            raise exc.CommandError(
                _('Software Deployment not found: %s') %
                parsed_args.deployment)
        else:
            columns = [
                'id',
                'server_id',
                'config_id',
                'creation_time',
                'updated_time',
                'status',
                'status_reason',
                'input_values',
                'action',
            ]
            if parsed_args.long:
                columns.append('output_values')
            return columns, utils.get_item_properties(data, columns)
コード例 #59
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]'
                                 ' or %(arg4)s') %
                               {
                                   'arg1': '--template-file',
                                   'arg2': '--template-url',
                                   'arg3': '--template-object',
                                   'arg4': '--existing'})

    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
コード例 #60
0
 def get_parser(self, prog_name):
     parser = super(ListEvent, 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 resource to show events for. Note: this cannot '
                'be specified with --nested-depth')
     )
     parser.add_argument(
         '--filter',
         metavar='<key=value>',
         action='append',
         help=_('Filter parameters to apply on returned events')
     )
     parser.add_argument(
         '--limit',
         metavar='<limit>',
         type=int,
         help=_('Limit the number of events returned')
     )
     parser.add_argument(
         '--marker',
         metavar='<id>',
         help=_('Only return events that appear after the given ID')
     )
     parser.add_argument(
         '--nested-depth',
         metavar='<depth>',
         type=int,
         help=_('Depth of nested stacks from which to display events. '
                'Note: this cannot be specified with --resource')
     )
     parser.add_argument(
         '--sort',
         metavar='<key>[:<direction>]',
         action='append',
         help=_('Sort output by selected keys and directions (asc or desc) '
                '(default: asc). Specify multiple times to sort on '
                'multiple keys. Sort key can be: '
                '"event_time" (default), "resource_name", "links", '
                '"logical_resource_id", "resource_status", '
                '"resource_status_reason", "physical_resource_id", or '
                '"id". You can leave the key empty and specify ":desc" '
                'for sorting by reverse time.')
     )
     parser.add_argument(
         '--follow',
         action='store_true',
         help=_('Print events until process is halted')
     )
     return parser