def _set_template_fields(hc, args, fields):
    if args.template_file:
        tpl = open(args.template_file).read()
        if tpl.startswith('{'):
            try:
                fields['template'] = jsonutils.loads(tpl)
            except ValueError as e:
                raise exc.CommandError(
                    "Cannot parse template file: %s" % e)
        else:
            fields['template'] = tpl
    elif args.template_url:
        fields['template_url'] = args.template_url
    elif args.template_object:
        template_body = hc.http_client.raw_request('GET', args.template_object)
        if template_body:
            try:
                fields['template'] = jsonutils.loads(template_body)
            except ValueError as e:
                raise exc.CommandError(
                    "Cannot parse template file: %s" % e)
        else:
            raise exc.CommandError('Could not fetch template from %s'
                                   % args.template_object)
    else:
        raise exc.CommandError('Need to specify exactly one of '
                               '--template-file, --template-url '
                               'or --template-object')
    def test_template_show_cfn(self):
        self._script_keystone_client()
        template_data = open(os.path.join(TEST_VAR_DIR,
                                          'minimal.template')).read()
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            template_data)
        resp_dict = jsonutils.loads(template_data)
        http.HTTPClient.json_request(
            'GET', '/stacks/teststack/template').AndReturn((resp, resp_dict))

        self.m.ReplayAll()

        show_text = self.shell('template-show teststack')
        required = [
            '{',
            '  "AWSTemplateFormatVersion": "2010-09-09"',
            '  "Outputs": {}',
            '  "Resources": {}',
            '  "Parameters": {}',
            '}'
        ]
        for r in required:
            self.assertRegexpMatches(show_text, r)
Beispiel #3
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 = template_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: %s %s' %
                               (args.id, args.resource))
Beispiel #4
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 = template_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: %s %s' %
                               (args.id, args.resource))
Beispiel #5
0
 def __init__(self, message=None):
     super(HTTPException, self).__init__(message)
     try:
         self.error = jsonutils.loads(message)
         if 'error' not in self.error:
             raise KeyError('Key "error" not exists')
     except KeyError:
         # NOTE(jianingy): If key 'error' happens not exist,
         # self.message becomes no sense. In this case, we
         # return doc of current exception class instead.
         self.error = {'error':
                       {'message': self.__class__.__doc__}}
     except Exception:
         self.error = {'error':
                       {'message': self.message or self.__class__.__doc__}}
Beispiel #6
0
 def __init__(self, message=None):
     super(HTTPException, self).__init__(message)
     try:
         self.error = jsonutils.loads(message)
         if 'error' not in self.error:
             raise KeyError('Key "error" not exists')
     except KeyError:
         # NOTE(jianingy): If key 'error' happens not exist,
         # self.message becomes no sense. In this case, we
         # return doc of current exception class instead.
         self.error = {'error': {'message': self.__class__.__doc__}}
     except Exception:
         self.error = {
             'error': {
                 'message': self.message or self.__class__.__doc__
             }
         }
    def json_request(self, method, url, **kwargs):
        kwargs.setdefault('headers', {})
        kwargs['headers'].setdefault('Content-Type', 'application/json')
        kwargs['headers'].setdefault('Accept', 'application/json')

        if 'body' in kwargs:
            kwargs['body'] = jsonutils.dumps(kwargs['body'])

        resp, body_str = self._http_request(url, method, **kwargs)

        if 'application/json' in resp.getheader('content-type', None):
            body = body_str
            try:
                body = jsonutils.loads(body)
            except ValueError:
                LOG.error('Could not decode response body as JSON')
        else:
            body = None

        return resp, body
    def test_stack_abandon(self):
        self._script_keystone_client()

        resp_dict = {"stack": {
            "id": "1",
            "stack_name": "teststack",
            "stack_status": 'CREATE_COMPLETE',
            "creation_time": "2012-10-25T01:58:47Z"
        }}

        abandoned_stack = {
            "action": "CREATE",
            "status": "COMPLETE",
            "name": "teststack",
            "id": "1",
            "resources": {
                "foo": {
                    "name": "foo",
                    "resource_id": "test-res-id",
                    "action": "CREATE",
                    "status": "COMPLETE",
                    "resource_data": {},
                    "metadata": {},
                }
            }
        }

        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            jsonutils.dumps(resp_dict))
        http.HTTPClient.json_request(
            'GET', '/stacks/teststack/1').AndReturn((resp, resp_dict))
        http.HTTPClient.json_request(
            'DELETE',
            '/stacks/teststack/1/abandon').AndReturn((resp, abandoned_stack))

        self.m.ReplayAll()
        abandon_resp = self.shell('stack-abandon teststack/1')
        self.assertEqual(abandoned_stack, jsonutils.loads(abandon_resp))
Beispiel #9
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 = template_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: %s %s" % (args.id, args.resource))
Beispiel #10
0
 def json(self):
     return jsonutils.loads(self.content)
Beispiel #11
0
 def json(self):
     return jsonutils.loads(self.content)