示例#1
0
    def test_create_server_detect_from_image(self):
        """If user doesn't pass in diskConfig for server, use image metadata
        to specify AUTO or MANUAL.
        """
        req = fakes.HTTPRequest.blank('/fake/servers')
        req.method = 'POST'
        req.content_type = 'application/json'
        body = {'server': {
                  'name': 'server_test',
                  'imageRef': 'a440c04b-79fa-479c-bed1-0b816eaec379',
                  'flavorRef': '1',
               }}

        req.body = utils.dumps(body)
        res = req.get_response(self.app)
        server_dict = utils.loads(res.body)['server']
        self.assertDiskConfig(server_dict, 'MANUAL')

        req = fakes.HTTPRequest.blank('/fake/servers')
        req.method = 'POST'
        req.content_type = 'application/json'
        body = {'server': {
                  'name': 'server_test',
                  'imageRef': '70a599e0-31e7-49b7-b260-868f441e862b',
                  'flavorRef': '1',
               }}

        req.body = utils.dumps(body)
        res = req.get_response(self.app)
        server_dict = utils.loads(res.body)['server']
        self.assertDiskConfig(server_dict, 'AUTO')
示例#2
0
    def process(self, req, *args, **kwargs):
        for pre_handler in self.pre_handlers:
            pre_handler(req)

        res = req.get_response(self.application)

        # Don't call extensions if the main application returned an
        # unsuccessful status
        successful = 200 <= res.status_int < 400
        if not successful:
            return res

        # Deserialize the response body, if any
        body = None
        if res.body:
            body = utils.loads(res.body)

        # currently request handlers are un-ordered
        for handler in self.handlers:
            res = handler(req, res, body)

        # Reserialize the response body
        if body is not None:
            res.body = utils.dumps(body)

        return res
示例#3
0
    def serialize(self, request, content_type, default_serializers=None):
        """Serializes the wrapped object.

        Utility method for serializing the wrapped object.  Returns a
        webob.Response object.
        """

        serializer = self.get_serializer(content_type, default_serializers)()

        response = webob.Response()
        response.status_int = self.code
        for hdr, value in self._headers.items():
            response.headers[hdr] = value
        response.headers['Content-Type'] = content_type
        if self.obj is not None:
            # TODO(Vek): When lazy serialization is retired, so can
            #            this inner 'if'...
            lazy_serialize = request.environ.get('engine.lazy_serialize',
                                                 False)
            if lazy_serialize:
                response.body = utils.dumps(self.obj)
                request.environ['engine.simple_serial'] = serializer
                # NOTE(Vek): Temporary ugly hack to support xml
                #            templates in extensions, until we can
                #            fold extensions into Resource and do away
                #            with lazy serialization...
                if _MEDIA_TYPE_MAP.get(content_type) == 'xml':
                    request.environ['engine.template'] = serializer
            else:
                response.body = serializer.serialize(self.obj)

        return response
示例#4
0
    def process(self, req, *args, **kwargs):
        for pre_handler in self.pre_handlers:
            pre_handler(req)

        res = req.get_response(self.application)

        # Don't call extensions if the main application returned an
        # unsuccessful status
        successful = 200 <= res.status_int < 400
        if not successful:
            return res

        # Deserialize the response body, if any
        body = None
        if res.body:
            body = utils.loads(res.body)

        # currently request handlers are un-ordered
        for handler in self.handlers:
            res = handler(req, res, body)

        # Reserialize the response body
        if body is not None:
            res.body = utils.dumps(body)

        return res
示例#5
0
    def serialize(self, request, content_type, default_serializers=None):
        """Serializes the wrapped object.

        Utility method for serializing the wrapped object.  Returns a
        webob.Response object.
        """

        serializer = self.get_serializer(content_type, default_serializers)()

        response = webob.Response()
        response.status_int = self.code
        for hdr, value in self._headers.items():
            response.headers[hdr] = value
        response.headers['Content-Type'] = content_type
        if self.obj is not None:
            # TODO(Vek): When lazy serialization is retired, so can
            #            this inner 'if'...
            lazy_serialize = request.environ.get('engine.lazy_serialize', False)
            if lazy_serialize:
                response.body = utils.dumps(self.obj)
                request.environ['engine.simple_serial'] = serializer
                # NOTE(Vek): Temporary ugly hack to support xml
                #            templates in extensions, until we can
                #            fold extensions into Resource and do away
                #            with lazy serialization...
                if _MEDIA_TYPE_MAP.get(content_type) == 'xml':
                    request.environ['engine.template'] = serializer
            else:
                response.body = serializer.serialize(self.obj)

        return response
