コード例 #1
0
ファイル: test_disk_config.py プロジェクト: BillTheBest/nova
    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
ファイル: test_disk_config.py プロジェクト: Razique/nova
    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')
コード例 #3
0
ファイル: wsgi.py プロジェクト: rbenali/nova
    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('nova.lazy_serialize', False)
            if lazy_serialize:
                response.body = utils.dumps(self.obj)
                request.environ['nova.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['nova.template'] = serializer
            else:
                response.body = serializer.serialize(self.obj)

        return response
コード例 #4
0
def serialize_remote_exception(failure_info):
    """Prepares exception data to be sent over rpc.

    Failure_info should be a sys.exc_info() tuple.

    """
    tb = traceback.format_exception(*failure_info)
    failure = failure_info[1]
    LOG.error(_("Returning exception %s to caller"), unicode(failure))
    LOG.error(tb)

    kwargs = {}
    if hasattr(failure, 'kwargs'):
        kwargs = failure.kwargs

    data = {
        'class': str(failure.__class__.__name__),
        'module': str(failure.__class__.__module__),
        'message': unicode(failure),
        'tb': tb,
        'args': failure.args,
        'kwargs': kwargs
    }

    json_data = utils.dumps(data)

    return json_data
コード例 #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('nova.lazy_serialize', False)
            if lazy_serialize:
                response.body = utils.dumps(self.obj)
                request.environ['nova.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['nova.template'] = serializer
            else:
                response.body = serializer.serialize(self.obj)

        return response
コード例 #6
0
ファイル: extensions.py プロジェクト: chrisglass/nova
    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
コード例 #7
0
ファイル: extensions.py プロジェクト: nicoleLiu/nova
    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
コード例 #8
0
ファイル: common.py プロジェクト: Cygnet/nova
def serialize_remote_exception(failure_info):
    """Prepares exception data to be sent over rpc.

    Failure_info should be a sys.exc_info() tuple.

    """
    tb = traceback.format_exception(*failure_info)
    failure = failure_info[1]
    LOG.error(_("Returning exception %s to caller"), unicode(failure))
    LOG.error(tb)

    kwargs = {}
    if hasattr(failure, 'kwargs'):
        kwargs = failure.kwargs

    data = {
        'class': str(failure.__class__.__name__),
        'module': str(failure.__class__.__module__),
        'message': unicode(failure),
        'tb': tb,
        'args': failure.args,
        'kwargs': kwargs
    }

    json_data = utils.dumps(data)

    return json_data
コード例 #9
0
    def __call__(self, req):
        request_id = context.generate_request_id()
        signature = req.params.get('Signature')
        if not signature:
            msg = _("Signature not provided")
            return ec2_error(req, request_id, "Unauthorized", msg)
        access = req.params.get('AWSAccessKeyId')
        if not access:
            msg = _("Access key not provided")
            return ec2_error(req, request_id, "Unauthorized", msg)

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

        cred_dict = {
            'access': access,
            'signature': signature,
            'host': req.host,
            'verb': req.method,
            'path': req.path,
            'params': auth_params,
        }
        if "ec2" in FLAGS.keystone_ec2_url:
            creds = {'ec2Credentials': cred_dict}
        else:
            creds = {'auth': {'OS-KSEC2:ec2Credentials': cred_dict}}
        creds_json = utils.dumps(creds)
        headers = {'Content-Type': 'application/json'}

        o = urlparse.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()
        data = response.read()
        if response.status != 200:
            if response.status == 401:
                msg = response.reason
            else:
                msg = _("Failure communicating with keystone")
            return ec2_error(req, request_id, "Unauthorized", msg)
        result = utils.loads(data)
        conn.close()

        try:
            token_id = result['access']['token']['id']
            user_id = result['access']['user']['id']
            project_id = result['access']['token']['tenant']
            roles = [
                role['name'] for role in result['access']['user']['roles']
            ]
        except (AttributeError, KeyError), e:
            LOG.exception("Keystone failure: %s" % e)
            msg = _("Failure communicating with keystone")
            return ec2_error(req, request_id, "Unauthorized", msg)
コード例 #10
0
ファイル: __init__.py プロジェクト: double-z/nova
    def __call__(self, req):
        request_id = context.generate_request_id()
        signature = req.params.get('Signature')
        if not signature:
            msg = _("Signature not provided")
            return ec2_error(req, request_id, "Unauthorized", msg)
        access = req.params.get('AWSAccessKeyId')
        if not access:
            msg = _("Access key not provided")
            return ec2_error(req, request_id, "Unauthorized", msg)

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

        cred_dict = {
            'access': access,
            'signature': signature,
            'host': req.host,
            'verb': req.method,
            'path': req.path,
            'params': auth_params,
        }
        if "ec2" in FLAGS.keystone_ec2_url:
            creds = {'ec2Credentials': cred_dict}
        else:
            creds = {'auth': {'OS-KSEC2:ec2Credentials': cred_dict}}
        creds_json = utils.dumps(creds)
        headers = {'Content-Type': 'application/json'}

        o = urlparse.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()
        data = response.read()
        if response.status != 200:
            if response.status == 401:
                msg = response.reason
            else:
                msg = _("Failure communicating with keystone")
            return ec2_error(req, request_id, "Unauthorized", msg)
        result = utils.loads(data)
        conn.close()

        try:
            token_id = result['access']['token']['id']
            user_id = result['access']['user']['id']
            project_id = result['access']['token']['tenant']['id']
            roles = [role['name'] for role
                     in result['access']['user']['roles']]
        except (AttributeError, KeyError), e:
            LOG.exception("Keystone failure: %s" % e)
            msg = _("Failure communicating with keystone")
            return ec2_error(req, request_id, "Unauthorized", msg)
コード例 #11
0
ファイル: direct.py プロジェクト: lerner/osc-robot-nova
 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['openstack.context'] = context
     resp = req.get_response(self.app)
     try:
         return utils.loads(resp.body)
     except Exception:
         return resp.body
コード例 #12
0
ファイル: direct.py プロジェクト: rackerlabs/reddwarf
 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["openstack.context"] = context
     resp = req.get_response(self.app)
     try:
         return utils.loads(resp.body)
     except Exception:
         return resp.body
コード例 #13
0
    def test_create_server_bad_hints(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"},
            "os:scheduler_hints": "here",
        }

        req.body = utils.dumps(body)
        res = req.get_response(self.app)
        self.assertEqual(400, res.status_int)
コード例 #14
0
class EC2Token(wsgi.Middleware):
    """Authenticate an EC2 request with keystone and convert to token."""
    @webob.dec.wsgify(RequestClass=wsgi.Request)
    def __call__(self, req):
        # Read request signature and access id.
        try:
            signature = req.params['Signature']
            access = req.params['AWSAccessKeyId']
        except KeyError, e:
            LOG.exception(e)
            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.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), e:
            LOG.exception(e)
            raise webob.exc.HTTPBadRequest()
コード例 #15
0
ファイル: ec2_token.py プロジェクト: brandon-miles/keystone
    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.urlparse(FLAGS.keystone_ec2_url)
        if o.scheme == 'http':
            conn = environment.httplib.HTTPConnection(o.netloc)
        else:
            conn = environment.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
コード例 #16
0
ファイル: ec2_token.py プロジェクト: runRanrun/keystone
    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.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
コード例 #17
0
ファイル: load_balancer.py プロジェクト: caiqin/dough
 def send(self, msg_body):
     msg_type = 'lb'
     msg_uuid = str(utils.gen_uuid())
     self.handler.send_multipart([msg_type, msg_uuid,
                                  utils.dumps(msg_body)])
     r_msg_type, r_msg_uuid, r_msg_body = self.handler.recv_multipart()
     assert (all([x == y for x, y in zip([msg_type, msg_uuid],
                                         [r_msg_type, r_msg_uuid])]))
     result = utils.loads(r_msg_body)['msg']
     if result['code'] == 500:
         raise Exception()
     else:
         return result['load_balancer_ids']
コード例 #18
0
ファイル: test_disk_config.py プロジェクト: Razique/nova
 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)
