From e76fe31644ab616dbde14e1b2063ab8419410404 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Sun, 12 Sep 2010 16:02:22 -0700 Subject: Periodic callback for services and managers. Added code to automatically disassociate stale ip addresses --- nova/db/api.py | 5 +++++ nova/db/sqlalchemy/api.py | 14 ++++++++++++++ nova/manager.py | 6 ++++++ nova/network/manager.py | 37 +++++++++++++++++++++++++------------ nova/service.py | 24 ++++++++++++++++++++---- nova/tests/service_unittest.py | 9 +++++++-- 6 files changed, 77 insertions(+), 18 deletions(-) diff --git a/nova/db/api.py b/nova/db/api.py index 1529888ba..43f50555f 100644 --- a/nova/db/api.py +++ b/nova/db/api.py @@ -170,6 +170,11 @@ def fixed_ip_disassociate(context, address): return IMPL.fixed_ip_disassociate(context, address) +def fixed_ip_disassociate_all_by_timeout(context, host, time): + """Disassociate old fixed ips from host""" + return IMPL.fixed_ip_disassociate_all_by_timeout(context, host, time) + + def fixed_ip_get_by_address(context, address): """Get a fixed ip by address or raise if it does not exist.""" return IMPL.fixed_ip_get_by_address(context, address) diff --git a/nova/db/sqlalchemy/api.py b/nova/db/sqlalchemy/api.py index 3d3b766fc..fa2981899 100644 --- a/nova/db/sqlalchemy/api.py +++ b/nova/db/sqlalchemy/api.py @@ -244,6 +244,20 @@ def fixed_ip_disassociate(_context, address): fixed_ip_ref.save(session=session) +def fixed_ip_disassociate_all_by_timeout(_context, host, time): + session = get_session() + result = session.execute('update fixed_ips set instance_id = NULL ' + 'WHERE id IN (SELECT fixed_ips.id FROM fixed_ips ' + 'INNER JOIN networks ' + 'ON fixed_ips.network_id = ' + 'networks.id ' + 'WHERE host = :host) ' + 'AND updated_at < :time ' + 'AND instance_id IS NOT NULL', + {'host': host, + 'time': time.isoformat()}) + return result.rowcount + def fixed_ip_get_by_address(_context, address): session = get_session() with session.begin(): diff --git a/nova/manager.py b/nova/manager.py index e9aa50c56..0694907bd 100644 --- a/nova/manager.py +++ b/nova/manager.py @@ -22,6 +22,7 @@ Base class for managers of different parts of the system from nova import utils from nova import flags +from twisted.internet import defer FLAGS = flags.FLAGS flags.DEFINE_string('db_driver', 'nova.db.api', @@ -37,3 +38,8 @@ class Manager(object): if not db_driver: db_driver = FLAGS.db_driver self.db = utils.import_object(db_driver) # pylint: disable-msg=C0103 + + @defer.inlineCallbacks + def periodic_tasks(self, context=None): + """Tasks to be run at a periodic interval""" + yield diff --git a/nova/network/manager.py b/nova/network/manager.py index 9564a3e33..b3541aacc 100644 --- a/nova/network/manager.py +++ b/nova/network/manager.py @@ -20,10 +20,12 @@ Network Hosts are responsible for allocating ips and setting up network """ +import datetime import logging import math import IPy +from twisted.internet import defer from nova import db from nova import exception @@ -62,7 +64,9 @@ flags.DEFINE_integer('cnt_vpn_clients', 5, flags.DEFINE_string('network_driver', 'nova.network.linux_net', 'Driver to use for network creation') flags.DEFINE_bool('update_dhcp_on_disassociate', False, - 'Whether to update dhcp when fixed_ip is disassocated') + 'Whether to update dhcp when fixed_ip is disassociated') +flags.DEFINE_integer('fixed_ip_disassociate_timeout', 600, + 'Seconds after which a deallocated ip is disassociated') class AddressAlreadyAllocated(exception.Error): @@ -90,7 +94,7 @@ class NetworkManager(manager.Manager): network_id = network_ref['id'] host = self.db.network_set_host(context, network_id, - FLAGS.host) + self.host) self._on_set_network_host(context, network_id) return host @@ -118,7 +122,7 @@ class NetworkManager(manager.Manager): """Gets an floating ip from the pool""" # TODO(vish): add floating ips through manage command return self.db.floating_ip_allocate_address(context, - FLAGS.host, + self.host, project_id) def associate_floating_ip(self, context, floating_address, fixed_address): @@ -218,6 +222,21 @@ class FlatManager(NetworkManager): class VlanManager(NetworkManager): """Vlan network with dhcp""" + + @defer.inlineCallbacks + def periodic_tasks(self, context=None): + """Tasks to be run at a periodic interval""" + yield super(VlanManager, self).periodic_tasks(context) + now = datetime.datetime.utcnow() + timeout = FLAGS.fixed_ip_disassociate_timeout + time = now - datetime.timedelta(seconds=timeout) + num = self.db.fixed_ip_disassociate_all_by_timeout(self, + self.host, + time) + if num: + logging.debug("Dissassociated %s stale fixed ip(s)", num) + + def allocate_fixed_ip(self, context, instance_id, *args, **kwargs): """Gets a fixed ip from the pool""" network_ref = self.db.project_get_network(context, context.project.id) @@ -235,14 +254,6 @@ class VlanManager(NetworkManager): """Returns a fixed ip to the pool""" self.db.fixed_ip_update(context, address, {'allocated': False}) fixed_ip_ref = self.db.fixed_ip_get_by_address(context, address) - if not fixed_ip_ref['leased']: - self.db.fixed_ip_disassociate(context, address) - # NOTE(vish): dhcp server isn't updated until next setup, this - # means there will stale entries in the conf file - # the code below will update the file if necessary - if FLAGS.update_dhcp_on_disassociate: - network_ref = self.db.fixed_ip_get_network(context, address) - self.driver.update_dhcp(context, network_ref['id']) def setup_fixed_ip(self, context, address): @@ -287,7 +298,9 @@ class VlanManager(NetworkManager): if instance_ref['mac_address'] != mac: raise exception.Error("IP %s released from bad mac %s vs %s" % (address, instance_ref['mac_address'], mac)) - self.db.fixed_ip_update(context, address, {'leased': False}) + self.db.fixed_ip_update(context, + fixed_ip_ref['str_id'], + {'leased': False}) if not fixed_ip_ref['allocated']: self.db.fixed_ip_disassociate(context, address) # NOTE(vish): dhcp server isn't updated until next setup, this diff --git a/nova/service.py b/nova/service.py index 870dd6ceb..df450025b 100644 --- a/nova/service.py +++ b/nova/service.py @@ -37,7 +37,11 @@ from nova import utils FLAGS = flags.FLAGS flags.DEFINE_integer('report_interval', 10, - 'seconds between nodes reporting state to cloud', + 'seconds between nodes reporting state to datastore', + lower_bound=1) + +flags.DEFINE_integer('periodic_interval', 60, + 'seconds between running periodic tasks', lower_bound=1) @@ -80,7 +84,8 @@ class Service(object, service.Service): binary=None, topic=None, manager=None, - report_interval=None): + report_interval=None, + periodic_interval=None): """Instantiates class and passes back application object. Args: @@ -89,6 +94,7 @@ class Service(object, service.Service): topic, defaults to bin_name - "nova-" part manager, defaults to FLAGS._manager report_interval, defaults to FLAGS.report_interval + periodic_interval, defaults to FLAGS.periodic_interval """ if not host: host = FLAGS.host @@ -100,6 +106,8 @@ class Service(object, service.Service): manager = FLAGS.get('%s_manager' % topic, None) if not report_interval: report_interval = FLAGS.report_interval + if not periodic_interval: + periodic_interval = FLAGS.periodic_interval logging.warn("Starting %s node", topic) service_obj = cls(host, binary, topic, manager) conn = rpc.Connection.instance() @@ -112,11 +120,14 @@ class Service(object, service.Service): topic='%s.%s' % (topic, host), proxy=service_obj) + consumer_all.attach_to_twisted() + consumer_node.attach_to_twisted() + pulse = task.LoopingCall(service_obj.report_state) pulse.start(interval=report_interval, now=False) - consumer_all.attach_to_twisted() - consumer_node.attach_to_twisted() + pulse = task.LoopingCall(service_obj.periodic_tasks) + pulse.start(interval=periodic_interval, now=False) # This is the parent service that twistd will be looking for when it # parses this file, return it so that we can get it into globals. @@ -131,6 +142,11 @@ class Service(object, service.Service): except exception.NotFound: logging.warn("Service killed that has no database entry") + @defer.inlineCallbacks + def periodic_tasks(self, context=None): + """Tasks to be run at a periodic interval""" + yield self.manager.periodic_tasks(context) + @defer.inlineCallbacks def report_state(self, context=None): """Update the state of this service in the datastore.""" diff --git a/nova/tests/service_unittest.py b/nova/tests/service_unittest.py index 01da0eb8a..06f80e82c 100644 --- a/nova/tests/service_unittest.py +++ b/nova/tests/service_unittest.py @@ -65,15 +65,20 @@ class ServiceTestCase(test.BaseTestCase): proxy=mox.IsA(service.Service)).AndReturn( rpc.AdapterConsumer) + rpc.AdapterConsumer.attach_to_twisted() + rpc.AdapterConsumer.attach_to_twisted() + # Stub out looping call a bit needlessly since we don't have an easy # way to cancel it (yet) when the tests finishes service.task.LoopingCall(mox.IgnoreArg()).AndReturn( service.task.LoopingCall) service.task.LoopingCall.start(interval=mox.IgnoreArg(), now=mox.IgnoreArg()) + service.task.LoopingCall(mox.IgnoreArg()).AndReturn( + service.task.LoopingCall) + service.task.LoopingCall.start(interval=mox.IgnoreArg(), + now=mox.IgnoreArg()) - rpc.AdapterConsumer.attach_to_twisted() - rpc.AdapterConsumer.attach_to_twisted() service_create = {'host': host, 'binary': binary, 'topic': topic, -- cgit From efeb5243ffd5e588748d8786ac82a04e302f0612 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Sun, 12 Sep 2010 17:24:06 -0700 Subject: workaround for mysql select in update --- nova/db/sqlalchemy/api.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/nova/db/sqlalchemy/api.py b/nova/db/sqlalchemy/api.py index fa2981899..aa8670253 100644 --- a/nova/db/sqlalchemy/api.py +++ b/nova/db/sqlalchemy/api.py @@ -246,12 +246,19 @@ def fixed_ip_disassociate(_context, address): def fixed_ip_disassociate_all_by_timeout(_context, host, time): session = get_session() - result = session.execute('update fixed_ips set instance_id = NULL ' - 'WHERE id IN (SELECT fixed_ips.id FROM fixed_ips ' - 'INNER JOIN networks ' - 'ON fixed_ips.network_id = ' - 'networks.id ' - 'WHERE host = :host) ' + # NOTE(vish): The annoying nested select here is because SQLite doesn't + # support JOINs in UPDATEs and Mysql doesn't support SELECT + # from the same table you are updating without using a temp + # table. It would be great if we can coax sqlalchemy into + # generating this update for us without having to update + # each fixed_ip individually. + result = session.execute('UPDATE fixed_ips SET instance_id = NULL ' + 'WHERE id IN (SELECT x.id FROM ' + '(SELECT fixed_ips.id FROM fixed_ips ' + 'INNER JOIN networks ' + 'ON fixed_ips.network_id = ' + 'networks.id ' + 'WHERE host = :host) as x) ' 'AND updated_at < :time ' 'AND instance_id IS NOT NULL', {'host': host, -- cgit From cb2a28d82210e43a221a8fa8f2a03a7dbd6e8779 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Sun, 12 Sep 2010 17:56:28 -0700 Subject: speed up the query and make sure allocated is false --- nova/db/sqlalchemy/api.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/nova/db/sqlalchemy/api.py b/nova/db/sqlalchemy/api.py index aa8670253..ca5e12f95 100644 --- a/nova/db/sqlalchemy/api.py +++ b/nova/db/sqlalchemy/api.py @@ -258,9 +258,10 @@ def fixed_ip_disassociate_all_by_timeout(_context, host, time): 'INNER JOIN networks ' 'ON fixed_ips.network_id = ' 'networks.id ' - 'WHERE host = :host) as x) ' - 'AND updated_at < :time ' - 'AND instance_id IS NOT NULL', + 'WHERE networks.host = :host ' + 'AND fixed_ip.updated_at < :time ' + 'AND fixed_ip.instance_id IS NOT NULL' + 'AND fixed_ip.allocated = 0) as x) ', {'host': host, 'time': time.isoformat()}) return result.rowcount -- cgit From 3f9118b2ae025cd707642b179fe58459dd39dbc3 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Sun, 12 Sep 2010 18:06:59 -0700 Subject: set leased = 0 as well on disassociate update --- nova/db/sqlalchemy/api.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/nova/db/sqlalchemy/api.py b/nova/db/sqlalchemy/api.py index ca5e12f95..b4b68fa02 100644 --- a/nova/db/sqlalchemy/api.py +++ b/nova/db/sqlalchemy/api.py @@ -252,16 +252,17 @@ def fixed_ip_disassociate_all_by_timeout(_context, host, time): # table. It would be great if we can coax sqlalchemy into # generating this update for us without having to update # each fixed_ip individually. - result = session.execute('UPDATE fixed_ips SET instance_id = NULL ' + result = session.execute('UPDATE fixed_ips SET instance_id = NULL, ' + 'leased = 0 ' 'WHERE id IN (SELECT x.id FROM ' - '(SELECT fixed_ips.id FROM fixed_ips ' - 'INNER JOIN networks ' - 'ON fixed_ips.network_id = ' - 'networks.id ' - 'WHERE networks.host = :host ' - 'AND fixed_ip.updated_at < :time ' - 'AND fixed_ip.instance_id IS NOT NULL' - 'AND fixed_ip.allocated = 0) as x) ', + '(SELECT fixed_ips.id FROM fixed_ips ' + 'INNER JOIN networks ' + 'ON fixed_ips.network_id = ' + 'networks.id ' + 'WHERE networks.host = :host ' + 'AND fixed_ip.updated_at < :time ' + 'AND fixed_ip.instance_id IS NOT NULL' + 'AND fixed_ip.allocated = 0) as x) ', {'host': host, 'time': time.isoformat()}) return result.rowcount -- cgit From 8e5a2ab3614da2676a3627cf62fedfedf7f3585c Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Sun, 12 Sep 2010 18:16:52 -0700 Subject: missed a space --- nova/db/sqlalchemy/api.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/db/sqlalchemy/api.py b/nova/db/sqlalchemy/api.py index b4b68fa02..5ec477666 100644 --- a/nova/db/sqlalchemy/api.py +++ b/nova/db/sqlalchemy/api.py @@ -261,7 +261,7 @@ def fixed_ip_disassociate_all_by_timeout(_context, host, time): 'networks.id ' 'WHERE networks.host = :host ' 'AND fixed_ip.updated_at < :time ' - 'AND fixed_ip.instance_id IS NOT NULL' + 'AND fixed_ip.instance_id IS NOT NULL ' 'AND fixed_ip.allocated = 0) as x) ', {'host': host, 'time': time.isoformat()}) -- cgit From dbb3358f851c245ccb5ea9a9c7ace636b4e73a80 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Sun, 12 Sep 2010 18:25:15 -0700 Subject: simplified query --- nova/db/sqlalchemy/api.py | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/nova/db/sqlalchemy/api.py b/nova/db/sqlalchemy/api.py index 5ec477666..18a43cad4 100644 --- a/nova/db/sqlalchemy/api.py +++ b/nova/db/sqlalchemy/api.py @@ -246,23 +246,15 @@ def fixed_ip_disassociate(_context, address): def fixed_ip_disassociate_all_by_timeout(_context, host, time): session = get_session() - # NOTE(vish): The annoying nested select here is because SQLite doesn't - # support JOINs in UPDATEs and Mysql doesn't support SELECT - # from the same table you are updating without using a temp - # table. It would be great if we can coax sqlalchemy into - # generating this update for us without having to update - # each fixed_ip individually. + # NOTE(vish): The nested select is because sqlite doesn't support + # JOINs in UPDATEs. result = session.execute('UPDATE fixed_ips SET instance_id = NULL, ' 'leased = 0 ' - 'WHERE id IN (SELECT x.id FROM ' - '(SELECT fixed_ips.id FROM fixed_ips ' - 'INNER JOIN networks ' - 'ON fixed_ips.network_id = ' - 'networks.id ' - 'WHERE networks.host = :host ' - 'AND fixed_ip.updated_at < :time ' - 'AND fixed_ip.instance_id IS NOT NULL ' - 'AND fixed_ip.allocated = 0) as x) ', + 'WHERE network_id IN (SELECT id FROM networks ' + 'WHERE host = :host) ' + 'AND updated_at < :time ' + 'AND instance_id IS NOT NULL ' + 'AND allocated = 0', {'host': host, 'time': time.isoformat()}) return result.rowcount -- cgit From 892e55724e8265865a1b298e478d98acd42c68d7 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Sun, 12 Sep 2010 22:12:24 -0700 Subject: move the warnings about leasing ips --- nova/network/manager.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/nova/network/manager.py b/nova/network/manager.py index b3541aacc..b4c4a53b4 100644 --- a/nova/network/manager.py +++ b/nova/network/manager.py @@ -270,9 +270,6 @@ class VlanManager(NetworkManager): """Called by dhcp-bridge when ip is leased""" logging.debug("Leasing IP %s", address) fixed_ip_ref = self.db.fixed_ip_get_by_address(context, address) - if not fixed_ip_ref['allocated']: - logging.warn("IP %s leased that was already deallocated", address) - return instance_ref = fixed_ip_ref['instance'] if not instance_ref: raise exception.Error("IP %s leased that isn't associated" % @@ -283,14 +280,13 @@ class VlanManager(NetworkManager): self.db.fixed_ip_update(context, fixed_ip_ref['str_id'], {'leased': True}) + if not fixed_ip_ref['allocated']: + logging.warn("IP %s leased that was already deallocated", address) def release_fixed_ip(self, context, mac, address): """Called by dhcp-bridge when ip is released""" logging.debug("Releasing IP %s", address) fixed_ip_ref = self.db.fixed_ip_get_by_address(context, address) - if not fixed_ip_ref['leased']: - logging.warn("IP %s released that was not leased", address) - return instance_ref = fixed_ip_ref['instance'] if not instance_ref: raise exception.Error("IP %s released that isn't associated" % @@ -298,6 +294,8 @@ class VlanManager(NetworkManager): if instance_ref['mac_address'] != mac: raise exception.Error("IP %s released from bad mac %s vs %s" % (address, instance_ref['mac_address'], mac)) + if not fixed_ip_ref['leased']: + logging.warn("IP %s released that was not leased", address) self.db.fixed_ip_update(context, fixed_ip_ref['str_id'], {'leased': False}) -- cgit From f3698b8da4bd63abfade32c9894ac2095672344e Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Tue, 21 Sep 2010 15:44:49 -0700 Subject: cleaned up exception handling for fixed_ip_get --- nova/db/sqlalchemy/api.py | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/nova/db/sqlalchemy/api.py b/nova/db/sqlalchemy/api.py index 026cdf10d..daa9e991e 100644 --- a/nova/db/sqlalchemy/api.py +++ b/nova/db/sqlalchemy/api.py @@ -19,15 +19,13 @@ Implementation of SQLAlchemy backend """ -import sys - from nova import db from nova import exception from nova import flags from nova.db.sqlalchemy import models from nova.db.sqlalchemy.session import get_session from sqlalchemy import or_ -from sqlalchemy.orm import exc, joinedload_all +from sqlalchemy.orm import joinedload_all from sqlalchemy.sql import func FLAGS = flags.FLAGS @@ -352,17 +350,14 @@ def fixed_ip_disassociate_all_by_timeout(_context, host, time): def fixed_ip_get_by_address(_context, address): session = get_session() - with session.begin(): - try: - return session.query(models.FixedIp - ).options(joinedload_all('instance') - ).filter_by(address=address - ).filter_by(deleted=False - ).one() - except exc.NoResultFound: - new_exc = exception.NotFound("No model for address %s" % address) - raise new_exc.__class__, new_exc, sys.exc_info()[2] - + result = session.query(models.FixedIp + ).options(joinedload_all('instance') + ).filter_by(address=address + ).filter_by(deleted=False + ).first() + if not result: + raise exception.NotFound("No model for address %s" % address) + return result def fixed_ip_get_instance(_context, address): session = get_session() -- cgit From 05e3e188e03624884ed019fe9cd8f216c9262f98 Mon Sep 17 00:00:00 2001 From: Michael Gundlach Date: Tue, 28 Sep 2010 20:36:50 -0400 Subject: Fault support --- nova/api/rackspace/__init__.py | 9 +++-- nova/api/rackspace/auth.py | 7 ++-- nova/api/rackspace/faults.py | 61 ++++++++++++++++++++++++++++++++++ nova/api/rackspace/flavors.py | 3 +- nova/api/rackspace/images.py | 7 ++-- nova/tests/api/rackspace/testfaults.py | 30 +++++++++++++++++ 6 files changed, 107 insertions(+), 10 deletions(-) create mode 100644 nova/api/rackspace/faults.py create mode 100644 nova/tests/api/rackspace/testfaults.py diff --git a/nova/api/rackspace/__init__.py b/nova/api/rackspace/__init__.py index c24d08585..447037020 100644 --- a/nova/api/rackspace/__init__.py +++ b/nova/api/rackspace/__init__.py @@ -31,6 +31,7 @@ import webob from nova import flags from nova import utils from nova import wsgi +from nova.api.rackspace import faults from nova.api.rackspace import flavors from nova.api.rackspace import images from nova.api.rackspace import ratelimiting @@ -66,7 +67,7 @@ class AuthMiddleware(wsgi.Middleware): user = self.auth_driver.authorize_token(req.headers["X-Auth-Token"]) if not user: - return webob.exc.HTTPUnauthorized() + return faults.Fault(webob.exc.HTTPUnauthorized()) context = {'user': user} req.environ['nova.context'] = context return self.application @@ -109,8 +110,10 @@ class RateLimitingMiddleware(wsgi.Middleware): delay = self.get_delay(action_name, username) if delay: # TODO(gundlach): Get the retry-after format correct. - raise webob.exc.HTTPRequestEntityTooLarge(headers={ - 'Retry-After': time.time() + delay}) + 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): diff --git a/nova/api/rackspace/auth.py b/nova/api/rackspace/auth.py index ce5a967eb..519263367 100644 --- a/nova/api/rackspace/auth.py +++ b/nova/api/rackspace/auth.py @@ -9,6 +9,7 @@ from nova import auth from nova import manager from nova import db from nova import utils +from nova.api.rackspace import faults FLAGS = flags.FLAGS @@ -34,13 +35,13 @@ class BasicApiAuthManager(object): # honor it path_info = req.path_info if len(path_info) > 1: - return webob.exc.HTTPUnauthorized() + return faults.Fault(webob.exc.HTTPUnauthorized()) try: username, key = req.headers['X-Auth-User'], \ req.headers['X-Auth-Key'] except KeyError: - return webob.exc.HTTPUnauthorized() + return faults.Fault(webob.exc.HTTPUnauthorized()) username, key = req.headers['X-Auth-User'], req.headers['X-Auth-Key'] token, user = self._authorize_user(username, key) @@ -55,7 +56,7 @@ class BasicApiAuthManager(object): res.status = '204' return res else: - return webob.exc.HTTPUnauthorized() + return faults.Fault(webob.exc.HTTPUnauthorized()) def authorize_token(self, token_hash): """ retrieves user information from the datastore given a token diff --git a/nova/api/rackspace/faults.py b/nova/api/rackspace/faults.py new file mode 100644 index 000000000..fd6bc3623 --- /dev/null +++ b/nova/api/rackspace/faults.py @@ -0,0 +1,61 @@ +# 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 webob.dec + +from nova import wsgi + + +class Fault(wsgi.Application): + + """An RS API fault response.""" + + _fault_names = { + 400: "badRequest", + 401: "unauthorized", + 403: "resizeNotAllowed", + 404: "itemNotFound", + 405: "badMethod", + 409: "inProgress", + 413: "overLimit", + 415: "badMediaType", + 501: "notImplemented", + 503: "serviceUnavailable"} + + def __init__(self, exception): + """Create a Fault for the given webob.exc.exception.""" + self.exception = exception + + @webob.dec.wsgify + def __call__(self, req): + """Generate a WSGI response based on self.exception.""" + # Replace the body with fault details. + code = self.exception.status_int + fault_name = self._fault_names.get(code, "cloudServersFault") + fault_data = { + fault_name: { + 'code': code, + 'message': self.exception.explanation}} + if code == 413: + retry = self.exception.headers['Retry-After'] + fault_data[fault_name]['retryAfter'] = retry + # 'code' is an attribute on the fault tag itself + metadata = {'application/xml': {'attributes': {fault_name: 'code'}}} + serializer = wsgi.Serializer(req.environ, metadata) + self.exception.body = serializer.to_content_type(fault_data) + return self.exception diff --git a/nova/api/rackspace/flavors.py b/nova/api/rackspace/flavors.py index 60b35c939..6cc57be33 100644 --- a/nova/api/rackspace/flavors.py +++ b/nova/api/rackspace/flavors.py @@ -16,6 +16,7 @@ # under the License. from nova.api.rackspace import base +from nova.api.rackspace import faults from nova.compute import instance_types from webob import exc @@ -47,7 +48,7 @@ class Controller(base.Controller): item = dict(ram=val['memory_mb'], disk=val['local_gb'], id=val['flavorid'], name=name) return dict(flavor=item) - raise exc.HTTPNotFound() + raise faults.Fault(exc.HTTPNotFound()) def _all_ids(self): """Return the list of all flavorids.""" diff --git a/nova/api/rackspace/images.py b/nova/api/rackspace/images.py index 2f3e928b9..1c50d0bec 100644 --- a/nova/api/rackspace/images.py +++ b/nova/api/rackspace/images.py @@ -18,6 +18,7 @@ import nova.image.service from nova.api.rackspace import base from nova.api.rackspace import _id_translator +from nova.api.rackspace import faults from webob import exc class Controller(base.Controller): @@ -57,14 +58,14 @@ class Controller(base.Controller): def delete(self, req, id): # Only public images are supported for now. - raise exc.HTTPNotFound() + raise faults.Fault(exc.HTTPNotFound()) def create(self, req): # Only public images are supported for now, so a request to # make a backup of a server cannot be supproted. - raise exc.HTTPNotFound() + raise faults.Fault(exc.HTTPNotFound()) def update(self, req, id): # Users may not modify public images, and that's all that # we support for now. - raise exc.HTTPNotFound() + raise faults.Fault(exc.HTTPNotFound()) diff --git a/nova/tests/api/rackspace/testfaults.py b/nova/tests/api/rackspace/testfaults.py new file mode 100644 index 000000000..74caffd30 --- /dev/null +++ b/nova/tests/api/rackspace/testfaults.py @@ -0,0 +1,30 @@ +import unittest +import webob +import webob.exc + +from nova.api.rackspace import faults + +class TestFaults(unittest.TestCase): + + def test_fault_parts(self): + req = webob.Request.blank('/.xml') + f = faults.Fault(webob.exc.HTTPBadRequest(explanation='scram')) + resp = req.get_response(f) + + first_two_words = resp.body.strip().split()[:2] + self.assertEqual(first_two_words, ['']) + body_without_spaces = ''.join(resp.body.split()) + self.assertTrue('scram' in body_without_spaces) + + def test_retry_header(self): + req = webob.Request.blank('/.xml') + exc = webob.exc.HTTPRequestEntityTooLarge(explanation='sorry', + headers={'Retry-After': 4}) + f = faults.Fault(exc) + resp = req.get_response(f) + first_two_words = resp.body.strip().split()[:2] + self.assertEqual(first_two_words, ['']) + body_sans_spaces = ''.join(resp.body.split()) + self.assertTrue('sorry' in body_sans_spaces) + self.assertTrue('4' in body_sans_spaces) + self.assertEqual(resp.headers['Retry-After'], 4) -- cgit From 4c1aa3d96f0c44d3e01864ca3128e9b052d1d7fd Mon Sep 17 00:00:00 2001 From: Michael Gundlach Date: Wed, 29 Sep 2010 10:17:10 -0400 Subject: After update from trunk, a few more exceptions that need to be converted to Faults --- nova/api/rackspace/backup_schedules.py | 7 ++++--- nova/api/rackspace/servers.py | 17 +++++++++-------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/nova/api/rackspace/backup_schedules.py b/nova/api/rackspace/backup_schedules.py index 46da778ee..cb83023bc 100644 --- a/nova/api/rackspace/backup_schedules.py +++ b/nova/api/rackspace/backup_schedules.py @@ -20,6 +20,7 @@ from webob import exc from nova import wsgi from nova.api.rackspace import _id_translator +from nova.api.rackspace import faults import nova.image.service class Controller(wsgi.Controller): @@ -27,12 +28,12 @@ class Controller(wsgi.Controller): pass def index(self, req, server_id): - return exc.HTTPNotFound() + return faults.Fault(exc.HTTPNotFound()) def create(self, req, server_id): """ No actual update method required, since the existing API allows both create and update through a POST """ - return exc.HTTPNotFound() + return faults.Fault(exc.HTTPNotFound()) def delete(self, req, server_id): - return exc.HTTPNotFound() + return faults.Fault(exc.HTTPNotFound()) diff --git a/nova/api/rackspace/servers.py b/nova/api/rackspace/servers.py index 4ab04bde7..888d67542 100644 --- a/nova/api/rackspace/servers.py +++ b/nova/api/rackspace/servers.py @@ -24,6 +24,7 @@ from nova import rpc from nova import utils from nova import wsgi from nova.api.rackspace import _id_translator +from nova.api.rackspace import faults from nova.compute import power_state import nova.image.service @@ -120,7 +121,7 @@ class Controller(wsgi.Controller): if inst: if inst.user_id == user_id: return _entity_detail(inst) - raise exc.HTTPNotFound() + raise faults.Fault(exc.HTTPNotFound()) def delete(self, req, id): """ Destroys a server """ @@ -128,13 +129,13 @@ class Controller(wsgi.Controller): instance = self.db_driver.instance_get(None, id) if instance and instance['user_id'] == user_id: self.db_driver.instance_destroy(None, id) - return exc.HTTPAccepted() - return exc.HTTPNotFound() + return faults.Fault(exc.HTTPAccepted()) + return faults.Fault(exc.HTTPNotFound()) def create(self, req): """ Creates a new server for a given user """ if not req.environ.has_key('inst_dict'): - return exc.HTTPUnprocessableEntity() + return faults.Fault(exc.HTTPUnprocessableEntity()) inst = self._build_server_instance(req) @@ -147,22 +148,22 @@ class Controller(wsgi.Controller): def update(self, req, id): """ Updates the server name or password """ if not req.environ.has_key('inst_dict'): - return exc.HTTPUnprocessableEntity() + return faults.Fault(exc.HTTPUnprocessableEntity()) instance = self.db_driver.instance_get(None, id) if not instance: - return exc.HTTPNotFound() + return faults.Fault(exc.HTTPNotFound()) attrs = req.environ['nova.context'].get('model_attributes', None) if attrs: self.db_driver.instance_update(None, id, _filter_params(attrs)) - return exc.HTTPNoContent() + return faults.Fault(exc.HTTPNoContent()) def action(self, req, id): """ multi-purpose method used to reboot, rebuild, and resize a server """ if not req.environ.has_key('inst_dict'): - return exc.HTTPUnprocessableEntity() + return faults.Fault(exc.HTTPUnprocessableEntity()) def _build_server_instance(self, req): """Build instance data structure and save it to the data store.""" -- cgit From 29eca7e7992fc5c073d70f7c8ca5e5bc03f62af7 Mon Sep 17 00:00:00 2001 From: Michael Gundlach Date: Wed, 29 Sep 2010 11:37:26 -0400 Subject: Limit entity lists by &offset and &limit --- nova/api/rackspace/__init__.py | 20 ++++++++++++++++++++ nova/api/rackspace/flavors.py | 5 ++++- nova/api/rackspace/images.py | 2 ++ nova/api/rackspace/servers.py | 18 ++++++++++++------ nova/tests/api/rackspace/__init__.py | 29 +++++++++++++++++++++++++++++ 5 files changed, 67 insertions(+), 7 deletions(-) diff --git a/nova/api/rackspace/__init__.py b/nova/api/rackspace/__init__.py index 98802663f..48104f6df 100644 --- a/nova/api/rackspace/__init__.py +++ b/nova/api/rackspace/__init__.py @@ -165,3 +165,23 @@ class APIRouter(wsgi.Router): controller=sharedipgroups.Controller()) 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/rackspace/flavors.py b/nova/api/rackspace/flavors.py index 3bcf170e5..ba7aa937c 100644 --- a/nova/api/rackspace/flavors.py +++ b/nova/api/rackspace/flavors.py @@ -15,9 +15,11 @@ # License for the specific language governing permissions and limitations # under the License. +from webob import exc + from nova.compute import instance_types from nova import wsgi -from webob import exc +import nova.api.rackspace class Controller(wsgi.Controller): """Flavor controller for the Rackspace API.""" @@ -38,6 +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.rackspace.limited(items, req) return dict(flavors=items) def show(self, req, id): diff --git a/nova/api/rackspace/images.py b/nova/api/rackspace/images.py index 11b058dec..7da17e6a7 100644 --- a/nova/api/rackspace/images.py +++ b/nova/api/rackspace/images.py @@ -19,6 +19,7 @@ from webob import exc from nova import wsgi from nova.api.rackspace import _id_translator +import nova.api.rackspace import nova.image.service class Controller(wsgi.Controller): @@ -45,6 +46,7 @@ class Controller(wsgi.Controller): def detail(self, req): """Return all public images in detail.""" data = self._service.index() + data = nova.api.rackspace.limited(data, req) for img in data: img['id'] = self._id_translator.to_rs_id(img['id']) return dict(images=data) diff --git a/nova/api/rackspace/servers.py b/nova/api/rackspace/servers.py index 4ab04bde7..958fc86a3 100644 --- a/nova/api/rackspace/servers.py +++ b/nova/api/rackspace/servers.py @@ -25,6 +25,7 @@ from nova import utils from nova import wsgi from nova.api.rackspace import _id_translator from nova.compute import power_state +import nova.api.rackspace import nova.image.service FLAGS = flags.FLAGS @@ -101,16 +102,21 @@ class Controller(wsgi.Controller): def index(self, req): """ Returns a list of server names and ids for a given user """ - user_id = req.environ['nova.context']['user']['id'] - instance_list = self.db_driver.instance_get_all_by_user(None, user_id) - res = [_entity_inst(inst)['server'] for inst in instance_list] - return _entity_list(res) + return self._items(req, entity_maker=_entity_inst) def detail(self, req): """ Returns a list of server details for a given user """ + return self._items(req, entity_maker=_entity_detail) + + def _items(self, req, entity_maker): + """Returns a list of servers for a given user. + + entity_maker - either _entity_detail or _entity_inst + """ user_id = req.environ['nova.context']['user']['id'] - res = [_entity_detail(inst)['server'] for inst in - self.db_driver.instance_get_all_by_user(None, user_id)] + instance_list = self.db_driver.instance_get_all_by_user(None, user_id) + limited_list = nova.api.rackspace.limited(instance_list, req) + res = [entity_maker(inst)['server'] for inst in limited_list] return _entity_list(res) def show(self, req, id): diff --git a/nova/tests/api/rackspace/__init__.py b/nova/tests/api/rackspace/__init__.py index 622cb4335..bfd0f87a7 100644 --- a/nova/tests/api/rackspace/__init__.py +++ b/nova/tests/api/rackspace/__init__.py @@ -17,6 +17,7 @@ import unittest +from nova.api.rackspace import limited from nova.api.rackspace import RateLimitingMiddleware from nova.tests.api.test_helper import * from webob import Request @@ -77,3 +78,31 @@ class RateLimitingMiddlewareTest(unittest.TestCase): self.assertEqual(middleware.limiter.__class__.__name__, "Limiter") middleware = RateLimitingMiddleware(APIStub(), service_host='foobar') self.assertEqual(middleware.limiter.__class__.__name__, "WSGIAppProxy") + + +class LimiterTest(unittest.TestCase): + + def testLimiter(self): + items = range(2000) + req = Request.blank('/') + self.assertEqual(limited(items, req), items[ :1000]) + req = Request.blank('/?offset=0') + self.assertEqual(limited(items, req), items[ :1000]) + req = Request.blank('/?offset=3') + self.assertEqual(limited(items, req), items[3:1003]) + req = Request.blank('/?offset=2005') + self.assertEqual(limited(items, req), []) + req = Request.blank('/?limit=10') + self.assertEqual(limited(items, req), items[ :10]) + req = Request.blank('/?limit=0') + self.assertEqual(limited(items, req), items[ :1000]) + req = Request.blank('/?limit=3000') + self.assertEqual(limited(items, req), items[ :1000]) + req = Request.blank('/?offset=1&limit=3') + self.assertEqual(limited(items, req), items[1:4]) + req = Request.blank('/?offset=3&limit=0') + self.assertEqual(limited(items, req), items[3:1003]) + req = Request.blank('/?offset=3&limit=1500') + self.assertEqual(limited(items, req), items[3:1003]) + req = Request.blank('/?offset=3000&limit=10') + self.assertEqual(limited(items, req), []) -- cgit From 0868bcee453665b1ce24d43a90b3addfaab8c49d Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 29 Sep 2010 12:16:53 -0500 Subject: Server update name and password --- nova/api/rackspace/servers.py | 61 +++++++++++++++++++++++-------------- nova/db/sqlalchemy/models.py | 3 ++ nova/tests/api/rackspace/servers.py | 36 +++++++++++++++++++--- nova/wsgi.py | 9 ++++++ 4 files changed, 82 insertions(+), 27 deletions(-) diff --git a/nova/api/rackspace/servers.py b/nova/api/rackspace/servers.py index 4ab04bde7..c156309bd 100644 --- a/nova/api/rackspace/servers.py +++ b/nova/api/rackspace/servers.py @@ -15,6 +15,7 @@ # License for the specific language governing permissions and limitations # under the License. +import datetime import time from webob import exc @@ -25,11 +26,13 @@ from nova import utils from nova import wsgi from nova.api.rackspace import _id_translator from nova.compute import power_state +from nova.wsgi import Serializer import nova.image.service FLAGS = flags.FLAGS - +flags.DEFINE_string('rs_network_manager', 'nova.network.manager.FlatManager', + 'Networking for rackspace') def translator_instance(): """ Helper method for initializing the image id translator """ @@ -82,7 +85,6 @@ def _entity_inst(inst): class Controller(wsgi.Controller): """ The Server API controller for the Openstack API """ - _serialization_metadata = { 'application/xml': { @@ -146,16 +148,19 @@ class Controller(wsgi.Controller): def update(self, req, id): """ Updates the server name or password """ - if not req.environ.has_key('inst_dict'): + user_id = req.environ['nova.context']['user']['id'] + + inst_dict = self._deserialize(req.body, req) + + if not inst_dict: return exc.HTTPUnprocessableEntity() instance = self.db_driver.instance_get(None, id) - if not instance: + if not instance or instance.user_id != user_id: return exc.HTTPNotFound() - attrs = req.environ['nova.context'].get('model_attributes', None) - if attrs: - self.db_driver.instance_update(None, id, _filter_params(attrs)) + self.db_driver.instance_update(None, id, + _filter_params(inst_dict['server'])) return exc.HTTPNoContent() def action(self, req, id): @@ -170,34 +175,44 @@ class Controller(wsgi.Controller): inst = {} env = req.environ['inst_dict'] + user_id = req.environ['nova.context']['user']['id'] + inst['rs_id'] = _new_rs_id(user_id) image_id = env['server']['imageId'] + opaque_id = translator_instance().from_rs_id(image_id) - inst['name'] = env['server']['server_name'] + inst['name'] = env['server']['name'] inst['image_id'] = opaque_id inst['instance_type'] = env['server']['flavorId'] - - user_id = req.environ['nova.context']['user']['id'] inst['user_id'] = user_id - inst['launch_time'] = ltime inst['mac_address'] = utils.generate_mac() - inst['project_id'] = env['project']['id'] - inst['reservation_id'] = reservation - reservation = utils.generate_uid('r') + #TODO(dietz) These are the attributes I'm unsure of + inst['state_description'] = 'scheduling' + inst['kernel_id'] = '' + inst['ramdisk_id'] = '' + inst['reservation_id'] = utils.generate_uid('r') + inst['key_data'] = '' + inst['key_name'] = '' + inst['security_group'] = '' + + # Flavor related attributes + inst['instance_type'] = '' + inst['memory_mb'] = '' + inst['vcpus'] = '' + inst['local_gb'] = '' - address = self.network.allocate_ip( - inst['user_id'], - inst['project_id'], - mac=inst['mac_address']) + + + #TODO(dietz): This seems necessary. How do these apply across + #the Rackspace implementation? + inst['project_id'] = '' - inst['private_dns_name'] = str(address) - inst['bridge_name'] = network.BridgedNetwork.get_network_for_project( - inst['user_id'], - inst['project_id'], - 'default')['bridge_name'] + self.network_manager = utils.import_object(FLAGS.rs_network_manager) + + address = self.network_manager.allocate_fixed_ip( None, inst['id']) ref = self.db_driver.instance_create(None, inst) inst['id'] = ref.id diff --git a/nova/db/sqlalchemy/models.py b/nova/db/sqlalchemy/models.py index 3d2460c39..83fc7c852 100644 --- a/nova/db/sqlalchemy/models.py +++ b/nova/db/sqlalchemy/models.py @@ -199,6 +199,9 @@ class Instance(BASE, NovaBase): id = Column(Integer, primary_key=True) ec2_id = Column(String(10), unique=True) + rs_id = Column(String(255)) + rs_root_password = Column(String(255)) + user_id = Column(String(255)) project_id = Column(String(255)) diff --git a/nova/tests/api/rackspace/servers.py b/nova/tests/api/rackspace/servers.py index 9fd8e5e88..81682288c 100644 --- a/nova/tests/api/rackspace/servers.py +++ b/nova/tests/api/rackspace/servers.py @@ -95,11 +95,39 @@ class ServersTest(unittest.TestCase): # res = req.get_response(nova.api.API()) # print res - def test_update_server_password(self): - pass - def test_update_server_name(self): - pass + def test_update_bad_params(self): + """ Confirm that update is filtering params """ + inst_dict = dict(cat='leopard', name='server_test', adminPass='bacon') + self.body = json.dumps(dict(server=inst_dict)) + + def server_update(context, id, params): + self.update_called = True + filtered_dict = dict(name='server_test', adminPass='bacon') + self.assertEqual(params, filtered_dict) + + self.stubs.Set(nova.db.api, 'instance_update', + server_update) + + req = webob.Request.blank('/v1.0/servers/1') + req.method = 'PUT' + req.body = self.body + req.get_response(nova.api.API()) + + def test_update_server(self): + inst_dict = dict(name='server_test', adminPass='bacon') + self.body = json.dumps(dict(server=inst_dict)) + + def server_update(context, id, params): + self.assertEqual(params, json.loads(self.body)['server']) + + self.stubs.Set(nova.db.api, 'instance_update', + server_update) + + req = webob.Request.blank('/v1.0/servers/1') + req.method = 'PUT' + req.body = self.body + req.get_response(nova.api.API()) def test_create_backup_schedules(self): req = webob.Request.blank('/v1.0/servers/1/backup_schedules') diff --git a/nova/wsgi.py b/nova/wsgi.py index da9374542..48c4dabc2 100644 --- a/nova/wsgi.py +++ b/nova/wsgi.py @@ -230,6 +230,15 @@ class Controller(object): serializer = Serializer(request.environ, _metadata) return serializer.to_content_type(data) + def _deserialize(self, data, request): + """ + Deserialize the request body to the response type requested in request. + Uses self._serialization_metadata if it exists, which is a dict mapping + MIME types to information needed to serialize to that type. + """ + _metadata = getattr(type(self), "_serialization_metadata", {}) + serializer = Serializer(request.environ, _metadata) + return serializer.deserialize(data) class Serializer(object): """ -- cgit From 9c4319a83a6e7d61ffa6b78e9f17ea35821c5526 Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 29 Sep 2010 12:58:40 -0500 Subject: Make update work correctly --- nova/api/rackspace/servers.py | 20 ++++++++++++++------ nova/db/sqlalchemy/models.py | 2 +- nova/tests/api/rackspace/servers.py | 5 +++-- 3 files changed, 18 insertions(+), 9 deletions(-) diff --git a/nova/api/rackspace/servers.py b/nova/api/rackspace/servers.py index c156309bd..aa955c222 100644 --- a/nova/api/rackspace/servers.py +++ b/nova/api/rackspace/servers.py @@ -34,7 +34,12 @@ FLAGS = flags.FLAGS flags.DEFINE_string('rs_network_manager', 'nova.network.manager.FlatManager', 'Networking for rackspace') -def translator_instance(): +def _instance_id_translator(): + """ Helper method for initializing an id translator for Rackspace instance + ids """ + return _id_translator.RackspaceAPIIdTranslator( "instance", 'nova') + +def _image_id_translator(): """ Helper method for initializing the image id translator """ service = nova.image.service.ImageService.load() return _id_translator.RackspaceAPIIdTranslator( @@ -42,11 +47,11 @@ def translator_instance(): def _filter_params(inst_dict): """ Extracts all updatable parameters for a server update request """ - keys = ['name', 'adminPass'] + keys = dict(name='name', admin_pass='adminPass') new_attrs = {} - for k in keys: - if inst_dict.has_key(k): - new_attrs[k] = inst_dict[k] + for k, v in keys.items(): + if inst_dict.has_key(v): + new_attrs[k] = inst_dict[v] return new_attrs def _entity_list(entities): @@ -174,10 +179,13 @@ class Controller(wsgi.Controller): ltime = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) inst = {} + inst_id_trans = _instance_id_translator() + image_id_trans = _image_id_translator() + env = req.environ['inst_dict'] user_id = req.environ['nova.context']['user']['id'] - inst['rs_id'] = _new_rs_id(user_id) + inst['rs_id'] = inst_id_trans.to_rs_id() image_id = env['server']['imageId'] opaque_id = translator_instance().from_rs_id(image_id) diff --git a/nova/db/sqlalchemy/models.py b/nova/db/sqlalchemy/models.py index 83fc7c852..2a314b037 100644 --- a/nova/db/sqlalchemy/models.py +++ b/nova/db/sqlalchemy/models.py @@ -200,7 +200,7 @@ class Instance(BASE, NovaBase): ec2_id = Column(String(10), unique=True) rs_id = Column(String(255)) - rs_root_password = Column(String(255)) + admin_pass = Column(String(255)) user_id = Column(String(255)) project_id = Column(String(255)) diff --git a/nova/tests/api/rackspace/servers.py b/nova/tests/api/rackspace/servers.py index 81682288c..e08c9c6fd 100644 --- a/nova/tests/api/rackspace/servers.py +++ b/nova/tests/api/rackspace/servers.py @@ -103,7 +103,7 @@ class ServersTest(unittest.TestCase): def server_update(context, id, params): self.update_called = True - filtered_dict = dict(name='server_test', adminPass='bacon') + filtered_dict = dict(name='server_test', admin_pass='bacon') self.assertEqual(params, filtered_dict) self.stubs.Set(nova.db.api, 'instance_update', @@ -119,7 +119,8 @@ class ServersTest(unittest.TestCase): self.body = json.dumps(dict(server=inst_dict)) def server_update(context, id, params): - self.assertEqual(params, json.loads(self.body)['server']) + filtered_dict = dict(name='server_test', admin_pass='bacon') + self.assertEqual(params, filtered_dict) self.stubs.Set(nova.db.api, 'instance_update', server_update) -- cgit From 724c15b6583b47baabd2f01090580cb248ad1244 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Wed, 29 Sep 2010 14:12:02 -0400 Subject: Remove debuggish print statement. --- bin/nova-manage | 1 - 1 file changed, 1 deletion(-) diff --git a/bin/nova-manage b/bin/nova-manage index 7a9a4c3d1..bf3c67612 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -277,7 +277,6 @@ class UserCommands(object): is_admin = True else: is_admin = False - print "is_admin: %r" % is_admin self.manager.modify_user(name, access_key, secret_key, is_admin) class ProjectCommands(object): -- cgit From 2136f12d29cef9acc7dc6ee0a5901fa3878160f8 Mon Sep 17 00:00:00 2001 From: Michael Gundlach Date: Wed, 29 Sep 2010 15:09:39 -0400 Subject: Make Fault raiseable by inheriting from webob.exc.HTTPException. Change from using self.exception which is reserved by HTTPException to self.wrapped_exc. --- nova/api/rackspace/faults.py | 17 +++++++++-------- nova/tests/api/rackspace/testfaults.py | 10 ++++++++++ 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/nova/api/rackspace/faults.py b/nova/api/rackspace/faults.py index fd6bc3623..32e5c866f 100644 --- a/nova/api/rackspace/faults.py +++ b/nova/api/rackspace/faults.py @@ -17,11 +17,12 @@ import webob.dec +import webob.exc from nova import wsgi -class Fault(wsgi.Application): +class Fault(webob.exc.HTTPException): """An RS API fault response.""" @@ -39,23 +40,23 @@ class Fault(wsgi.Application): def __init__(self, exception): """Create a Fault for the given webob.exc.exception.""" - self.exception = exception + self.wrapped_exc = exception @webob.dec.wsgify def __call__(self, req): - """Generate a WSGI response based on self.exception.""" + """Generate a WSGI response based on the exception passed to ctor.""" # Replace the body with fault details. - code = self.exception.status_int + code = self.wrapped_exc.status_int fault_name = self._fault_names.get(code, "cloudServersFault") fault_data = { fault_name: { 'code': code, - 'message': self.exception.explanation}} + 'message': self.wrapped_exc.explanation}} if code == 413: - retry = self.exception.headers['Retry-After'] + retry = self.wrapped_exc.headers['Retry-After'] fault_data[fault_name]['retryAfter'] = retry # 'code' is an attribute on the fault tag itself metadata = {'application/xml': {'attributes': {fault_name: 'code'}}} serializer = wsgi.Serializer(req.environ, metadata) - self.exception.body = serializer.to_content_type(fault_data) - return self.exception + self.wrapped_exc.body = serializer.to_content_type(fault_data) + return self.wrapped_exc diff --git a/nova/tests/api/rackspace/testfaults.py b/nova/tests/api/rackspace/testfaults.py index 74caffd30..b2931bc98 100644 --- a/nova/tests/api/rackspace/testfaults.py +++ b/nova/tests/api/rackspace/testfaults.py @@ -1,5 +1,6 @@ import unittest import webob +import webob.dec import webob.exc from nova.api.rackspace import faults @@ -28,3 +29,12 @@ class TestFaults(unittest.TestCase): self.assertTrue('sorry' in body_sans_spaces) self.assertTrue('4' in body_sans_spaces) self.assertEqual(resp.headers['Retry-After'], 4) + + def test_raise(self): + @webob.dec.wsgify + def raiser(req): + raise faults.Fault(webob.exc.HTTPNotFound(explanation='whut?')) + req = webob.Request.blank('/.xml') + resp = req.get_response(raiser) + self.assertEqual(resp.status_int, 404) + self.assertTrue('whut?' in resp.body) -- cgit From 072661db01ed196eac92ceb1e942429a0e380e4a Mon Sep 17 00:00:00 2001 From: Michael Gundlach Date: Wed, 29 Sep 2010 15:52:02 -0400 Subject: Support reboot in api.rackspace by extracting reboot function from api.ec2 into api.cloud. --- nova/api/cloud.py | 42 ++++++++++++++++++++++++++++++ nova/api/ec2/cloud.py | 8 ++---- nova/api/rackspace/servers.py | 10 +++++-- nova/tests/api/rackspace/images.py | 1 + nova/tests/api/rackspace/sharedipgroups.py | 1 + 5 files changed, 54 insertions(+), 8 deletions(-) create mode 100644 nova/api/cloud.py diff --git a/nova/api/cloud.py b/nova/api/cloud.py new file mode 100644 index 000000000..345677d4f --- /dev/null +++ b/nova/api/cloud.py @@ -0,0 +1,42 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2010 United States Government as represented by the +# Administrator of the National Aeronautics and Space Administration. +# 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. + +""" +Methods for API calls to control instances via AMQP. +""" + + +from nova import db +from nova import flags +from nova import rpc + +FLAGS = flags.FLAGS + + +def reboot(instance_id, context=None): + """Reboot the given instance. + + #TODO(gundlach) not actually sure what context is used for by ec2 here + -- I think we can just remove it and use None all the time. + """ + instance_ref = db.instance_get_by_ec2_id(None, instance_id) + host = instance_ref['host'] + rpc.cast(db.queue_get_for(context, FLAGS.compute_topic, host), + {"method": "reboot_instance", + "args": {"context": None, + "instance_id": instance_ref['id']}}) diff --git a/nova/api/ec2/cloud.py b/nova/api/ec2/cloud.py index 05e8065f3..4d962fcdd 100644 --- a/nova/api/ec2/cloud.py +++ b/nova/api/ec2/cloud.py @@ -36,6 +36,7 @@ from nova import quota from nova import rpc from nova import utils from nova.compute.instance_types import INSTANCE_TYPES +from nova.api import cloud from nova.api.ec2 import images @@ -664,12 +665,7 @@ class CloudController(object): def reboot_instances(self, context, instance_id, **kwargs): """instance_id is a list of instance ids""" for id_str in instance_id: - instance_ref = db.instance_get_by_ec2_id(context, id_str) - host = instance_ref['host'] - rpc.cast(db.queue_get_for(context, FLAGS.compute_topic, host), - {"method": "reboot_instance", - "args": {"context": None, - "instance_id": instance_ref['id']}}) + cloud.reboot(id_str, context=context) return True def delete_volume(self, context, volume_id, **kwargs): diff --git a/nova/api/rackspace/servers.py b/nova/api/rackspace/servers.py index aa955c222..4f81e25f9 100644 --- a/nova/api/rackspace/servers.py +++ b/nova/api/rackspace/servers.py @@ -24,6 +24,7 @@ from nova import flags from nova import rpc from nova import utils from nova import wsgi +from nova.api import cloud from nova.api.rackspace import _id_translator from nova.compute import power_state from nova.wsgi import Serializer @@ -171,8 +172,13 @@ class Controller(wsgi.Controller): def action(self, req, id): """ multi-purpose method used to reboot, rebuild, and resize a server """ - if not req.environ.has_key('inst_dict'): - return exc.HTTPUnprocessableEntity() + input_dict = self._deserialize(req.body, req) + try: + reboot_type = input_dict['reboot']['type'] + except Exception: + raise faults.Fault(webob.exc.HTTPNotImplemented()) + opaque_id = _instance_id_translator().from_rsapi_id(id) + cloud.reboot(opaque_id) def _build_server_instance(self, req): """Build instance data structure and save it to the data store.""" diff --git a/nova/tests/api/rackspace/images.py b/nova/tests/api/rackspace/images.py index 560d8c898..4c9987e8b 100644 --- a/nova/tests/api/rackspace/images.py +++ b/nova/tests/api/rackspace/images.py @@ -15,6 +15,7 @@ # License for the specific language governing permissions and limitations # under the License. +import stubout import unittest from nova.api.rackspace import images diff --git a/nova/tests/api/rackspace/sharedipgroups.py b/nova/tests/api/rackspace/sharedipgroups.py index b4b281db7..1906b54f5 100644 --- a/nova/tests/api/rackspace/sharedipgroups.py +++ b/nova/tests/api/rackspace/sharedipgroups.py @@ -15,6 +15,7 @@ # License for the specific language governing permissions and limitations # under the License. +import stubout import unittest from nova.api.rackspace import sharedipgroups -- cgit From 128ec65cf39e74b53903dd9788a58c8eb513abe8 Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 29 Sep 2010 16:21:28 -0500 Subject: Server creation up to, but not including, network configuration --- nova/api/rackspace/servers.py | 97 +++++++++++++++++++++------------ nova/db/sqlalchemy/models.py | 1 - nova/tests/api/rackspace/auth.py | 8 ++- nova/tests/api/rackspace/servers.py | 48 +++++++++++----- nova/tests/api/rackspace/test_helper.py | 17 +++++- nova/wsgi.py | 11 ++-- 6 files changed, 123 insertions(+), 59 deletions(-) diff --git a/nova/api/rackspace/servers.py b/nova/api/rackspace/servers.py index aa955c222..cc971adc0 100644 --- a/nova/api/rackspace/servers.py +++ b/nova/api/rackspace/servers.py @@ -25,6 +25,7 @@ from nova import rpc from nova import utils from nova import wsgi from nova.api.rackspace import _id_translator +from nova.compute import instance_types from nova.compute import power_state from nova.wsgi import Serializer import nova.image.service @@ -39,11 +40,11 @@ def _instance_id_translator(): ids """ return _id_translator.RackspaceAPIIdTranslator( "instance", 'nova') -def _image_id_translator(): +def _image_service(): """ Helper method for initializing the image id translator """ service = nova.image.service.ImageService.load() - return _id_translator.RackspaceAPIIdTranslator( - "image", service.__class__.__name__) + return (service, _id_translator.RackspaceAPIIdTranslator( + "image", service.__class__.__name__)) def _filter_params(inst_dict): """ Extracts all updatable parameters for a server update request """ @@ -122,8 +123,11 @@ class Controller(wsgi.Controller): def show(self, req, id): """ Returns server details by server id """ + inst_id_trans = _instance_id_translator() + inst_id = inst_id_trans.from_rs_id(id) + user_id = req.environ['nova.context']['user']['id'] - inst = self.db_driver.instance_get(None, id) + inst = self.db_driver.instance_get_by_ec2_id(None, inst_id) if inst: if inst.user_id == user_id: return _entity_detail(inst) @@ -131,8 +135,11 @@ class Controller(wsgi.Controller): def delete(self, req, id): """ Destroys a server """ + inst_id_trans = _instance_id_translator() + inst_id = inst_id_trans.from_rs_id(id) + user_id = req.environ['nova.context']['user']['id'] - instance = self.db_driver.instance_get(None, id) + instance = self.db_driver.instance_get_by_ec2_id(None, inst_id) if instance and instance['user_id'] == user_id: self.db_driver.instance_destroy(None, id) return exc.HTTPAccepted() @@ -140,10 +147,16 @@ class Controller(wsgi.Controller): def create(self, req): """ Creates a new server for a given user """ - if not req.environ.has_key('inst_dict'): + + env = self._deserialize(req.body, req) + if not env: return exc.HTTPUnprocessableEntity() - inst = self._build_server_instance(req) + #try: + inst = self._build_server_instance(req, env) + #except Exception, e: + # print e + # return exc.HTTPUnprocessableEntity() rpc.cast( FLAGS.compute_topic, { @@ -153,6 +166,8 @@ class Controller(wsgi.Controller): def update(self, req, id): """ Updates the server name or password """ + inst_id_trans = _instance_id_translator() + inst_id = inst_id_trans.from_rs_id(id) user_id = req.environ['nova.context']['user']['id'] inst_dict = self._deserialize(req.body, req) @@ -160,7 +175,7 @@ class Controller(wsgi.Controller): if not inst_dict: return exc.HTTPUnprocessableEntity() - instance = self.db_driver.instance_get(None, id) + instance = self.db_driver.instance_get_by_ec2_id(None, inst_id) if not instance or instance.user_id != user_id: return exc.HTTPNotFound() @@ -174,56 +189,68 @@ class Controller(wsgi.Controller): if not req.environ.has_key('inst_dict'): return exc.HTTPUnprocessableEntity() - def _build_server_instance(self, req): + def _build_server_instance(self, req, env): """Build instance data structure and save it to the data store.""" ltime = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) inst = {} inst_id_trans = _instance_id_translator() - image_id_trans = _image_id_translator() - env = req.environ['inst_dict'] user_id = req.environ['nova.context']['user']['id'] - inst['rs_id'] = inst_id_trans.to_rs_id() + instance_type, flavor = None, None + for k, v in instance_types.INSTANCE_TYPES.iteritems(): + if v['flavorid'] == env['server']['flavorId']: + instance_type, flavor = k, v + break + + if not flavor: + raise Exception, "Flavor not found" + image_id = env['server']['imageId'] - opaque_id = translator_instance().from_rs_id(image_id) + img_service, image_id_trans = _image_service() + + opaque_image_id = image_id_trans.to_rs_id(image_id) + image = img_service.show(opaque_image_id) - inst['name'] = env['server']['name'] - inst['image_id'] = opaque_id - inst['instance_type'] = env['server']['flavorId'] + if not image: + raise Exception, "Image not found" + + inst['server_name'] = env['server']['name'] + inst['image_id'] = opaque_image_id inst['user_id'] = user_id inst['launch_time'] = ltime inst['mac_address'] = utils.generate_mac() + inst['project_id'] = user_id - #TODO(dietz) These are the attributes I'm unsure of inst['state_description'] = 'scheduling' - inst['kernel_id'] = '' - inst['ramdisk_id'] = '' + inst['kernel_id'] = image.get('kernelId', FLAGS.default_kernel) + inst['ramdisk_id'] = image.get('ramdiskId', FLAGS.default_ramdisk) inst['reservation_id'] = utils.generate_uid('r') - inst['key_data'] = '' - inst['key_name'] = '' - inst['security_group'] = '' - # Flavor related attributes - inst['instance_type'] = '' - inst['memory_mb'] = '' - inst['vcpus'] = '' - inst['local_gb'] = '' + #TODO(dietz) this may be ill advised + key_pair_ref = self.db_driver.key_pair_get_all_by_user( + None, user_id)[0] - + inst['key_data'] = key_pair_ref['public_key'] + inst['key_name'] = key_pair_ref['name'] - #TODO(dietz): This seems necessary. How do these apply across - #the Rackspace implementation? - inst['project_id'] = '' + #TODO(dietz) stolen from ec2 api, see TODO there + inst['security_group'] = 'default' - self.network_manager = utils.import_object(FLAGS.rs_network_manager) - - address = self.network_manager.allocate_fixed_ip( None, inst['id']) + # Flavor related attributes + inst['instance_type'] = instance_type + inst['memory_mb'] = flavor['memory_mb'] + inst['vcpus'] = flavor['vcpus'] + inst['local_gb'] = flavor['local_gb'] ref = self.db_driver.instance_create(None, inst) - inst['id'] = ref.id + inst['id'] = inst_id_trans.to_rs_id(ref.ec2_id) + + #self.network_manager = utils.import_object(FLAGS.rs_network_manager) + # + #address = self.network_manager.allocate_fixed_ip( None, inst['id']) return inst diff --git a/nova/db/sqlalchemy/models.py b/nova/db/sqlalchemy/models.py index 2a314b037..22446fc64 100644 --- a/nova/db/sqlalchemy/models.py +++ b/nova/db/sqlalchemy/models.py @@ -199,7 +199,6 @@ class Instance(BASE, NovaBase): id = Column(Integer, primary_key=True) ec2_id = Column(String(10), unique=True) - rs_id = Column(String(255)) admin_pass = Column(String(255)) user_id = Column(String(255)) diff --git a/nova/tests/api/rackspace/auth.py b/nova/tests/api/rackspace/auth.py index a6e10970f..56677c2f4 100644 --- a/nova/tests/api/rackspace/auth.py +++ b/nova/tests/api/rackspace/auth.py @@ -1,12 +1,14 @@ -import webob -import webob.dec +import datetime import unittest + import stubout +import webob +import webob.dec + import nova.api import nova.api.rackspace.auth from nova import auth from nova.tests.api.rackspace import test_helper -import datetime class Test(unittest.TestCase): def setUp(self): diff --git a/nova/tests/api/rackspace/servers.py b/nova/tests/api/rackspace/servers.py index e08c9c6fd..d759eba3c 100644 --- a/nova/tests/api/rackspace/servers.py +++ b/nova/tests/api/rackspace/servers.py @@ -26,6 +26,7 @@ import nova.api.rackspace from nova.api.rackspace import servers import nova.db.api from nova.db.sqlalchemy.models import Instance +import nova.rpc from nova.tests.api.test_helper import * from nova.tests.api.rackspace import test_helper @@ -52,8 +53,11 @@ class ServersTest(unittest.TestCase): test_helper.stub_for_testing(self.stubs) test_helper.stub_out_rate_limiting(self.stubs) test_helper.stub_out_auth(self.stubs) + test_helper.stub_out_id_translator(self.stubs) + test_helper.stub_out_key_pair_funcs(self.stubs) + test_helper.stub_out_image_service(self.stubs) self.stubs.Set(nova.db.api, 'instance_get_all', return_servers) - self.stubs.Set(nova.db.api, 'instance_get', return_server) + self.stubs.Set(nova.db.api, 'instance_get_by_ec2_id', return_server) self.stubs.Set(nova.db.api, 'instance_get_all_by_user', return_servers) @@ -67,9 +71,6 @@ class ServersTest(unittest.TestCase): self.assertEqual(res_dict['server']['id'], '1') self.assertEqual(res_dict['server']['name'], 'server1') - def test_get_backup_schedule(self): - pass - def test_get_server_list(self): req = webob.Request.blank('/v1.0/servers') res = req.get_response(nova.api.API()) @@ -82,19 +83,36 @@ class ServersTest(unittest.TestCase): self.assertEqual(s.get('imageId', None), None) i += 1 - #def test_create_instance(self): - # test_helper.stub_out_image_translator(self.stubs) - # body = dict(server=dict( - # name='server_test', imageId=2, flavorId=2, metadata={}, - # personality = {} - # )) - # req = webob.Request.blank('/v1.0/servers') - # req.method = 'POST' - # req.body = json.dumps(body) + def test_create_instance(self): + def instance_create(context, inst): + class Foo(object): + ec2_id = 1 + return Foo() - # res = req.get_response(nova.api.API()) + def fake_cast(*args, **kwargs): + pass - # print res + self.stubs.Set(nova.db.api, 'instance_create', instance_create) + self.stubs.Set(nova.rpc, 'cast', fake_cast) + + test_helper.stub_out_id_translator(self.stubs) + body = dict(server=dict( + name='server_test', imageId=2, flavorId=2, metadata={}, + personality = {} + )) + req = webob.Request.blank('/v1.0/servers') + req.method = 'POST' + req.body = json.dumps(body) + + res = req.get_response(nova.api.API()) + + self.assertEqual(res.status_int, 200) + + def test_update_no_body(self): + req = webob.Request.blank('/v1.0/servers/1') + req.method = 'PUT' + res = req.get_response(nova.api.API()) + self.assertEqual(res.status_int, 422) def test_update_bad_params(self): """ Confirm that update is filtering params """ diff --git a/nova/tests/api/rackspace/test_helper.py b/nova/tests/api/rackspace/test_helper.py index aa7fb382c..962f0ba4c 100644 --- a/nova/tests/api/rackspace/test_helper.py +++ b/nova/tests/api/rackspace/test_helper.py @@ -9,6 +9,7 @@ from nova import utils from nova import flags import nova.api.rackspace.auth import nova.api.rackspace._id_translator +from nova.image import service from nova.wsgi import Router FLAGS = flags.FLAGS @@ -40,7 +41,21 @@ def fake_wsgi(self, req): req.environ['inst_dict'] = json.loads(req.body) return self.application -def stub_out_image_translator(stubs): + + +def stub_out_key_pair_funcs(stubs): + def key_pair(context, user_id): + return [dict(name='key', public_key='public_key')] + stubs.Set(nova.db.api, 'key_pair_get_all_by_user', + key_pair) + +def stub_out_image_service(stubs): + def fake_image_show(meh, id): + return dict(kernelId=1, ramdiskId=1) + + stubs.Set(nova.image.service.LocalImageService, 'show', fake_image_show) + +def stub_out_id_translator(stubs): class FakeTranslator(object): def __init__(self, id_type, service_name): pass diff --git a/nova/wsgi.py b/nova/wsgi.py index 48c4dabc2..b91d91121 100644 --- a/nova/wsgi.py +++ b/nova/wsgi.py @@ -281,10 +281,13 @@ class Serializer(object): The string must be in the format of a supported MIME type. """ datastring = datastring.strip() - is_xml = (datastring[0] == '<') - if not is_xml: - return json.loads(datastring) - return self._from_xml(datastring) + try: + is_xml = (datastring[0] == '<') + if not is_xml: + return json.loads(datastring) + return self._from_xml(datastring) + except: + return None def _from_xml(self, datastring): xmldata = self.metadata.get('application/xml', {}) -- cgit From 35741ff23bec2b4f301b93128fd018e9c8e70945 Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 29 Sep 2010 17:06:35 -0500 Subject: Servers stuff --- nova/api/rackspace/servers.py | 38 ++++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/nova/api/rackspace/servers.py b/nova/api/rackspace/servers.py index 357e0895f..40cd4f691 100644 --- a/nova/api/rackspace/servers.py +++ b/nova/api/rackspace/servers.py @@ -26,6 +26,8 @@ from nova import utils from nova import wsgi from nova.api import cloud from nova.api.rackspace import _id_translator +from nova.api.rackspace import context +from nova.api.rackspace import faults from nova.compute import instance_types from nova.compute import power_state from nova.wsgi import Serializer @@ -254,10 +256,38 @@ class Controller(wsgi.Controller): ref = self.db_driver.instance_create(None, inst) inst['id'] = inst_id_trans.to_rs_id(ref.ec2_id) - #self.network_manager = utils.import_object(FLAGS.rs_network_manager) - # - #address = self.network_manager.allocate_fixed_ip( None, inst['id']) + # TODO(dietz): this isn't explicitly necessary, but the networking + # calls depend on an object with a project_id property + context = context.APIRequestContext(user_id) + + inst['mac_address'] = utils.generate_mac() + + #TODO(dietz) is this necessary? + inst['launch_index'] = 0 + + inst['hostname'] = instance_ref['ec2_id'] + self.db_driver.instance_update(None, inst_id, inst) + self.network_manager = utils.import_object(FLAGS.rs_network_manager) + address = self.network_manager.allocate_fixed_ip(context, inst_id) + + # TODO(vish): This probably should be done in the scheduler + # network is setup when host is assigned + network_topic = self._get_network_topic(user_id) + rpc.call(network_topic, + {"method": "setup_fixed_ip", + "args": {"context": None, + "address": address}}) return inst - + def _get_network_topic(self, user_id): + """Retrieves the network host for a project""" + network_ref = self.db_driver.project_get_network(None, + user_id) + host = network_ref['host'] + if not host: + host = rpc.call(FLAGS.network_topic, + {"method": "set_network_host", + "args": {"context": None, + "project_id": user_id}}) + return self.db_driver.queue_get_for(None, FLAGS.network_topic, host) -- cgit From 33f101c309852f358ab30a8af64ef64a848f16ae Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 29 Sep 2010 17:36:26 -0500 Subject: Some minor cleanup --- nova/api/rackspace/servers.py | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/nova/api/rackspace/servers.py b/nova/api/rackspace/servers.py index c3d56debd..0d285999b 100644 --- a/nova/api/rackspace/servers.py +++ b/nova/api/rackspace/servers.py @@ -213,14 +213,11 @@ class Controller(wsgi.Controller): user_id = req.environ['nova.context']['user']['id'] - instance_type, flavor = None, None - for k, v in instance_types.INSTANCE_TYPES.iteritems(): - if v['flavorid'] == env['server']['flavorId']: - instance_type, flavor = k, v - break + flavor_id = env['server']['flavorId'] - if not flavor: - raise Exception, "Flavor not found" + instance_type, flavor = [(k, v) for k, v in + instance_types.INSTANCE_TYPES.iteritems() + if v['flavorid'] == flavor_id][0] image_id = env['server']['imageId'] @@ -262,10 +259,10 @@ class Controller(wsgi.Controller): ref = self.db_driver.instance_create(None, inst) inst['id'] = inst_id_trans.to_rs_id(ref.ec2_id) - # TODO(dietz): this isn't explicitly necessary, but the networking - # calls depend on an object with a project_id property + # calls depend on an object with a project_id property, and therefore + # should be cleaned up later api_context = context.APIRequestContext(user_id) inst['mac_address'] = utils.generate_mac() -- cgit From 41e940a5cfa62d56e7d4f111827217c64f0ec61d Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 29 Sep 2010 17:40:46 -0500 Subject: Forgot the context module --- nova/api/rackspace/context.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 nova/api/rackspace/context.py diff --git a/nova/api/rackspace/context.py b/nova/api/rackspace/context.py new file mode 100644 index 000000000..3a7941f0f --- /dev/null +++ b/nova/api/rackspace/context.py @@ -0,0 +1,32 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2010 United States Government as represented by the +# Administrator of the National Aeronautics and Space Administration. +# 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. + +""" +APIRequestContext +""" + +import random + +class APIRequestContext(object): + """ This is an adapter class to get around all of the assumptions made in + the FlatNetworking """ + def __init__(self, user_id): + class Dummy(object): pass + self.user_id = user_id + self.project = Dummy() + self.project.id = self.user_id -- cgit From 6b932780b6bf10b387ad04be6ec88395cae6b564 Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 29 Sep 2010 17:52:15 -0500 Subject: pylint and pep8 cleanup --- nova/api/rackspace/context.py | 8 +++++--- nova/api/rackspace/servers.py | 8 +++----- nova/tests/api/rackspace/flavors.py | 1 - 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/nova/api/rackspace/context.py b/nova/api/rackspace/context.py index 3a7941f0f..924ee151e 100644 --- a/nova/api/rackspace/context.py +++ b/nova/api/rackspace/context.py @@ -22,11 +22,13 @@ APIRequestContext import random +class Project(object): + def __init__(self, user_id): + self.id = user_id + class APIRequestContext(object): """ This is an adapter class to get around all of the assumptions made in the FlatNetworking """ def __init__(self, user_id): - class Dummy(object): pass self.user_id = user_id - self.project = Dummy() - self.project.id = self.user_id + self.project = Project(user_id) diff --git a/nova/api/rackspace/servers.py b/nova/api/rackspace/servers.py index 0d285999b..965deb402 100644 --- a/nova/api/rackspace/servers.py +++ b/nova/api/rackspace/servers.py @@ -15,7 +15,6 @@ # License for the specific language governing permissions and limitations # under the License. -import datetime import time import webob @@ -31,7 +30,6 @@ from nova.api.rackspace import context from nova.api.rackspace import faults from nova.compute import instance_types from nova.compute import power_state -from nova.wsgi import Serializer import nova.api.rackspace import nova.image.service @@ -201,7 +199,7 @@ class Controller(wsgi.Controller): reboot_type = input_dict['reboot']['type'] except Exception: raise faults.Fault(webob.exc.HTTPNotImplemented()) - opaque_id = _instance_id_translator().from_rsapi_id(id) + opaque_id = _instance_id_translator().from_rs_id(id) cloud.reboot(opaque_id) def _build_server_instance(self, req, env): @@ -273,8 +271,8 @@ class Controller(wsgi.Controller): inst['hostname'] = ref.ec2_id self.db_driver.instance_update(None, inst['id'], inst) - self.network_manager = utils.import_object(FLAGS.rs_network_manager) - address = self.network_manager.allocate_fixed_ip(api_context, + network_manager = utils.import_object(FLAGS.rs_network_manager) + address = network_manager.allocate_fixed_ip(api_context, inst['id']) # TODO(vish): This probably should be done in the scheduler diff --git a/nova/tests/api/rackspace/flavors.py b/nova/tests/api/rackspace/flavors.py index 7bd1ea1c4..d25a2e2be 100644 --- a/nova/tests/api/rackspace/flavors.py +++ b/nova/tests/api/rackspace/flavors.py @@ -38,7 +38,6 @@ class FlavorsTest(unittest.TestCase): def test_get_flavor_list(self): req = webob.Request.blank('/v1.0/flavors') res = req.get_response(nova.api.API()) - print res def test_get_flavor_by_id(self): pass -- cgit From 13a73f2606f4b9dee4e51cccbb7e48c8ce322b76 Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 29 Sep 2010 18:00:24 -0500 Subject: Missed a few attributes while mirroring the ec2 instance spin up --- nova/api/rackspace/servers.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/nova/api/rackspace/servers.py b/nova/api/rackspace/servers.py index 965deb402..2395cb358 100644 --- a/nova/api/rackspace/servers.py +++ b/nova/api/rackspace/servers.py @@ -239,6 +239,9 @@ class Controller(wsgi.Controller): inst['ramdisk_id'] = image.get('ramdiskId', FLAGS.default_ramdisk) inst['reservation_id'] = utils.generate_uid('r') + inst['display_name'] = env['server']['name'] + inst['display_description'] = env['server']['name'] + #TODO(dietz) this may be ill advised key_pair_ref = self.db_driver.key_pair_get_all_by_user( None, user_id)[0] -- cgit From b075b504a0a402fc4e8c24379804633139883008 Mon Sep 17 00:00:00 2001 From: Cerberus Date: Wed, 29 Sep 2010 19:28:14 -0500 Subject: Whoops, forgot the exception handling bit --- nova/api/rackspace/servers.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/nova/api/rackspace/servers.py b/nova/api/rackspace/servers.py index 2395cb358..11efd8aef 100644 --- a/nova/api/rackspace/servers.py +++ b/nova/api/rackspace/servers.py @@ -160,11 +160,10 @@ class Controller(wsgi.Controller): if not env: return faults.Fault(exc.HTTPUnprocessableEntity()) - #try: - inst = self._build_server_instance(req, env) - #except Exception, e: - # print e - # return exc.HTTPUnprocessableEntity() + try: + inst = self._build_server_instance(req, env) + except Exception, e: + return faults.Fault(exc.HTTPUnprocessableEntity()) rpc.cast( FLAGS.compute_topic, { -- cgit From 8c21cc52b1ba007fc12964ea5973290a3f660662 Mon Sep 17 00:00:00 2001 From: Ewan Mellor Date: Thu, 30 Sep 2010 10:21:44 +0100 Subject: Bug #651887: xenapi list_instances completely broken Don't just compute the result for list_instances -- return it! --- nova/virt/xenapi.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nova/virt/xenapi.py b/nova/virt/xenapi.py index 1c6de4403..0d06b1fce 100644 --- a/nova/virt/xenapi.py +++ b/nova/virt/xenapi.py @@ -103,8 +103,8 @@ class XenAPIConnection(object): self._conn.login_with_password(user, pw) def list_instances(self): - result = [self._conn.xenapi.VM.get_name_label(vm) \ - for vm in self._conn.xenapi.VM.get_all()] + return [self._conn.xenapi.VM.get_name_label(vm) \ + for vm in self._conn.xenapi.VM.get_all()] @defer.inlineCallbacks def spawn(self, instance): -- cgit From 75c5ba6aae6a57a61771ed78b6797c90f7da6940 Mon Sep 17 00:00:00 2001 From: Cerberus Date: Thu, 30 Sep 2010 09:22:46 -0500 Subject: Grabbed the wrong copyright info --- nova/api/rackspace/context.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/nova/api/rackspace/context.py b/nova/api/rackspace/context.py index 924ee151e..77394615b 100644 --- a/nova/api/rackspace/context.py +++ b/nova/api/rackspace/context.py @@ -1,7 +1,6 @@ # vim: tabstop=4 shiftwidth=4 softtabstop=4 -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. +# Copyright 2010 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may -- cgit From 76d9510ac496051697f7cdf0d693d5146e83283a Mon Sep 17 00:00:00 2001 From: Ewan Mellor Date: Thu, 30 Sep 2010 16:00:53 +0100 Subject: Bug #652103: NameError in exception handler in sqlalchemy API layer Fix reference to NoResultFound. --- nova/db/sqlalchemy/api.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/nova/db/sqlalchemy/api.py b/nova/db/sqlalchemy/api.py index 9c3caf9af..e63d3b18e 100644 --- a/nova/db/sqlalchemy/api.py +++ b/nova/db/sqlalchemy/api.py @@ -30,6 +30,7 @@ from nova.db.sqlalchemy.session import get_session from sqlalchemy import or_ from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import joinedload_all +from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.sql import exists, func FLAGS = flags.FLAGS @@ -348,7 +349,7 @@ def fixed_ip_get_by_address(_context, address): ).filter_by(address=address ).filter_by(deleted=False ).one() - except exc.NoResultFound: + except NoResultFound: new_exc = exception.NotFound("No model for address %s" % address) raise new_exc.__class__, new_exc, sys.exc_info()[2] -- cgit From ae55b04a4b25c6756311f001e36b5bbd76675e8c Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Thu, 30 Sep 2010 18:48:45 -0400 Subject: Mongo bad, swift good. --- nova/objectstore/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/objectstore/__init__.py b/nova/objectstore/__init__.py index b8890ac03..ecad9be7c 100644 --- a/nova/objectstore/__init__.py +++ b/nova/objectstore/__init__.py @@ -22,7 +22,7 @@ .. automodule:: nova.objectstore :platform: Unix - :synopsis: Currently a trivial file-based system, getting extended w/ mongo. + :synopsis: Currently a trivial file-based system, getting extended w/ swift. .. moduleauthor:: Jesse Andrews .. moduleauthor:: Devin Carlen .. moduleauthor:: Vishvananda Ishaya -- cgit