示例#6
0
 def __do_request(self, path, context, **kwargs):
     req = wsgi.Request.blank(path)
     req.method = 'POST'
     req.body = urllib.urlencode({'json': utils.dumps(kwargs)})
     req.environ['x7.context'] = context
     resp = req.get_response(self.app)
     try:
         return utils.loads(resp.body)
     except Exception:
         return resp.body
示例#7
0
 def __do_request(self, path, context, **kwargs):
     req = wsgi.Request.blank(path)
     req.method = 'POST'
     req.body = urllib.urlencode({'json': utils.dumps(kwargs)})
     req.environ['x7.context'] = context
     resp = req.get_response(self.app)
     try:
         return utils.loads(resp.body)
     except Exception:
         return resp.body
示例#8
0
    def __call__(self, req):
        # Read request signature and access id.
        try:
            signature = req.params['Signature']
            access = req.params['AWSAccessKeyId']
        except KeyError:
            raise webob.exc.HTTPBadRequest()

        # Make a copy of args for authentication and signature verification.
        auth_params = dict(req.params)
        # Not part of authentication args
        auth_params.pop('Signature')

        # Authenticate the request.
        creds = {
            'ec2Credentials': {
                'access': access,
                'signature': signature,
                'host': req.host,
                'verb': req.method,
                'path': req.path,
                'params': auth_params,
            }
        }
        creds_json = utils.dumps(creds)
        headers = {'Content-Type': 'application/json'}

        # Disable "has no x member" pylint error
        # for httplib and urlparse
        # pylint: disable-msg=E1101
        o = urlparse(FLAGS.keystone_ec2_url)
        if o.scheme == "http":
            conn = httplib.HTTPConnection(o.netloc)
        else:
            conn = httplib.HTTPSConnection(o.netloc)
        conn.request('POST', o.path, body=creds_json, headers=headers)
        response = conn.getresponse().read()
        conn.close()

        # NOTE(vish): We could save a call to keystone by
        #             having keystone return token, tenant,
        #             user, and roles from this call.

        result = utils.loads(response)
        try:
            token_id = result['access']['token']['id']
        except (AttributeError, KeyError):
            raise webob.exc.HTTPBadRequest()

        # Authenticated!
        req.headers['X-Auth-Token'] = token_id
        return self.application
示例#9
0
 def test_update_server_invalid_disk_config(self):
     """Return BadRequest if user passes an invalid diskConfig value."""
     req = fakes.HTTPRequest.blank(
         '/fake/servers/%s' % MANUAL_INSTANCE_UUID)
     req.method = 'PUT'
     req.content_type = 'application/json'
     body = {'server': {'RAX-DCF:diskConfig': 'server_test'}}
     req.body = utils.dumps(body)
     res = req.get_response(self.app)
     self.assertEqual(res.status_int, 400)
     expected_msg = '{"badRequest": {"message": "RAX-DCF:diskConfig must'\
                    ' be either \'MANUAL\' or \'AUTO\'.", "code": 400}}'
     self.assertEqual(res.body, expected_msg)
示例#10
0
    def __call__(self, req):
        # Read request signature and access id.
        try:
            signature = req.params['Signature']
            access = req.params['AWSAccessKeyId']
        except KeyError:
            raise webob.exc.HTTPBadRequest()

        # Make a copy of args for authentication and signature verification.
        auth_params = dict(req.params)
        # Not part of authentication args
        auth_params.pop('Signature')

        # Authenticate the request.
        creds = {'ec2Credentials': {'access': access,
                                    'signature': signature,
                                    'host': req.host,
                                    'verb': req.method,
                                    'path': req.path,
                                    'params': auth_params,
                                   }}
        creds_json = utils.dumps(creds)
        headers = {'Content-Type': 'application/json'}

        # Disable "has no x member" pylint error
        # for httplib and urlparse
        # pylint: disable-msg=E1101
        o = urlparse(FLAGS.keystone_ec2_url)
        if o.scheme == "http":
            conn = httplib.HTTPConnection(o.netloc)
        else:
            conn = httplib.HTTPSConnection(o.netloc)
        conn.request('POST', o.path, body=creds_json, headers=headers)
        response = conn.getresponse().read()
        conn.close()

        # NOTE(vish): We could save a call to keystone by
        #             having keystone return token, tenant,
        #             user, and roles from this call.

        result = utils.loads(response)
        try:
            token_id = result['access']['token']['id']
        except (AttributeError, KeyError):
            raise webob.exc.HTTPBadRequest()

        # Authenticated!
        req.headers['X-Auth-Token'] = token_id
        return self.application