コード例 #19
0
ファイル: test_disk_config.py プロジェクト: BillTheBest/nova
 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)
コード例 #20
0
ファイル: network.py プロジェクト: young8/dough
 def send(self, msg_body):
     msg_type = 'kanyun'
     msg_uuid = str(utils.gen_uuid())
     self.handler.send_multipart([msg_type, msg_uuid,
                                  utils.dumps(msg_body)])
     r_msg_type, r_msg_uuid, r_msg_body = self.handler.recv_multipart()
     assert (all([x == y for x, y in zip([msg_type, msg_uuid],
                                         [r_msg_type, r_msg_uuid])]))
     result = utils.loads(r_msg_body)
     if result['code'] == 500:
         raise Exception()
     else:
         return result['data'] or dict()
コード例 #21
0
    def test_create_server_without_hints(self):
        def fake_create(*args, **kwargs):
            self.assertEqual(kwargs["scheduler_hints"], {})
            return ([self.fake_instance], "")

        self.stubs.Set(nova.compute.api.API, "create", fake_create)

        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"}}

        req.body = utils.dumps(body)
        res = req.get_response(self.app)
        self.assertEqual(202, res.status_int)
コード例 #22
0
ファイル: test_disk_config.py プロジェクト: BillTheBest/nova
    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')
