From 7f2cae4d63d1fb9c351d88ad911166f55e89c2f4 Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Thu, 16 Dec 2010 18:01:21 +0000 Subject: fixed up openstack api images index and detail --- nova/api/openstack/images.py | 58 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 46 insertions(+), 12 deletions(-) (limited to 'nova/api') diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index 4a0a8e6f1..3a9bdea64 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -27,6 +27,40 @@ from nova.api.openstack import faults FLAGS = flags.FLAGS +def _entity_list(entities): + """ Coerces a list of images into proper dictionary format + entities is a list of entities (dicts) """ + return dict(images=entities) + +def _entity_detail(inst): + """ Maps everything to Rackspace-like attributes for return + also pares down attributes to those we want + inst is a single entity (dict) """ + status_mapping = { + 'pending': 'queued', + 'decrypting': 'preparing', + 'untarring': 'saving', + 'available': 'active', + new_inst = {} + mapped_keys = {status:'imageState', id:'imageId', name:'imageLocation'} + + for k,v in mapped_keys.iteritems(): + new_inst[k] = inst[v] + + new_inst['status'] = status_mapping[inew_inst['status']] + + return new_inst + +def _entity_inst(inst): + """ Filters all model attributes save for id and name + inst is a single entity (dict) """ + return _filter_keys(inst, ['id','name']) + +def _filter_keys(inst, keys): + """ Filters all model attributes for keys + inst is a single entity (dict) """ + return dict( (k,v) for k,v in inst.iteritems() if k in keys) + class Controller(wsgi.Controller): @@ -40,24 +74,24 @@ class Controller(wsgi.Controller): self._service = utils.import_object(FLAGS.image_service) def index(self, req): - """Return all public images in brief.""" - return dict(images=[dict(id=img['id'], name=img['name']) - for img in self.detail(req)['images']]) + """ Return all public images in brief """ + items = self._service.index(req.environ['nova.context']) + items = nova.api.openstack.limited(items, req) + items = [_entity_inst(item) for item in items] + return dict(images=items) def detail(self, req): - """Return all public images in detail.""" + """ Return all public images in detail """ try: - images = self._service.detail(req.environ['nova.context']) - images = nova.api.openstack.limited(images, req) + items = self._service.detail(req.environ['nova.context']) except NotImplementedError: - # Emulate detail() using repeated calls to show() - images = self._service.index(ctxt) - images = nova.api.openstack.limited(images, req) - images = [self._service.show(ctxt, i['id']) for i in images] - return dict(images=images) + items = self._service.index(req.environ['nova.context']) + items = nova.api.openstack.limited(items, req) + items = [_entity_detail(item) for item in items] + return dict(images=items) def show(self, req, id): - """Return data about the given image id.""" + """ Return data about the given image id """ return dict(image=self._service.show(req.environ['nova.context'], id)) def delete(self, req, id): -- cgit From 7b0c5b3f06328ec9dbb02b2def306d671353354e Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Thu, 16 Dec 2010 18:09:25 +0000 Subject: typo --- nova/api/openstack/images.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'nova/api') diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index 3a9bdea64..78c07abde 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -40,7 +40,7 @@ def _entity_detail(inst): 'pending': 'queued', 'decrypting': 'preparing', 'untarring': 'saving', - 'available': 'active', + 'available': 'active'} new_inst = {} mapped_keys = {status:'imageState', id:'imageId', name:'imageLocation'} -- cgit From e01e6d7976adfd99addf31f4f914c7625a394fda Mon Sep 17 00:00:00 2001 From: Cerberus Date: Thu, 16 Dec 2010 12:09:38 -0600 Subject: Moved implementation specific stuff from the middleware into their respective modules --- nova/api/openstack/__init__.py | 83 ++++------------------------- nova/api/openstack/auth.py | 20 ++++--- nova/api/openstack/common.py | 17 ++++++ nova/api/openstack/flavors.py | 3 +- nova/api/openstack/images.py | 6 ++- nova/api/openstack/ratelimiting/__init__.py | 60 +++++++++++++++++++++ nova/api/openstack/servers.py | 3 +- 7 files changed, 106 insertions(+), 86 deletions(-) create mode 100644 nova/api/openstack/common.py (limited to 'nova/api') diff --git a/nova/api/openstack/__init__.py b/nova/api/openstack/__init__.py index b9ecbd9b8..e941694d9 100644 --- a/nova/api/openstack/__init__.py +++ b/nova/api/openstack/__init__.py @@ -49,6 +49,10 @@ flags.DEFINE_string('nova_api_auth', 'nova.api.openstack.auth.BasicApiAuthManager', 'The auth mechanism to use for the OpenStack API implemenation') +flags.DEFINE_string('os_api_ratelimiting', + 'nova.api.openstack.ratelimiting.BasicRateLimiting', + 'Default ratelimiting implementation for the Openstack API') + flags.DEFINE_bool('allow_admin_api', False, 'When True, this API service will accept admin operations.') @@ -81,10 +85,10 @@ class AuthMiddleware(wsgi.Middleware): @webob.dec.wsgify def __call__(self, req): - if 'X-Auth-Token' not in req.headers: + if not self.auth_driver.has_authentication(req) return self.auth_driver.authenticate(req) - user = self.auth_driver.authorize_token(req.headers["X-Auth-Token"]) + user = self.auth_driver.get_user_by_authentication(req) if not user: return faults.Fault(webob.exc.HTTPUnauthorized()) @@ -104,62 +108,12 @@ class RateLimitingMiddleware(wsgi.Middleware): at the given host+port to keep rate counters. """ super(RateLimitingMiddleware, self).__init__(application) - if not service_host: - #TODO(gundlach): These limits were based on limitations of Cloud - #Servers. We should revisit them in Nova. - self.limiter = ratelimiting.Limiter(limits={ - 'DELETE': (100, ratelimiting.PER_MINUTE), - 'PUT': (10, ratelimiting.PER_MINUTE), - 'POST': (10, ratelimiting.PER_MINUTE), - 'POST servers': (50, ratelimiting.PER_DAY), - 'GET changes-since': (3, ratelimiting.PER_MINUTE), - }) - else: - self.limiter = ratelimiting.WSGIAppProxy(service_host) + self._limiting_driver = + utils.import_class(FLAGS.os_api_ratelimiting)(service_host) @webob.dec.wsgify def __call__(self, req): - """Rate limit the request. - - If the request should be rate limited, return a 413 status with a - Retry-After header giving the time when the request would succeed. - """ - action_name = self.get_action_name(req) - if not action_name: - # Not rate limited - return self.application - delay = self.get_delay(action_name, - req.environ['nova.context'].user_id) - if delay: - # TODO(gundlach): Get the retry-after format correct. - exc = webob.exc.HTTPRequestEntityTooLarge( - explanation='Too many requests.', - headers={'Retry-After': time.time() + delay}) - raise faults.Fault(exc) - return self.application - - def get_delay(self, action_name, username): - """Return the delay for the given action and username, or None if - the action would not be rate limited. - """ - if action_name == 'POST servers': - # "POST servers" is a POST, so it counts against "POST" too. - # Attempt the "POST" first, lest we are rate limited by "POST" but - # use up a precious "POST servers" call. - delay = self.limiter.perform("POST", username=username) - if delay: - return delay - return self.limiter.perform(action_name, username=username) - - def get_action_name(self, req): - """Return the action name for this request.""" - if req.method == 'GET' and 'changes-since' in req.GET: - return 'GET changes-since' - if req.method == 'POST' and req.path_info.startswith('/servers'): - return 'POST servers' - if req.method in ['PUT', 'POST', 'DELETE']: - return req.method - return None + return self._limiting_driver.limited_request(req) class APIRouter(wsgi.Router): @@ -191,22 +145,3 @@ class APIRouter(wsgi.Router): # TODO: Place routes for admin operations here. super(APIRouter, self).__init__(mapper) - - -def limited(items, req): - """Return a slice of items according to requested offset and limit. - - items - a sliceable - req - wobob.Request possibly containing offset and limit GET variables. - offset is where to start in the list, and limit is the maximum number - of items to return. - - If limit is not specified, 0, or > 1000, defaults to 1000. - """ - offset = int(req.GET.get('offset', 0)) - limit = int(req.GET.get('limit', 0)) - if not limit: - limit = 1000 - limit = min(1000, limit) - range_end = offset + limit - return items[offset:range_end] diff --git a/nova/api/openstack/auth.py b/nova/api/openstack/auth.py index fcda97ab1..da8ebcfcd 100644 --- a/nova/api/openstack/auth.py +++ b/nova/api/openstack/auth.py @@ -7,6 +7,7 @@ import webob.exc import webob.dec from nova import auth +from nova import context from nova import db from nova import flags from nova import manager @@ -16,10 +17,6 @@ from nova.api.openstack import faults FLAGS = flags.FLAGS -class Context(object): - pass - - class BasicApiAuthManager(object): """ Implements a somewhat rudimentary version of OpenStack Auth""" @@ -28,9 +25,14 @@ class BasicApiAuthManager(object): db_driver = FLAGS.db_driver self.db = utils.import_object(db_driver) self.auth = auth.manager.AuthManager() - self.context = Context() super(BasicApiAuthManager, self).__init__() + def has_authentication(self, req): + return 'X-Auth-Token' in req.headers: + + def get_user_by_authentication(self, req): + return self.auth_driver.authorize_token(req.headers["X-Auth-Token"]) + def authenticate(self, req): # Unless the request is explicitly made against // don't # honor it @@ -68,11 +70,12 @@ class BasicApiAuthManager(object): This method will also remove the token if the timestamp is older than 2 days ago. """ - token = self.db.auth_get_token(self.context, token_hash) + ctxt = context.get_admin_context() + token = self.db.auth_get_token(ctxt, token_hash) if token: delta = datetime.datetime.now() - token.created_at if delta.days >= 2: - self.db.auth_destroy_token(self.context, token) + self.db.auth_destroy_token(ctxt, token) else: return self.auth.get_user(token.user_id) return None @@ -84,6 +87,7 @@ class BasicApiAuthManager(object): key - string API key req - webob.Request object """ + ctxt = context.get_admin_context() user = self.auth.get_user_from_access_key(key) if user and user.name == username: token_hash = hashlib.sha1('%s%s%f' % (username, key, @@ -95,6 +99,6 @@ class BasicApiAuthManager(object): token_dict['server_management_url'] = req.url token_dict['storage_url'] = '' token_dict['user_id'] = user.id - token = self.db.auth_create_token(self.context, token_dict) + token = self.db.auth_create_token(ctxt, token_dict) return token, user return None, None diff --git a/nova/api/openstack/common.py b/nova/api/openstack/common.py new file mode 100644 index 000000000..29e9a8623 --- /dev/null +++ b/nova/api/openstack/common.py @@ -0,0 +1,17 @@ +def limited(items, req): + """Return a slice of items according to requested offset and limit. + + items - a sliceable + req - wobob.Request possibly containing offset and limit GET variables. + offset is where to start in the list, and limit is the maximum number + of items to return. + + If limit is not specified, 0, or > 1000, defaults to 1000. + """ + offset = int(req.GET.get('offset', 0)) + limit = int(req.GET.get('limit', 0)) + if not limit: + limit = 1000 + limit = min(1000, limit) + range_end = offset + limit + return items[offset:range_end] diff --git a/nova/api/openstack/flavors.py b/nova/api/openstack/flavors.py index f23f74fd1..f620d4107 100644 --- a/nova/api/openstack/flavors.py +++ b/nova/api/openstack/flavors.py @@ -18,6 +18,7 @@ from webob import exc from nova.api.openstack import faults +from nova.api.openstack import common from nova.compute import instance_types from nova import wsgi import nova.api.openstack @@ -39,7 +40,7 @@ class Controller(wsgi.Controller): def detail(self, req): """Return all flavors in detail.""" items = [self.show(req, id)['flavor'] for id in self._all_ids()] - items = nova.api.openstack.limited(items, req) + items = common.limited(items, req) return dict(flavors=items) def show(self, req, id): diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index 4a0a8e6f1..fe8d9d75f 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -22,6 +22,8 @@ from nova import utils from nova import wsgi import nova.api.openstack import nova.image.service + +from nova.api.openstack import common from nova.api.openstack import faults @@ -48,11 +50,11 @@ class Controller(wsgi.Controller): """Return all public images in detail.""" try: images = self._service.detail(req.environ['nova.context']) - images = nova.api.openstack.limited(images, req) + images = common.limited(images, req) except NotImplementedError: # Emulate detail() using repeated calls to show() images = self._service.index(ctxt) - images = nova.api.openstack.limited(images, req) + images = common.limited(images, req) images = [self._service.show(ctxt, i['id']) for i in images] return dict(images=images) diff --git a/nova/api/openstack/ratelimiting/__init__.py b/nova/api/openstack/ratelimiting/__init__.py index 918caf055..d1da9afa7 100644 --- a/nova/api/openstack/ratelimiting/__init__.py +++ b/nova/api/openstack/ratelimiting/__init__.py @@ -14,6 +14,66 @@ PER_HOUR = 60 * 60 PER_DAY = 60 * 60 * 24 +class BasicRateLimiting(object): + """ Implements Rate limits as per the Rackspace CloudServers API spec. """ + + def __init__(self, service_host): + if not service_host: + #TODO(gundlach): These limits were based on limitations of Cloud + #Servers. We should revisit them in Nova. + self.limiter = ratelimiting.Limiter(limits={ + 'DELETE': (100, ratelimiting.PER_MINUTE), + 'PUT': (10, ratelimiting.PER_MINUTE), + 'POST': (10, ratelimiting.PER_MINUTE), + 'POST servers': (50, ratelimiting.PER_DAY), + 'GET changes-since': (3, ratelimiting.PER_MINUTE), + }) + else: + self.limiter = ratelimiting.WSGIAppProxy(service_host) + + def limited_request(self, req): + """Rate limit the request. + + If the request should be rate limited, return a 413 status with a + Retry-After header giving the time when the request would succeed. + """ + action_name = self.get_action_name(req) + if not action_name: + # Not rate limited + return self.application + delay = self.get_delay(action_name, + req.environ['nova.context'].user_id) + if delay: + # TODO(gundlach): Get the retry-after format correct. + exc = webob.exc.HTTPRequestEntityTooLarge( + explanation='Too many requests.', + headers={'Retry-After': time.time() + delay}) + raise faults.Fault(exc) + return self.application + + def get_delay(self, action_name, username): + """Return the delay for the given action and username, or None if + the action would not be rate limited. + """ + if action_name == 'POST servers': + # "POST servers" is a POST, so it counts against "POST" too. + # Attempt the "POST" first, lest we are rate limited by "POST" but + # use up a precious "POST servers" call. + delay = self.limiter.perform("POST", username=username) + if delay: + return delay + return self.limiter.perform(action_name, username=username) + + def get_action_name(self, req): + """Return the action name for this request.""" + if req.method == 'GET' and 'changes-since' in req.GET: + return 'GET changes-since' + if req.method == 'POST' and req.path_info.startswith('/servers'): + return 'POST servers' + if req.method in ['PUT', 'POST', 'DELETE']: + return req.method + return None + class Limiter(object): """Class providing rate limiting of arbitrary actions.""" diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index 7704f48f1..9e6047805 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -19,6 +19,7 @@ from webob import exc from nova import exception from nova import wsgi +from nova.api.openstack import common from nova.api.openstack import faults from nova.auth import manager as auth_manager from nova.compute import api as compute_api @@ -91,7 +92,7 @@ class Controller(wsgi.Controller): """ instance_list = self.compute_api.get_instances( req.environ['nova.context']) - limited_list = nova.api.openstack.limited(instance_list, req) + limited_list = common.limited(instance_list, req) res = [entity_maker(inst)['server'] for inst in limited_list] return _entity_list(res) -- cgit From fc1354a639edb1c3a7f979f58bb90918c63695ab Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Thu, 16 Dec 2010 18:17:53 +0000 Subject: fixed a couple of more syntax errors --- nova/api/openstack/images.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'nova/api') diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index 78c07abde..7f2be5472 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -41,15 +41,15 @@ def _entity_detail(inst): 'decrypting': 'preparing', 'untarring': 'saving', 'available': 'active'} - new_inst = {} - mapped_keys = {status:'imageState', id:'imageId', name:'imageLocation'} + mapped_inst = {} + mapped_keys = {'status':'imageState', 'id':'imageId', 'name':'imageLocation'} for k,v in mapped_keys.iteritems(): - new_inst[k] = inst[v] + mapped_inst[k] = inst[v] - new_inst['status'] = status_mapping[inew_inst['status']] + mapped_inst['status'] = status_mapping[mapped_inst['status']] - return new_inst + return mapped_inst def _entity_inst(inst): """ Filters all model attributes save for id and name -- cgit From 6383f7f9f63e348a12adeff66a266ef796d98ded Mon Sep 17 00:00:00 2001 From: Cerberus Date: Fri, 17 Dec 2010 11:54:59 -0600 Subject: Some typo fixes --- nova/api/openstack/__init__.py | 4 ++-- nova/api/openstack/auth.py | 4 ++-- nova/api/openstack/ratelimiting/__init__.py | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'nova/api') diff --git a/nova/api/openstack/__init__.py b/nova/api/openstack/__init__.py index e941694d9..e78080012 100644 --- a/nova/api/openstack/__init__.py +++ b/nova/api/openstack/__init__.py @@ -85,7 +85,7 @@ class AuthMiddleware(wsgi.Middleware): @webob.dec.wsgify def __call__(self, req): - if not self.auth_driver.has_authentication(req) + if not self.auth_driver.has_authentication(req): return self.auth_driver.authenticate(req) user = self.auth_driver.get_user_by_authentication(req) @@ -108,7 +108,7 @@ class RateLimitingMiddleware(wsgi.Middleware): at the given host+port to keep rate counters. """ super(RateLimitingMiddleware, self).__init__(application) - self._limiting_driver = + self._limiting_driver = \ utils.import_class(FLAGS.os_api_ratelimiting)(service_host) @webob.dec.wsgify diff --git a/nova/api/openstack/auth.py b/nova/api/openstack/auth.py index da8ebcfcd..26cb50dca 100644 --- a/nova/api/openstack/auth.py +++ b/nova/api/openstack/auth.py @@ -28,10 +28,10 @@ class BasicApiAuthManager(object): super(BasicApiAuthManager, self).__init__() def has_authentication(self, req): - return 'X-Auth-Token' in req.headers: + return 'X-Auth-Token' in req.headers def get_user_by_authentication(self, req): - return self.auth_driver.authorize_token(req.headers["X-Auth-Token"]) + return self.authorize_token(req.headers["X-Auth-Token"]) def authenticate(self, req): # Unless the request is explicitly made against // don't diff --git a/nova/api/openstack/ratelimiting/__init__.py b/nova/api/openstack/ratelimiting/__init__.py index d1da9afa7..2dc5ec32e 100644 --- a/nova/api/openstack/ratelimiting/__init__.py +++ b/nova/api/openstack/ratelimiting/__init__.py @@ -21,7 +21,7 @@ class BasicRateLimiting(object): if not service_host: #TODO(gundlach): These limits were based on limitations of Cloud #Servers. We should revisit them in Nova. - self.limiter = ratelimiting.Limiter(limits={ + self.limiter = Limiter(limits={ 'DELETE': (100, ratelimiting.PER_MINUTE), 'PUT': (10, ratelimiting.PER_MINUTE), 'POST': (10, ratelimiting.PER_MINUTE), @@ -29,7 +29,7 @@ class BasicRateLimiting(object): 'GET changes-since': (3, ratelimiting.PER_MINUTE), }) else: - self.limiter = ratelimiting.WSGIAppProxy(service_host) + self.limiter = WSGIAppProxy(service_host) def limited_request(self, req): """Rate limit the request. -- cgit From d71b9a34c3f76f95227da0f7a746cc5a1a76da24 Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Sun, 19 Dec 2010 23:51:17 +0000 Subject: small clean up --- nova/api/openstack/images.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'nova/api') diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index 7f2be5472..df5e1530f 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -41,9 +41,14 @@ def _entity_detail(inst): 'decrypting': 'preparing', 'untarring': 'saving', 'available': 'active'} - mapped_inst = {} - mapped_keys = {'status':'imageState', 'id':'imageId', 'name':'imageLocation'} + # TODO(tr3buchet): this map is specific to s3 object store, + # fix once the local image service is working + mapped_keys = {'status':'imageState', + 'id':'imageId', + 'name':'imageLocation'} + + mapped_inst = {} for k,v in mapped_keys.iteritems(): mapped_inst[k] = inst[v] @@ -54,9 +59,9 @@ def _entity_detail(inst): def _entity_inst(inst): """ Filters all model attributes save for id and name inst is a single entity (dict) """ - return _filter_keys(inst, ['id','name']) + return _select_keys(inst, ['id','name']) -def _filter_keys(inst, keys): +def _select_keys(inst, keys): """ Filters all model attributes for keys inst is a single entity (dict) """ return dict( (k,v) for k,v in inst.iteritems() if k in keys) -- cgit From b5756f6abf582b04a5fe6744d6a139b12440e35a Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Mon, 20 Dec 2010 21:12:20 +0000 Subject: fixed some pep8 business --- nova/api/openstack/images.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) (limited to 'nova/api') diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index df5e1530f..0f808a6bf 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -27,11 +27,13 @@ from nova.api.openstack import faults FLAGS = flags.FLAGS + def _entity_list(entities): """ Coerces a list of images into proper dictionary format entities is a list of entities (dicts) """ return dict(images=entities) + def _entity_detail(inst): """ Maps everything to Rackspace-like attributes for return also pares down attributes to those we want @@ -44,27 +46,29 @@ def _entity_detail(inst): # TODO(tr3buchet): this map is specific to s3 object store, # fix once the local image service is working - mapped_keys = {'status':'imageState', - 'id':'imageId', - 'name':'imageLocation'} + mapped_keys = {'status': 'imageState', + 'id': 'imageId', + 'name': 'imageLocation'} mapped_inst = {} - for k,v in mapped_keys.iteritems(): + for k, v in mapped_keys.iteritems(): mapped_inst[k] = inst[v] mapped_inst['status'] = status_mapping[mapped_inst['status']] return mapped_inst + def _entity_inst(inst): """ Filters all model attributes save for id and name inst is a single entity (dict) """ - return _select_keys(inst, ['id','name']) + return _select_keys(inst, ['id', 'name']) + def _select_keys(inst, keys): """ Filters all model attributes for keys inst is a single entity (dict) """ - return dict( (k,v) for k,v in inst.iteritems() if k in keys) + return dict((k, v) for k, v in inst.iteritems() if k in keys) class Controller(wsgi.Controller): -- cgit From aded4faba96e4de88f0294604927ef824cb249be Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Mon, 20 Dec 2010 22:55:11 +0000 Subject: added suspend and resume --- nova/api/openstack/__init__.py | 2 ++ nova/api/openstack/servers.py | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+) (limited to 'nova/api') diff --git a/nova/api/openstack/__init__.py b/nova/api/openstack/__init__.py index 210df8d24..2553313e4 100644 --- a/nova/api/openstack/__init__.py +++ b/nova/api/openstack/__init__.py @@ -176,6 +176,8 @@ class APIRouter(wsgi.Router): logging.debug("Including admin operations in API.") server_members['pause'] = 'POST' server_members['unpause'] = 'POST' + server_members['suspend'] = 'POST' + server_members['resume'] = 'POST' mapper.resource("server", "servers", controller=servers.Controller(), collection={'detail': 'GET'}, diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index 5c3322f7c..e6700ee96 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -195,3 +195,25 @@ class Controller(wsgi.Controller): logging.error("Compute.api::unpause %s", readable) return faults.Fault(exc.HTTPUnprocessableEntity()) return exc.HTTPAccepted() + + def suspend(self, req, id): + """permit admins to suspend the server""" + context = req.environ['nova.context'] + try: + self.compute_api.suspend(context, id) + except: + readable = traceback.format_exc() + logging.error("compute.api::suspend %s", readable) + return faults.Fault(exc.HTTPUnprocessableEntity()) + return exc.HTTPAccepted() + + def resume(self, req, id): + """permit admins to resume the server from suspend""" + context = req.environ['nova.context'] + try: + self.compute_api.resume(context, id) + except: + readable = traceback.format_exc() + logging.error("compute.api::resume %s", readable) + return faults.Fault(exc.HTTPUnprocessableEntity()) + return exc.HTTPAccepted() -- cgit From 21867297b673ec9fe055fb6c7e4a3dadcfa6fdd2 Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 22 Dec 2010 12:39:59 -0600 Subject: Minor bug fix --- nova/api/__init__.py | 1 + nova/api/openstack/images.py | 1 + 2 files changed, 2 insertions(+) (limited to 'nova/api') diff --git a/nova/api/__init__.py b/nova/api/__init__.py index 80f9f2109..e081ec10b 100644 --- a/nova/api/__init__.py +++ b/nova/api/__init__.py @@ -24,6 +24,7 @@ Root WSGI middleware for all API controllers. :ec2api_subdomain: subdomain running the EC2 API (default: ec2) """ +import logging import routes import webob.dec diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index fe8d9d75f..d3312aba8 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -53,6 +53,7 @@ class Controller(wsgi.Controller): images = common.limited(images, req) except NotImplementedError: # Emulate detail() using repeated calls to show() + ctxt = req.environ['nova.context'] images = self._service.index(ctxt) images = common.limited(images, req) images = [self._service.show(ctxt, i['id']) for i in images] -- cgit From c4fb755b169895f9ffab6ab4d18f5227688b7ae4 Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 22 Dec 2010 13:18:26 -0600 Subject: Abstracted auth and ratelimiting more --- nova/api/openstack/__init__.py | 56 ++++------------------------- nova/api/openstack/auth.py | 22 +++++++++--- nova/api/openstack/ratelimiting/__init__.py | 22 ++++++++++-- 3 files changed, 43 insertions(+), 57 deletions(-) (limited to 'nova/api') diff --git a/nova/api/openstack/__init__.py b/nova/api/openstack/__init__.py index cdc25e2b7..b18edc8e7 100644 --- a/nova/api/openstack/__init__.py +++ b/nova/api/openstack/__init__.py @@ -45,12 +45,12 @@ from nova.auth import manager FLAGS = flags.FLAGS -flags.DEFINE_string('nova_api_auth', - 'nova.api.openstack.auth.BasicApiAuthManager', +flags.DEFINE_string('os_api_auth', + 'nova.api.openstack.auth.AuthMiddleware', 'The auth mechanism to use for the OpenStack API implemenation') flags.DEFINE_string('os_api_ratelimiting', - 'nova.api.openstack.ratelimiting.BasicRateLimiting', + 'nova.api.openstack.ratelimiting.RateLimitingMiddleware', 'Default ratelimiting implementation for the Openstack API') flags.DEFINE_bool('allow_admin_api', @@ -62,7 +62,10 @@ class API(wsgi.Middleware): """WSGI entry point for all OpenStack API requests.""" def __init__(self): - app = AuthMiddleware(RateLimitingMiddleware(APIRouter())) + auth_middleware = utils.import_class(FLAGS.os_api_auth) + ratelimiting_middleware = \ + utils.import_class(FLAGS.os_api_ratelimiting) + app = auth_middleware(ratelimiting_middleware(APIRouter())) super(API, self).__init__(app) @webob.dec.wsgify @@ -76,51 +79,6 @@ class API(wsgi.Middleware): return faults.Fault(exc) -class AuthMiddleware(wsgi.Middleware): - """Authorize the openstack API request or return an HTTP Forbidden.""" - - def __init__(self, application): - self.auth_driver = utils.import_class(FLAGS.nova_api_auth)() - super(AuthMiddleware, self).__init__(application) - - @webob.dec.wsgify - def __call__(self, req): - if not self.auth_driver.has_authentication(req): - return self.auth_driver.authenticate(req) - - user = self.auth_driver.get_user_by_authentication(req) - - if not user: - return faults.Fault(webob.exc.HTTPUnauthorized()) - - req.environ['nova.context'] = context.RequestContext(user, user) - return self.application - - -class RateLimitingMiddleware(wsgi.Middleware): - """Rate limit incoming requests according to the OpenStack rate limits.""" - - def __init__(self, application, service_host=None): - """Create a rate limiting middleware that wraps the given application. - - By default, rate counters are stored in memory. If service_host is - specified, the middleware instead relies on the ratelimiting.WSGIApp - at the given host+port to keep rate counters. - """ - super(RateLimitingMiddleware, self).__init__(application) - self._limiting_driver = \ - utils.import_class(FLAGS.os_api_ratelimiting)(service_host) - - @webob.dec.wsgify - def __call__(self, req): - """Rate limit the request. - - If the request should be rate limited, return a 413 status with a - Retry-After header giving the time when the request would succeed. - """ - return self._limiting_driver.limited_request(req, self.application) - - class APIRouter(wsgi.Router): """ Routes requests on the OpenStack API to the appropriate controller diff --git a/nova/api/openstack/auth.py b/nova/api/openstack/auth.py index 26cb50dca..3850dd1f0 100644 --- a/nova/api/openstack/auth.py +++ b/nova/api/openstack/auth.py @@ -16,16 +16,28 @@ from nova.api.openstack import faults FLAGS = flags.FLAGS +class AuthMiddleware(wsgi.Middleware): + """Authorize the openstack API request or return an HTTP Forbidden.""" -class BasicApiAuthManager(object): - """ Implements a somewhat rudimentary version of OpenStack Auth""" - - def __init__(self, db_driver=None): + def __init__(self, application): if not db_driver: db_driver = FLAGS.db_driver self.db = utils.import_object(db_driver) self.auth = auth.manager.AuthManager() - super(BasicApiAuthManager, self).__init__() + super(AuthMiddleware, self).__init__(application) + + @webob.dec.wsgify + def __call__(self, req): + if not self.has_authentication(req): + return self.authenticate(req) + + user = self.get_user_by_authentication(req) + + if not user: + return faults.Fault(webob.exc.HTTPUnauthorized()) + + req.environ['nova.context'] = context.RequestContext(user, user) + return self.application def has_authentication(self, req): return 'X-Auth-Token' in req.headers diff --git a/nova/api/openstack/ratelimiting/__init__.py b/nova/api/openstack/ratelimiting/__init__.py index 1bf44bc7b..9892e792e 100644 --- a/nova/api/openstack/ratelimiting/__init__.py +++ b/nova/api/openstack/ratelimiting/__init__.py @@ -14,11 +14,16 @@ PER_MINUTE = 60 PER_HOUR = 60 * 60 PER_DAY = 60 * 60 * 24 +class RateLimitingMiddleware(wsgi.Middleware): + """Rate limit incoming requests according to the OpenStack rate limits.""" -class BasicRateLimiting(object): - """ Implements Rate limits as per the Rackspace CloudServers API spec. """ + def __init__(self, application, service_host=None): + """Create a rate limiting middleware that wraps the given application. - def __init__(self, service_host): + By default, rate counters are stored in memory. If service_host is + specified, the middleware instead relies on the ratelimiting.WSGIApp + at the given host+port to keep rate counters. + """ if not service_host: #TODO(gundlach): These limits were based on limitations of Cloud #Servers. We should revisit them in Nova. @@ -31,6 +36,16 @@ class BasicRateLimiting(object): }) else: self.limiter = WSGIAppProxy(service_host) + super(RateLimitingMiddleware, self).__init__(application) + + @webob.dec.wsgify + def __call__(self, req): + """Rate limit the request. + + If the request should be rate limited, return a 413 status with a + Retry-After header giving the time when the request would succeed. + """ + return self.limited_request(req, self.application) def limited_request(self, req, application): """Rate limit the request. @@ -75,6 +90,7 @@ class BasicRateLimiting(object): return req.method return None + class Limiter(object): """Class providing rate limiting of arbitrary actions.""" -- cgit From e419c27a00a85b7daba42f580e332d31713ae271 Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 22 Dec 2010 13:33:26 -0600 Subject: Moved some things for testing --- nova/api/openstack/auth.py | 1 + nova/api/openstack/ratelimiting/__init__.py | 1 + 2 files changed, 2 insertions(+) (limited to 'nova/api') diff --git a/nova/api/openstack/auth.py b/nova/api/openstack/auth.py index 3850dd1f0..6c3c870a1 100644 --- a/nova/api/openstack/auth.py +++ b/nova/api/openstack/auth.py @@ -12,6 +12,7 @@ from nova import db from nova import flags from nova import manager from nova import utils +from nova import wsgi from nova.api.openstack import faults FLAGS = flags.FLAGS diff --git a/nova/api/openstack/ratelimiting/__init__.py b/nova/api/openstack/ratelimiting/__init__.py index 9892e792e..a2e0734ef 100644 --- a/nova/api/openstack/ratelimiting/__init__.py +++ b/nova/api/openstack/ratelimiting/__init__.py @@ -6,6 +6,7 @@ import urllib import webob.dec import webob.exc +from nova import wsgi from nova.api.openstack import faults # Convenience constants for the limits dictionary passed to Limiter(). -- cgit From 168cde072542f9f4df7e7eb26f6b632306c0b7d2 Mon Sep 17 00:00:00 2001 From: mdietz Date: Wed, 22 Dec 2010 19:52:13 +0000 Subject: Finished moving the middleware layers and fixed the API tests again --- nova/api/openstack/auth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'nova/api') diff --git a/nova/api/openstack/auth.py b/nova/api/openstack/auth.py index 6c3c870a1..99cae2c75 100644 --- a/nova/api/openstack/auth.py +++ b/nova/api/openstack/auth.py @@ -20,7 +20,7 @@ FLAGS = flags.FLAGS class AuthMiddleware(wsgi.Middleware): """Authorize the openstack API request or return an HTTP Forbidden.""" - def __init__(self, application): + def __init__(self, application, db_driver=None): if not db_driver: db_driver = FLAGS.db_driver self.db = utils.import_object(db_driver) -- cgit From c2faf1c5e689ac5e81068a305a624e626e9a87b5 Mon Sep 17 00:00:00 2001 From: mdietz Date: Wed, 22 Dec 2010 20:06:22 +0000 Subject: Forgot the copyright info --- nova/api/openstack/auth.py | 18 +++++++++++++++++- nova/api/openstack/ratelimiting/__init__.py | 17 +++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) (limited to 'nova/api') diff --git a/nova/api/openstack/auth.py b/nova/api/openstack/auth.py index 99cae2c75..72ad4ffa9 100644 --- a/nova/api/openstack/auth.py +++ b/nova/api/openstack/auth.py @@ -1,4 +1,20 @@ -import datetime +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2010 OpenStack LLC. +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License.import datetime + import hashlib import json import time diff --git a/nova/api/openstack/ratelimiting/__init__.py b/nova/api/openstack/ratelimiting/__init__.py index a2e0734ef..8ca575b36 100644 --- a/nova/api/openstack/ratelimiting/__init__.py +++ b/nova/api/openstack/ratelimiting/__init__.py @@ -1,3 +1,20 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2010 OpenStack LLC. +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License.import datetime + """Rate limiting of arbitrary actions.""" import httplib -- cgit From 775958e3a020b6b4b4c9fd4777aa72f7e9b0bdbc Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 22 Dec 2010 15:50:26 -0600 Subject: Accidentally yanked the datetime line in auth --- nova/api/openstack/__init__.py | 2 +- nova/api/openstack/auth.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'nova/api') diff --git a/nova/api/openstack/__init__.py b/nova/api/openstack/__init__.py index b18edc8e7..c49399f28 100644 --- a/nova/api/openstack/__init__.py +++ b/nova/api/openstack/__init__.py @@ -74,7 +74,7 @@ class API(wsgi.Middleware): return req.get_response(self.application) except Exception as ex: logging.warn(_("Caught error: %s") % str(ex)) - logging.debug(traceback.format_exc()) + logging.error(traceback.format_exc()) exc = webob.exc.HTTPInternalServerError(explanation=str(ex)) return faults.Fault(exc) diff --git a/nova/api/openstack/auth.py b/nova/api/openstack/auth.py index 72ad4ffa9..c9d21ed49 100644 --- a/nova/api/openstack/auth.py +++ b/nova/api/openstack/auth.py @@ -15,6 +15,7 @@ # License for the specific language governing permissions and limitations # under the License.import datetime +import datetime import hashlib import json import time -- cgit From 12a9dc88f6ae947d005568dd2e644566cd1a9677 Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 22 Dec 2010 21:14:06 -0600 Subject: And the common module --- nova/api/openstack/common.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'nova/api') diff --git a/nova/api/openstack/common.py b/nova/api/openstack/common.py index 29e9a8623..83919cc23 100644 --- a/nova/api/openstack/common.py +++ b/nova/api/openstack/common.py @@ -1,3 +1,20 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2010 OpenStack LLC. +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + def limited(items, req): """Return a slice of items according to requested offset and limit. -- cgit From 62286399b69218418020baaf524292c1677d27d3 Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Thu, 23 Dec 2010 06:48:15 +0000 Subject: added suspend as a power state --- nova/api/openstack/servers.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'nova/api') diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index e6700ee96..9ee52ef2f 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -45,7 +45,8 @@ def _entity_detail(inst): power_state.NOSTATE: 'build', power_state.RUNNING: 'active', power_state.BLOCKED: 'active', - power_state.PAUSED: 'suspended', + power_state.SUSPENDED: 'suspended', + power_state.PAUSED: 'error', power_state.SHUTDOWN: 'active', power_state.SHUTOFF: 'active', power_state.CRASHED: 'error'} -- cgit From ba6a99f926180d47870dcb18e4387d18cddad9b0 Mon Sep 17 00:00:00 2001 From: Cerberus Date: Thu, 23 Dec 2010 11:58:13 -0600 Subject: Superfluous images include and added basic routes for shared ip groups --- nova/api/openstack/sharedipgroups.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) (limited to 'nova/api') diff --git a/nova/api/openstack/sharedipgroups.py b/nova/api/openstack/sharedipgroups.py index e805ca9f7..423ee61e1 100644 --- a/nova/api/openstack/sharedipgroups.py +++ b/nova/api/openstack/sharedipgroups.py @@ -19,4 +19,22 @@ from nova import wsgi class Controller(wsgi.Controller): - pass + """ The Shared IP Groups Controller for the Openstack API """ + + def index(self, req): + raise NotImplementedError + + def show(self, req, id): + raise NotImplementedError + + def update(self, req, id): + raise NotImplementedError + + def delete(self, req, id): + raise NotImplementedError + + def detail(self, req): + raise NotImplementedError + + def create(self, req): + raise NotImplementedError -- cgit From cb679a01e5905e4f7316f81de7c9ead9dc6536b8 Mon Sep 17 00:00:00 2001 From: Cerberus Date: Thu, 23 Dec 2010 13:17:53 -0600 Subject: Pep8 cleanup --- nova/api/openstack/auth.py | 1 + nova/api/openstack/common.py | 2 ++ nova/api/openstack/ratelimiting/__init__.py | 1 + nova/api/openstack/sharedipgroups.py | 2 +- 4 files changed, 5 insertions(+), 1 deletion(-) (limited to 'nova/api') diff --git a/nova/api/openstack/auth.py b/nova/api/openstack/auth.py index c9d21ed49..e24e58fd3 100644 --- a/nova/api/openstack/auth.py +++ b/nova/api/openstack/auth.py @@ -34,6 +34,7 @@ from nova.api.openstack import faults FLAGS = flags.FLAGS + class AuthMiddleware(wsgi.Middleware): """Authorize the openstack API request or return an HTTP Forbidden.""" diff --git a/nova/api/openstack/common.py b/nova/api/openstack/common.py index 83919cc23..ac0572c96 100644 --- a/nova/api/openstack/common.py +++ b/nova/api/openstack/common.py @@ -15,6 +15,7 @@ # License for the specific language governing permissions and limitations # under the License. + def limited(items, req): """Return a slice of items according to requested offset and limit. @@ -25,6 +26,7 @@ def limited(items, req): If limit is not specified, 0, or > 1000, defaults to 1000. """ + offset = int(req.GET.get('offset', 0)) limit = int(req.GET.get('limit', 0)) if not limit: diff --git a/nova/api/openstack/ratelimiting/__init__.py b/nova/api/openstack/ratelimiting/__init__.py index 8ca575b36..91a8b2e55 100644 --- a/nova/api/openstack/ratelimiting/__init__.py +++ b/nova/api/openstack/ratelimiting/__init__.py @@ -32,6 +32,7 @@ PER_MINUTE = 60 PER_HOUR = 60 * 60 PER_DAY = 60 * 60 * 24 + class RateLimitingMiddleware(wsgi.Middleware): """Rate limit incoming requests according to the OpenStack rate limits.""" diff --git a/nova/api/openstack/sharedipgroups.py b/nova/api/openstack/sharedipgroups.py index 423ee61e1..75d02905c 100644 --- a/nova/api/openstack/sharedipgroups.py +++ b/nova/api/openstack/sharedipgroups.py @@ -32,7 +32,7 @@ class Controller(wsgi.Controller): def delete(self, req, id): raise NotImplementedError - + def detail(self, req): raise NotImplementedError -- cgit From a0ca9d4a9550370cc262574fbee097e5b70e408d Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Thu, 23 Dec 2010 20:35:16 +0000 Subject: added _() for gettext and a couple of pep8s --- nova/api/openstack/servers.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'nova/api') diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index 9ee52ef2f..d3e5badea 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -182,7 +182,7 @@ class Controller(wsgi.Controller): self.compute_api.pause(ctxt, id) except: readable = traceback.format_exc() - logging.error("Compute.api::pause %s", readable) + logging.error(_("Compute.api::pause %s"), readable) return faults.Fault(exc.HTTPUnprocessableEntity()) return exc.HTTPAccepted() @@ -193,7 +193,7 @@ class Controller(wsgi.Controller): self.compute_api.unpause(ctxt, id) except: readable = traceback.format_exc() - logging.error("Compute.api::unpause %s", readable) + logging.error(_("Compute.api::unpause %s"), readable) return faults.Fault(exc.HTTPUnprocessableEntity()) return exc.HTTPAccepted() @@ -204,7 +204,7 @@ class Controller(wsgi.Controller): self.compute_api.suspend(context, id) except: readable = traceback.format_exc() - logging.error("compute.api::suspend %s", readable) + logging.error(_("compute.api::suspend %s"), readable) return faults.Fault(exc.HTTPUnprocessableEntity()) return exc.HTTPAccepted() @@ -215,6 +215,6 @@ class Controller(wsgi.Controller): self.compute_api.resume(context, id) except: readable = traceback.format_exc() - logging.error("compute.api::resume %s", readable) + logging.error(_("compute.api::resume %s"), readable) return faults.Fault(exc.HTTPUnprocessableEntity()) return exc.HTTPAccepted() -- cgit From 8e1122997867a16c161954004b5f1722282a97ef Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Thu, 23 Dec 2010 21:45:01 +0000 Subject: fixed error occuring when tests used glance attributes, fixed docstrings --- nova/api/openstack/images.py | 51 +++++++++++++++++++++++++++++++------------- 1 file changed, 36 insertions(+), 15 deletions(-) (limited to 'nova/api') diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index 0f808a6bf..4f16b0ed4 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -29,15 +29,21 @@ FLAGS = flags.FLAGS def _entity_list(entities): - """ Coerces a list of images into proper dictionary format - entities is a list of entities (dicts) """ + """ + Coerces a list of images into proper dictionary format + entities is a list of entities (dicts) + + """ return dict(images=entities) def _entity_detail(inst): - """ Maps everything to Rackspace-like attributes for return - also pares down attributes to those we want - inst is a single entity (dict) """ + """ + Maps everything to Rackspace-like attributes for return + also pares down attributes to those we want + inst is a single entity (dict) + + """ status_mapping = { 'pending': 'queued', 'decrypting': 'preparing', @@ -45,14 +51,23 @@ def _entity_detail(inst): 'available': 'active'} # TODO(tr3buchet): this map is specific to s3 object store, - # fix once the local image service is working + # replace with a list of keys for _select_keys later mapped_keys = {'status': 'imageState', 'id': 'imageId', 'name': 'imageLocation'} mapped_inst = {} - for k, v in mapped_keys.iteritems(): - mapped_inst[k] = inst[v] + # TODO(tr3buchet): + # this chunk of code works with s3 and the local image service/glance + # when we switch to glance/local image service it can be replaced with + # a call to _select_keys, and mapped_keys can be changed to a list + try: + for k, v in mapped_keys.iteritems(): + # map s3 fields + mapped_inst[k] = inst[v] + except KeyError: + mapped_inst = _select_keys(inst, mapped_keys.keys()) + mapped_inst['status'] = status_mapping[mapped_inst['status']] @@ -60,14 +75,20 @@ def _entity_detail(inst): def _entity_inst(inst): - """ Filters all model attributes save for id and name - inst is a single entity (dict) """ + """ + Filters all model attributes save for id and name + inst is a single entity (dict) + + """ return _select_keys(inst, ['id', 'name']) def _select_keys(inst, keys): - """ Filters all model attributes for keys - inst is a single entity (dict) """ + """ + Filters all model attributes except for keys + inst is a single entity (dict) + + """ return dict((k, v) for k, v in inst.iteritems() if k in keys) @@ -83,14 +104,14 @@ class Controller(wsgi.Controller): self._service = utils.import_object(FLAGS.image_service) def index(self, req): - """ Return all public images in brief """ + """Return all public images in brief""" items = self._service.index(req.environ['nova.context']) items = nova.api.openstack.limited(items, req) items = [_entity_inst(item) for item in items] return dict(images=items) def detail(self, req): - """ Return all public images in detail """ + """Return all public images in detail""" try: items = self._service.detail(req.environ['nova.context']) except NotImplementedError: @@ -100,7 +121,7 @@ class Controller(wsgi.Controller): return dict(images=items) def show(self, req, id): - """ Return data about the given image id """ + """Return data about the given image id""" return dict(image=self._service.show(req.environ['nova.context'], id)) def delete(self, req, id): -- cgit From 1c26d2b2ce824dbc64525eea699efbfa8bf04617 Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Thu, 23 Dec 2010 21:48:14 +0000 Subject: updated since dietz moved the limited function --- nova/api/openstack/images.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'nova/api') diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index 4f16b0ed4..132afc5fc 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -106,7 +106,7 @@ class Controller(wsgi.Controller): def index(self, req): """Return all public images in brief""" items = self._service.index(req.environ['nova.context']) - items = nova.api.openstack.limited(items, req) + items = common.limited(images, req) items = [_entity_inst(item) for item in items] return dict(images=items) @@ -116,7 +116,7 @@ class Controller(wsgi.Controller): items = self._service.detail(req.environ['nova.context']) except NotImplementedError: items = self._service.index(req.environ['nova.context']) - items = nova.api.openstack.limited(items, req) + items = common.limited(images, req) items = [_entity_detail(item) for item in items] return dict(images=items) -- cgit From 6df8d6827d48572ba4cc7cf13fd69286f0dcafe1 Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Thu, 23 Dec 2010 22:00:44 +0000 Subject: fixed typo --- nova/api/openstack/images.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'nova/api') diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index 515fd4423..787e23acc 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -108,7 +108,7 @@ class Controller(wsgi.Controller): def index(self, req): """Return all public images in brief""" items = self._service.index(req.environ['nova.context']) - items = common.limited(images, req) + items = common.limited(items, req) items = [_entity_inst(item) for item in items] return dict(images=items) @@ -118,7 +118,7 @@ class Controller(wsgi.Controller): items = self._service.detail(req.environ['nova.context']) except NotImplementedError: items = self._service.index(req.environ['nova.context']) - items = common.limited(images, req) + items = common.limited(items, req) items = [_entity_detail(item) for item in items] return dict(images=items) -- cgit From 4b271b9e25ac2573cbb82f4b89434d608a91a8c7 Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Mon, 27 Dec 2010 16:41:41 +0000 Subject: couple of pep8s --- nova/api/openstack/images.py | 1 - 1 file changed, 1 deletion(-) (limited to 'nova/api') diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index 787e23acc..e848a2e3e 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -70,7 +70,6 @@ def _entity_detail(inst): except KeyError: mapped_inst = _select_keys(inst, mapped_keys.keys()) - mapped_inst['status'] = status_mapping[mapped_inst['status']] return mapped_inst -- cgit From d2ec717f7f819503f977c7a6f35e96867cc6c512 Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Mon, 27 Dec 2010 20:06:45 +0000 Subject: renaming things to be a bit more descriptive --- nova/api/openstack/images.py | 60 +++++++++++++++++++++----------------------- 1 file changed, 29 insertions(+), 31 deletions(-) (limited to 'nova/api') diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index e848a2e3e..ea22b07ba 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -30,30 +30,18 @@ from nova.api.openstack import faults FLAGS = flags.FLAGS -def _entity_list(entities): +def _translate_keys(inst): """ - Coerces a list of images into proper dictionary format - entities is a list of entities (dicts) - - """ - return dict(images=entities) - - -def _entity_detail(inst): - """ - Maps everything to Rackspace-like attributes for return + Maps key names to Rackspace-like attributes for return also pares down attributes to those we want - inst is a single entity (dict) + inst is a single item (dict) - """ - status_mapping = { - 'pending': 'queued', - 'decrypting': 'preparing', - 'untarring': 'saving', - 'available': 'active'} + Note: should be removed when the set of keys expected by the api + and the set of keys returned by the image service are equivalent + """ # TODO(tr3buchet): this map is specific to s3 object store, - # replace with a list of keys for _select_keys later + # replace with a list of keys for _filter_keys later mapped_keys = {'status': 'imageState', 'id': 'imageId', 'name': 'imageLocation'} @@ -62,32 +50,41 @@ def _entity_detail(inst): # TODO(tr3buchet): # this chunk of code works with s3 and the local image service/glance # when we switch to glance/local image service it can be replaced with - # a call to _select_keys, and mapped_keys can be changed to a list + # a call to _filter_keys, and mapped_keys can be changed to a list try: for k, v in mapped_keys.iteritems(): # map s3 fields mapped_inst[k] = inst[v] except KeyError: - mapped_inst = _select_keys(inst, mapped_keys.keys()) - - mapped_inst['status'] = status_mapping[mapped_inst['status']] + # return only the fields api expects + mapped_inst = _filter_keys(inst, mapped_keys.keys()) return mapped_inst -def _entity_inst(inst): +def _translate_status(inst): """ - Filters all model attributes save for id and name - inst is a single entity (dict) + Translates status of image to match current Rackspace api bindings + inst is a single item (dict) + + Note: should be removed when the set of statuses expected by the api + and the set of statuses returned by the image service are equivalent """ - return _select_keys(inst, ['id', 'name']) + mapped_inst = {} + status_mapping = { + 'pending': 'queued', + 'decrypting': 'preparing', + 'untarring': 'saving', + 'available': 'active'} + mapped_inst['status'] = status_mapping[mapped_inst['status']] + return mapped_inst -def _select_keys(inst, keys): +def _filter_keys(inst, keys): """ Filters all model attributes except for keys - inst is a single entity (dict) + inst is a single item (dict) """ return dict((k, v) for k, v in inst.iteritems() if k in keys) @@ -108,7 +105,7 @@ class Controller(wsgi.Controller): """Return all public images in brief""" items = self._service.index(req.environ['nova.context']) items = common.limited(items, req) - items = [_entity_inst(item) for item in items] + items = [_filter_keys(item, ('id', 'name')) for item in items] return dict(images=items) def detail(self, req): @@ -118,7 +115,8 @@ class Controller(wsgi.Controller): except NotImplementedError: items = self._service.index(req.environ['nova.context']) items = common.limited(items, req) - items = [_entity_detail(item) for item in items] + items = [_translate_keys(item) for item in items] + items = [_translate_status(item) for item in items] return dict(images=items) def show(self, req, id): -- cgit From 0c983d1f3cba82f992fc128985f4f794fb76190f Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Mon, 27 Dec 2010 20:11:36 +0000 Subject: syntax error --- nova/api/openstack/images.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'nova/api') diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index ea22b07ba..8a16bcb0f 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -77,7 +77,7 @@ def _translate_status(inst): 'decrypting': 'preparing', 'untarring': 'saving', 'available': 'active'} - mapped_inst['status'] = status_mapping[mapped_inst['status']] + mapped_inst['status'] = status_mapping[inst['status']] return mapped_inst -- cgit From e86f765181a9d0a75486a98e827cc8505b7c4111 Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Mon, 27 Dec 2010 20:17:53 +0000 Subject: inst -> item --- nova/api/openstack/images.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) (limited to 'nova/api') diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index 8a16bcb0f..77625bab5 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -30,11 +30,11 @@ from nova.api.openstack import faults FLAGS = flags.FLAGS -def _translate_keys(inst): +def _translate_keys(item): """ Maps key names to Rackspace-like attributes for return also pares down attributes to those we want - inst is a single item (dict) + item is a dict Note: should be removed when the set of keys expected by the api and the set of keys returned by the image service are equivalent @@ -46,7 +46,7 @@ def _translate_keys(inst): 'id': 'imageId', 'name': 'imageLocation'} - mapped_inst = {} + mapped_item = {} # TODO(tr3buchet): # this chunk of code works with s3 and the local image service/glance # when we switch to glance/local image service it can be replaced with @@ -54,40 +54,40 @@ def _translate_keys(inst): try: for k, v in mapped_keys.iteritems(): # map s3 fields - mapped_inst[k] = inst[v] + mapped_item[k] = item[v] except KeyError: # return only the fields api expects - mapped_inst = _filter_keys(inst, mapped_keys.keys()) + mapped_item = _filter_keys(item, mapped_keys.keys()) - return mapped_inst + return mapped_item -def _translate_status(inst): +def _translate_status(item): """ Translates status of image to match current Rackspace api bindings - inst is a single item (dict) + item is a dict Note: should be removed when the set of statuses expected by the api and the set of statuses returned by the image service are equivalent """ - mapped_inst = {} + mapped_item = {} status_mapping = { 'pending': 'queued', 'decrypting': 'preparing', 'untarring': 'saving', 'available': 'active'} - mapped_inst['status'] = status_mapping[inst['status']] - return mapped_inst + mapped_item['status'] = status_mapping[item['status']] + return mapped_item -def _filter_keys(inst, keys): +def _filter_keys(item, keys): """ Filters all model attributes except for keys - inst is a single item (dict) + item is a dict """ - return dict((k, v) for k, v in inst.iteritems() if k in keys) + return dict((k, v) for k, v in item.iteritems() if k in keys) class Controller(wsgi.Controller): -- cgit From 243ba12a903b2eac30dd99305a92f76e430cfb49 Mon Sep 17 00:00:00 2001 From: Trey Morris Date: Mon, 27 Dec 2010 20:39:48 +0000 Subject: translate status was returning the wrong item --- nova/api/openstack/images.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'nova/api') diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index 77625bab5..ba35fbc78 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -71,14 +71,13 @@ def _translate_status(item): and the set of statuses returned by the image service are equivalent """ - mapped_item = {} status_mapping = { 'pending': 'queued', 'decrypting': 'preparing', 'untarring': 'saving', 'available': 'active'} - mapped_item['status'] = status_mapping[item['status']] - return mapped_item + item['status'] = status_mapping[item['status']] + return item def _filter_keys(item, keys): -- cgit