示例#11
0
    def test_create_server_override_manual(self):
        req = fakes.HTTPRequest.blank('/fake/servers')
        req.method = 'POST'
        req.content_type = 'application/json'
        body = {'server': {
                  'name': 'server_test',
                  'imageRef': 'cedef40a-ed67-4d10-800e-17455edce175',
                  'flavorRef': '1',
                  'RAX-DCF:diskConfig': 'MANUAL'
               }}

        req.body = utils.dumps(body)
        res = req.get_response(self.app)
        server_dict = utils.loads(res.body)['server']
        self.assertDiskConfig(server_dict, 'MANUAL')
示例#12
0
    def serialize_body(self, request, response, data, content_type, action):
        response.headers['Content-Type'] = content_type
        if data is not None:
            serializer = self.get_body_serializer(content_type)
            lazy_serialize = request.environ.get('engine.lazy_serialize', False)
            if lazy_serialize:
                response.body = utils.dumps(data)
                request.environ['engine.serializer'] = serializer
                request.environ['engine.action'] = action
                if (hasattr(serializer, 'get_template') and
                    'engine.template' not in request.environ):

                    template = serializer.get_template(action)
                    request.environ['engine.template'] = template
            else:
                response.body = serializer.serialize(data, action)
示例#13
0
    def serialize_body(self, request, response, data, content_type, action):
        response.headers['Content-Type'] = content_type
        if data is not None:
            serializer = self.get_body_serializer(content_type)
            lazy_serialize = request.environ.get('engine.lazy_serialize',
                                                 False)
            if lazy_serialize:
                response.body = utils.dumps(data)
                request.environ['engine.serializer'] = serializer
                request.environ['engine.action'] = action
                if (hasattr(serializer, 'get_template')
                        and 'engine.template' not in request.environ):

                    template = serializer.get_template(action)
                    request.environ['engine.template'] = template
            else:
                response.body = serializer.serialize(data, action)
示例#14
0
    def _pre_POST_servers(self, req):
        # NOTE(sirp): deserialization currently occurs *after* pre-processing
        # extensions are called. Until extensions are refactored so that
        # deserialization occurs earlier, we have to perform the
        # deserialization ourselves.
        content_type = req.content_type

        if 'xml' in content_type:
            node = minidom.parseString(req.body)
            server = node.getElementsByTagName('server')[0]
            api_value = server.getAttribute(self.API_DISK_CONFIG)
            if api_value:
                value = disk_config_from_api(api_value)
                server.setAttribute(self.INTERNAL_DISK_CONFIG, str(value))
                req.body = str(node.toxml())
        else:
            body = utils.loads(req.body)
            server = body['server']
            api_value = server.get(self.API_DISK_CONFIG)
            if api_value:
                value = disk_config_from_api(api_value)
                server[self.INTERNAL_DISK_CONFIG] = value
                req.body = utils.dumps(body)
示例#15
0
    def _pre_POST_servers(self, req):
        # NOTE(sirp): deserialization currently occurs *after* pre-processing
        # extensions are called. Until extensions are refactored so that
        # deserialization occurs earlier, we have to perform the
        # deserialization ourselves.
        content_type = req.content_type

        if 'xml' in content_type:
            node = minidom.parseString(req.body)
            server = node.getElementsByTagName('server')[0]
            api_value = server.getAttribute(self.API_DISK_CONFIG)
            if api_value:
                value = disk_config_from_api(api_value)
                server.setAttribute(self.INTERNAL_DISK_CONFIG, str(value))
                req.body = str(node.toxml())
        else:
            body = utils.loads(req.body)
            server = body['server']
            api_value = server.get(self.API_DISK_CONFIG)
            if api_value:
                value = disk_config_from_api(api_value)
                server[self.INTERNAL_DISK_CONFIG] = value
                req.body = utils.dumps(body)
示例#16
0
 def default(self, data):
     return utils.dumps(data)
示例#17
0
 def default(self, data):
     return utils.dumps(data)