コード例 #23
0
ファイル: test_disk_config.py プロジェクト: Razique/nova
    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')
コード例 #24
0
ファイル: wsgi.py プロジェクト: blamarvt/nova
 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('nova.lazy_serialize', False)
         if lazy_serialize:
             response.body = utils.dumps(data)
             request.environ['nova.serializer'] = serializer
             request.environ['nova.action'] = action
             if (hasattr(serializer, 'get_template') and
                 'nova.template' not in request.environ):
                 template = serializer.get_template(action)
                 request.environ['nova.template'] = template
         else:
             response.body = serializer.serialize(data, action)
コード例 #25
0
ファイル: load_balancer.py プロジェクト: carriercomm/dough
 def send(self, msg_body):
     msg_type = "lb"
     msg_uuid = str(utils.gen_uuid())
     self.handler.send_multipart([msg_type, msg_uuid, utils.dumps(msg_body)])
     r_msg_type, r_msg_uuid, r_msg_body = self.handler.recv_multipart()
     assert all([x == y for x, y in zip([msg_type, msg_uuid], [r_msg_type, r_msg_uuid])])
     # result = utils.loads(r_msg_body)['msg']
     # if result['code'] == 500:
     result = utils.loads(r_msg_body)
     if "msg" in result:  # FIXME: old version support
         result = result["msg"]
     if result["code"] == 500:
         return None
     else:
         # return result['load_balancer_ids']
         return result["data"]
コード例 #26
0
    def test_create_server_bad_hints(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',
            },
            'os:scheduler_hints': 'here',
        }

        req.body = utils.dumps(body)
        res = req.get_response(self.app)
        self.assertEqual(400, res.status_int)
コード例 #27
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('nova.lazy_serialize', False)
            if lazy_serialize:
                response.body = utils.dumps(data)
                request.environ['nova.serializer'] = serializer
                request.environ['nova.action'] = action
                if (hasattr(serializer, 'get_template')
                        and 'nova.template' not in request.environ):

                    template = serializer.get_template(action)
                    request.environ['nova.template'] = template
            else:
                response.body = serializer.serialize(data, action)
コード例 #28
0
    def test_create_server_bad_hints(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',
            },
            'os:scheduler_hints': 'here',
        }

        req.body = utils.dumps(body)
        res = req.get_response(self.app)
        self.assertEqual(400, res.status_int)
コード例 #29
0
ファイル: extensions.py プロジェクト: dragonetail/nova
    def process(self, req, *args, **kwargs):
        res = req.get_response(self.application)

        # 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
コード例 #30
0
ファイル: __init__.py プロジェクト: tomchill/reddwarf
    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'}
        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)
        # TODO(vish): check for errors

        token_id = result['auth']['token']['id']
        # Authenticated!
        req.headers['X-Auth-Token'] = token_id
        return self.application
コード例 #31
0
    def test_create_server_without_hints(self):

        def fake_create(*args, **kwargs):
            self.assertEqual(kwargs['scheduler_hints'], {})
            return ([self.fake_instance], '')

        self.stubs.Set(nova.compute.api.API, 'create', fake_create)

        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',
               }}

        req.body = utils.dumps(body)
        res = req.get_response(self.app)
        self.assertEqual(202, res.status_int)
コード例 #32
0
ファイル: load_balancer.py プロジェクト: young8/dough
 def send(self, msg_body):
     msg_type = 'lb'
     msg_uuid = str(utils.gen_uuid())
     self.handler.send_multipart(
         [msg_type, msg_uuid, utils.dumps(msg_body)])
     r_msg_type, r_msg_uuid, r_msg_body = self.handler.recv_multipart()
     assert (all([
         x == y
         for x, y in zip([msg_type, msg_uuid], [r_msg_type, r_msg_uuid])
     ]))
     #result = utils.loads(r_msg_body)['msg']
     #if result['code'] == 500:
     result = utils.loads(r_msg_body)
     if "msg" in result:  # FIXME: old version support
         result = result["msg"]
     if result['code'] == 500:
         return None
     else:
         #return result['load_balancer_ids']
         return result['data']
コード例 #33
0
    def test_create_server_without_hints(self):
        def fake_create(*args, **kwargs):
            self.assertEqual(kwargs['scheduler_hints'], {})
            return ([self.fake_instance], '')

        self.stubs.Set(nova.compute.api.API, 'create', fake_create)

        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',
            }
        }

        req.body = utils.dumps(body)
        res = req.get_response(self.app)
        self.assertEqual(202, res.status_int)
コード例 #34
0
ファイル: disk_config.py プロジェクト: bingmu/nova
    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)
コード例 #35
0
ファイル: disk_config.py プロジェクト: nicoleLiu/nova
    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)
コード例 #36
0
ファイル: __init__.py プロジェクト: YouthSun/nova
    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.
        client = httplib2.Http()
        creds = {'ec2Credentials': {'access': access,
                                    'signature': signature,
                                    'host': req.host,
                                    'verb': req.method,
                                    'path': req.path,
                                    'params': auth_params,
                                   }}
        headers = {'Content-Type': 'application/json'},
        resp, content = client.request(FLAGS.keystone_ec2_url,
                                       'POST',
                                       headers=headers,
                                       body=utils.dumps(creds))
        # NOTE(vish): We could save a call to keystone by
        #             having keystone return token, tenant,
        #             user, and roles from this call.
        result = utils.loads(content)
        # TODO(vish): check for errors
        token_id = result['auth']['token']['id']

        # Authenticated!
        req.headers['X-Auth-Token'] = token_id
        return self.application
コード例 #37
0
def write_domains(fname, domains):
    json = utils.dumps(domains)
    f = open(fname, 'w')
    f.write(json)
    f.close()
コード例 #38
0
ファイル: __init__.py プロジェクト: double-z/nova
    def __call__(self, req):
        context = req.environ['nova.context']
        request_id = context.request_id
        api_request = req.environ['ec2.request']
        result = None
        try:
            result = api_request.invoke(context)
        except exception.InstanceNotFound as ex:
            LOG.info(_('InstanceNotFound raised: %s'), unicode(ex),
                     context=context)
            ec2_id = ec2utils.id_to_ec2_id(ex.kwargs['instance_id'])
            message = ex.message % {'instance_id': ec2_id}
            return ec2_error(req, request_id, type(ex).__name__, message)
        except exception.VolumeNotFound as ex:
            LOG.info(_('VolumeNotFound raised: %s'), unicode(ex),
                     context=context)
            ec2_id = ec2utils.id_to_ec2_vol_id(ex.kwargs['volume_id'])
            message = ex.message % {'volume_id': ec2_id}
            return ec2_error(req, request_id, type(ex).__name__, message)
        except exception.SnapshotNotFound as ex:
            LOG.info(_('SnapshotNotFound raised: %s'), unicode(ex),
                     context=context)
            ec2_id = ec2utils.id_to_ec2_snap_id(ex.kwargs['snapshot_id'])
            message = ex.message % {'snapshot_id': ec2_id}
            return ec2_error(req, request_id, type(ex).__name__, message)
        except exception.NotFound as ex:
            LOG.info(_('NotFound raised: %s'), unicode(ex), context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.EC2APIError as ex:
            LOG.exception(_('EC2APIError raised: %s'), unicode(ex),
                          context=context)
            if ex.code:
                return ec2_error(req, request_id, ex.code, unicode(ex))
            else:
                return ec2_error(req, request_id, type(ex).__name__,
                                   unicode(ex))
        except exception.KeyPairExists as ex:
            LOG.debug(_('KeyPairExists raised: %s'), unicode(ex),
                     context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.InvalidParameterValue as ex:
            LOG.debug(_('InvalidParameterValue raised: %s'), unicode(ex),
                     context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.InvalidPortRange as ex:
            LOG.debug(_('InvalidPortRange raised: %s'), unicode(ex),
                     context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.NotAuthorized as ex:
            LOG.info(_('NotAuthorized raised: %s'), unicode(ex),
                    context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.InvalidRequest as ex:
            LOG.debug(_('InvalidRequest raised: %s'), unicode(ex),
                     context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.QuotaError as ex:
            LOG.debug(_('QuotaError raised: %s'), unicode(ex),
                      context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.InvalidInstanceIDMalformed as ex:
            LOG.debug(_('ValidatorError raised: %s'), unicode(ex),
                     context=context)
            #EC2 Compatibility
            return self._error(req, context, "InvalidInstanceID.Malformed",
                unicode(ex))
        except Exception as ex:
            env = req.environ.copy()
            for k in env.keys():
                if not isinstance(env[k], basestring):
                    env.pop(k)

            LOG.exception(_('Unexpected error raised: %s'), unicode(ex))
            LOG.error(_('Environment: %s') % utils.dumps(env))
            return ec2_error(req, request_id, 'UnknownError',
                             _('An unknown error has occurred. '
                               'Please try your request again.'))
        else:
            resp = webob.Response()
            resp.status = 200
            resp.headers['Content-Type'] = 'text/xml'
            resp.body = str(result)
            return resp
コード例 #39
0
def write_domains(fname, domains):
    # json = jsonutils.dumps(domains)
    json = utils.dumps(domains)
    f = open(fname, "w")
    f.write(json)
    f.close()
コード例 #40
0
def write_domains(fname, domains):
    json = utils.dumps(domains)
    f = open(fname, 'w')
    f.write(json)
    f.close()
コード例 #41
0
ファイル: wsgi.py プロジェクト: anotherjesse/nova
 def _to_json(self, data):
     return utils.dumps(data)
コード例 #42
0
    def __call__(self, req):
        context = req.environ['nova.context']
        request_id = context.request_id
        api_request = req.environ['ec2.request']
        result = None
        try:
            result = api_request.invoke(context)
        except exception.InstanceNotFound as ex:
            LOG.info(_('InstanceNotFound raised: %s'), unicode(ex),
                     context=context)
            ec2_id = ec2utils.id_to_ec2_id(ex.kwargs['instance_id'])
            message = ex.message % {'instance_id': ec2_id}
            return ec2_error(req, request_id, type(ex).__name__, message)
        except exception.VolumeNotFound as ex:
            LOG.info(_('VolumeNotFound raised: %s'), unicode(ex),
                     context=context)
            ec2_id = ec2utils.id_to_ec2_vol_id(ex.kwargs['volume_id'])
            message = ex.message % {'volume_id': ec2_id}
            return ec2_error(req, request_id, type(ex).__name__, message)
        except exception.SnapshotNotFound as ex:
            LOG.info(_('SnapshotNotFound raised: %s'), unicode(ex),
                     context=context)
            ec2_id = ec2utils.id_to_ec2_snap_id(ex.kwargs['snapshot_id'])
            message = ex.message % {'snapshot_id': ec2_id}
            return ec2_error(req, request_id, type(ex).__name__, message)
        except exception.NotFound as ex:
            LOG.info(_('NotFound raised: %s'), unicode(ex), context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.EC2APIError as ex:
            LOG.exception(_('EC2APIError raised: %s'), unicode(ex),
                          context=context)
            if ex.code:
                return ec2_error(req, request_id, ex.code, unicode(ex))
            else:
                return ec2_error(req, request_id, type(ex).__name__,
                                   unicode(ex))
        except exception.KeyPairExists as ex:
            LOG.debug(_('KeyPairExists raised: %s'), unicode(ex),
                     context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.InvalidParameterValue as ex:
            LOG.debug(_('InvalidParameterValue raised: %s'), unicode(ex),
                     context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.InvalidPortRange as ex:
            LOG.debug(_('InvalidPortRange raised: %s'), unicode(ex),
                     context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.NotAuthorized as ex:
            LOG.info(_('NotAuthorized raised: %s'), unicode(ex),
                    context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.InvalidRequest as ex:
            LOG.debug(_('InvalidRequest raised: %s'), unicode(ex),
                     context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.QuotaError as ex:
            LOG.debug(_('QuotaError raised: %s'), unicode(ex),
                      context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except exception.InvalidInstanceIDMalformed as ex:
            LOG.debug(_('Invalid id: bogus (expecting "i-..."): %s'),
                        unicode(ex), context=context)
            return ec2_error(req, request_id, type(ex).__name__, unicode(ex))
        except Exception as ex:
            env = req.environ.copy()
            for k in env.keys():
                if not isinstance(env[k], basestring):
                    env.pop(k)

            LOG.exception(_('Unexpected error raised: %s'), unicode(ex))
            LOG.error(_('Environment: %s') % utils.dumps(env))
            return ec2_error(req, request_id, 'UnknownError',
                             _('An unknown error has occurred. '
                               'Please try your request again.'))
        else:
            resp = webob.Response()
            resp.status = 200
            resp.headers['Content-Type'] = 'text/xml'
            resp.body = str(result)
            return resp
コード例 #43
0
ファイル: wsgi.py プロジェクト: termie/nova-migration-demo
 def _to_json(self, data):
     return utils.dumps(data)
コード例 #44
0
ファイル: wsgi.py プロジェクト: rcbops/nova-buildpackage
 def default(self, data):
     return utils.dumps(data)
コード例 #45
0
 def default(self, data):
     return utils.dumps(data)