From 48c04eb35fae704913e9ed05868d1334ee5458fa Mon Sep 17 00:00:00 2001 From: Mark Washenberger Date: Wed, 23 Mar 2011 12:17:48 -0400 Subject: add changePassword action to os api v1.1 --- nova/api/openstack/servers.py | 13 +++++++++ nova/tests/api/openstack/test_servers.py | 46 ++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index 73843f63e..90f709a47 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -256,6 +256,7 @@ class Controller(wsgi.Controller): resize a server""" actions = { + 'changePassword': self._action_change_password, 'reboot': self._action_reboot, 'resize': self._action_resize, 'confirmResize': self._action_confirm_resize, @@ -269,6 +270,9 @@ class Controller(wsgi.Controller): return actions[key](input_dict, req, id) return faults.Fault(exc.HTTPNotImplemented()) + def _action_change_password(self, input_dict, req, id): + return exc.HTTPNotImplemented() + def _action_confirm_resize(self, input_dict, req, id): try: self.compute_api.confirm_resize(req.environ['nova.context'], id) @@ -555,6 +559,15 @@ class ControllerV11(Controller): def _get_addresses_view_builder(self, req): return nova.api.openstack.views.addresses.ViewBuilderV11(req) + def _action_change_password(self, input_dict, req, id): + context = req.environ['nova.context'] + if not 'changePassword' in input_dict \ + or not 'adminPass' in input_dict['changePassword']: + return exc.HTTPBadRequest() + password = input_dict['changePassword']['adminPass'] + self.compute_api.set_admin_password(context, id, password) + return exc.HTTPAccepted() + class ServerCreateRequestXMLDeserializer(object): """ diff --git a/nova/tests/api/openstack/test_servers.py b/nova/tests/api/openstack/test_servers.py index e21637ea4..dc5fedb8c 100644 --- a/nova/tests/api/openstack/test_servers.py +++ b/nova/tests/api/openstack/test_servers.py @@ -558,6 +558,52 @@ class ServersTest(test.TestCase): res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 404) + def test_server_change_password(self): + body = {'changePassword': {'adminPass': '1234pass'}} + req = webob.Request.blank('/v1.0/servers/1/action') + req.method = 'POST' + req.content_type = 'application/json' + req.body = json.dumps(body) + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 501) + + def test_server_change_password_v1_1(self): + + class MockSetAdminPassword(object): + + def __init__(self): + self.called = False + self.instance_id = None + self.password = None + + def __call__(self, context, instance_id, password): + self.called = True + self.instance_id = instance_id + self.password = password + + mock_method = MockSetAdminPassword() + self.stubs.Set(nova.compute.api.API, 'set_admin_password', mock_method) + + body = {'changePassword': {'adminPass': '1234pass'}} + req = webob.Request.blank('/v1.1/servers/1/action') + req.method = 'POST' + req.content_type = 'application/json' + req.body = json.dumps(body) + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 202) + self.assertTrue(mock_method.called) + self.assertEqual(mock_method.instance_id, '1') + self.assertEqual(mock_method.password, '1234pass') + + def test_server_change_password_bad_request_v1_1(self): + body = {'changePassword': {'pass': '12345'}} + req = webob.Request.blank('/v1.1/servers/1/action') + req.method = 'POST' + req.content_type = 'application/json' + req.body = json.dumps(body) + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 400) + def test_server_reboot(self): body = dict(server=dict( name='server_test', imageId=2, flavorId=2, metadata={}, -- cgit From 5977a511ed202fcf396e7c60d713eb5329d6883b Mon Sep 17 00:00:00 2001 From: Mark Washenberger Date: Mon, 28 Mar 2011 13:30:15 -0400 Subject: style changes --- nova/api/openstack/servers.py | 12 ++++++------ nova/tests/api/openstack/test_servers.py | 5 ----- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index a8e3e7900..a98f81d98 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -267,11 +267,11 @@ class Controller(wsgi.Controller): actions = { 'changePassword': self._action_change_password, - 'reboot': self._action_reboot, - 'resize': self._action_resize, + 'reboot': self._action_reboot, + 'resize': self._action_resize, 'confirmResize': self._action_confirm_resize, - 'revertResize': self._action_revert_resize, - 'rebuild': self._action_rebuild, + 'revertResize': self._action_revert_resize, + 'rebuild': self._action_rebuild, } input_dict = self._deserialize(req.body, req.get_content_type()) @@ -595,8 +595,8 @@ class ControllerV11(Controller): def _action_change_password(self, input_dict, req, id): context = req.environ['nova.context'] - if not 'changePassword' in input_dict \ - or not 'adminPass' in input_dict['changePassword']: + if (not 'changePassword' in input_dict + or not 'adminPass' in input_dict['changePassword']): return exc.HTTPBadRequest() password = input_dict['changePassword']['adminPass'] self.compute_api.set_admin_password(context, id, password) diff --git a/nova/tests/api/openstack/test_servers.py b/nova/tests/api/openstack/test_servers.py index d2a72dd10..25d69401d 100644 --- a/nova/tests/api/openstack/test_servers.py +++ b/nova/tests/api/openstack/test_servers.py @@ -655,20 +655,16 @@ class ServersTest(test.TestCase): def test_server_change_password_v1_1(self): class MockSetAdminPassword(object): - def __init__(self): - self.called = False self.instance_id = None self.password = None def __call__(self, context, instance_id, password): - self.called = True self.instance_id = instance_id self.password = password mock_method = MockSetAdminPassword() self.stubs.Set(nova.compute.api.API, 'set_admin_password', mock_method) - body = {'changePassword': {'adminPass': '1234pass'}} req = webob.Request.blank('/v1.1/servers/1/action') req.method = 'POST' @@ -676,7 +672,6 @@ class ServersTest(test.TestCase): req.body = json.dumps(body) res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 202) - self.assertTrue(mock_method.called) self.assertEqual(mock_method.instance_id, '1') self.assertEqual(mock_method.password, '1234pass') -- cgit From 71347f2e9d6195a25cabff782c7058bed006e286 Mon Sep 17 00:00:00 2001 From: Mark Washenberger Date: Mon, 28 Mar 2011 13:40:16 -0400 Subject: lock down requirements for change password --- nova/api/openstack/servers.py | 2 ++ nova/tests/api/openstack/test_servers.py | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index a98f81d98..b5727a7e1 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -599,6 +599,8 @@ class ControllerV11(Controller): or not 'adminPass' in input_dict['changePassword']): return exc.HTTPBadRequest() password = input_dict['changePassword']['adminPass'] + if not isinstance(password, basestring) or password == '': + return exc.HTTPBadRequest() self.compute_api.set_admin_password(context, id, password) return exc.HTTPAccepted() diff --git a/nova/tests/api/openstack/test_servers.py b/nova/tests/api/openstack/test_servers.py index 25d69401d..6d6be817a 100644 --- a/nova/tests/api/openstack/test_servers.py +++ b/nova/tests/api/openstack/test_servers.py @@ -684,6 +684,33 @@ class ServersTest(test.TestCase): res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 400) + def test_server_change_password_empty_string_v1_1(self): + body = {'changePassword': {'adminPass': ''}} + req = webob.Request.blank('/v1.1/servers/1/action') + req.method = 'POST' + req.content_type = 'application/json' + req.body = json.dumps(body) + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 400) + + def test_server_change_password_none_v1_1(self): + body = {'changePassword': {'adminPass': None}} + req = webob.Request.blank('/v1.1/servers/1/action') + req.method = 'POST' + req.content_type = 'application/json' + req.body = json.dumps(body) + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 400) + + def test_server_change_password_not_a_string_v1_1(self): + body = {'changePassword': {'adminPass': 1234}} + req = webob.Request.blank('/v1.1/servers/1/action') + req.method = 'POST' + req.content_type = 'application/json' + req.body = json.dumps(body) + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 400) + def test_server_reboot(self): body = dict(server=dict( name='server_test', imageId=2, flavorId=2, metadata={}, -- cgit From 63747d35929a1df0a29792f41657b4821c5787a3 Mon Sep 17 00:00:00 2001 From: Mark Washenberger Date: Mon, 28 Mar 2011 13:50:24 -0400 Subject: pep8 whitespace --- nova/api/openstack/servers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index b5727a7e1..aaae17a39 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -595,7 +595,7 @@ class ControllerV11(Controller): def _action_change_password(self, input_dict, req, id): context = req.environ['nova.context'] - if (not 'changePassword' in input_dict + if (not 'changePassword' in input_dict or not 'adminPass' in input_dict['changePassword']): return exc.HTTPBadRequest() password = input_dict['changePassword']['adminPass'] -- cgit From 5c74862a08a82b7db3e11fbcbec63293ea903e00 Mon Sep 17 00:00:00 2001 From: Ken Pepple Date: Mon, 28 Mar 2011 23:11:42 -0700 Subject: make all openstack status uppercase --- nova/api/openstack/views/servers.py | 4 ++-- nova/tests/api/openstack/test_servers.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/nova/api/openstack/views/servers.py b/nova/api/openstack/views/servers.py index 4e7f62eb3..6b471a0f4 100644 --- a/nova/api/openstack/views/servers.py +++ b/nova/api/openstack/views/servers.py @@ -72,12 +72,12 @@ class ViewBuilder(object): 'id': int(inst['id']), 'name': inst['display_name'], 'addresses': self.addresses_builder.build(inst), - 'status': power_mapping[inst.get('state')]} + 'status': power_mapping[inst.get('state')].upper()} ctxt = nova.context.get_admin_context() compute_api = nova.compute.API() if compute_api.has_finished_migration(ctxt, inst['id']): - inst_dict['status'] = 'resize-confirm' + inst_dict['status'] = 'resize-confirm'.upper() # Return the metadata as a dictionary metadata = {} diff --git a/nova/tests/api/openstack/test_servers.py b/nova/tests/api/openstack/test_servers.py index 989385a8c..27cbd28c1 100644 --- a/nova/tests/api/openstack/test_servers.py +++ b/nova/tests/api/openstack/test_servers.py @@ -738,7 +738,7 @@ class ServersTest(test.TestCase): fake_migration_get) res = req.get_response(fakes.wsgi_app()) body = json.loads(res.body) - self.assertEqual(body['server']['status'], 'resize-confirm') + self.assertEqual(body['server']['status'], 'RESIZE-CONFIRM') def test_confirm_resize_server(self): req = self.webreq('/1/action', 'POST', dict(confirmResize=None)) -- cgit From c512bae72859b8583731886011e8f9a4310d69f8 Mon Sep 17 00:00:00 2001 From: Mark Washenberger Date: Tue, 29 Mar 2011 10:53:44 -0400 Subject: use informative error messages --- nova/api/openstack/servers.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index aaae17a39..31b9bc2f1 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -597,10 +597,12 @@ class ControllerV11(Controller): context = req.environ['nova.context'] if (not 'changePassword' in input_dict or not 'adminPass' in input_dict['changePassword']): - return exc.HTTPBadRequest() + msg = _("No adminPass was specified") + return exc.HTTPBadRequest(msg) password = input_dict['changePassword']['adminPass'] if not isinstance(password, basestring) or password == '': - return exc.HTTPBadRequest() + msg = _("Invalid adminPass") + return exc.HTTPBadRequest(msg) self.compute_api.set_admin_password(context, id, password) return exc.HTTPAccepted() -- cgit From 3987547248e07719dbc63752100b695ef0be1a9c Mon Sep 17 00:00:00 2001 From: John Tran Date: Tue, 29 Mar 2011 13:44:38 -0700 Subject: initial unit test for describe images --- nova/tests/test_cloud.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/nova/tests/test_cloud.py b/nova/tests/test_cloud.py index 00803d0ad..791498f89 100644 --- a/nova/tests/test_cloud.py +++ b/nova/tests/test_cloud.py @@ -216,6 +216,16 @@ class CloudTestCase(test.TestCase): db.service_destroy(self.context, comp1['id']) db.service_destroy(self.context, comp2['id']) + def test_describe_images(self): + def fake_detail(meh, context): + return [{'id': 1, 'properties': {'kernel_id': 1, 'ramdisk_id': 1, + 'type':'machine'}}] + + self.stubs.Set(local.LocalImageService, 'detail', fake_detail) + result = self.cloud.describe_images(self.context) + result = result['imagesSet'][0] + self.assertEqual(result['imageId'], 'ami-00000001') + def test_console_output(self): instance_type = FLAGS.default_instance_type max_count = 1 -- cgit From d92322400c31f1cad933da5117b24376d60a5798 Mon Sep 17 00:00:00 2001 From: John Tran Date: Tue, 29 Mar 2011 17:07:59 -0700 Subject: adding unit tests for describe_images --- Authors | 1 + nova/tests/test_cloud.py | 31 ++++++++++++++++++++++++++----- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/Authors b/Authors index eccf38a43..48b912184 100644 --- a/Authors +++ b/Authors @@ -32,6 +32,7 @@ Jesse Andrews Joe Heck Joel Moore John Dewey +John Tran Jonathan Bryce Jordan Rinke Josh Durgin diff --git a/nova/tests/test_cloud.py b/nova/tests/test_cloud.py index 791498f89..5cb969979 100644 --- a/nova/tests/test_cloud.py +++ b/nova/tests/test_cloud.py @@ -41,6 +41,7 @@ from nova.compute import power_state from nova.api.ec2 import cloud from nova.api.ec2 import ec2utils from nova.image import local +from nova.exception import NotFound FLAGS = flags.FLAGS @@ -71,7 +72,8 @@ class CloudTestCase(test.TestCase): host = self.network.get_network_host(self.context.elevated()) def fake_show(meh, context, id): - return {'id': 1, 'properties': {'kernel_id': 1, 'ramdisk_id': 1}} + return {'id': 1, 'properties': {'kernel_id': 1, 'ramdisk_id': 1, + 'type': 'machine'}} self.stubs.Set(local.LocalImageService, 'show', fake_show) self.stubs.Set(local.LocalImageService, 'show_by_name', fake_show) @@ -217,14 +219,33 @@ class CloudTestCase(test.TestCase): db.service_destroy(self.context, comp2['id']) def test_describe_images(self): + describe_images = self.cloud.describe_images + def fake_detail(meh, context): return [{'id': 1, 'properties': {'kernel_id': 1, 'ramdisk_id': 1, - 'type':'machine'}}] + 'type': 'machine'}}] + + def fake_show_none(meh, context, id): + raise NotFound self.stubs.Set(local.LocalImageService, 'detail', fake_detail) - result = self.cloud.describe_images(self.context) - result = result['imagesSet'][0] - self.assertEqual(result['imageId'], 'ami-00000001') + # list all + result1 = describe_images(self.context) + result1 = result1['imagesSet'][0] + self.assertEqual(result1['imageId'], 'ami-00000001') + # provided a valid image_id + result2 = describe_images(self.context, ['ami-00000001']) + self.assertEqual(1, len(result2['imagesSet'])) + # provide more than 1 valid image_id + result3 = describe_images(self.context, ['ami-00000001', + 'ami-00000002']) + self.assertEqual(2, len(result3['imagesSet'])) + # provide an non-existing image_id + self.stubs.UnsetAll() + self.stubs.Set(local.LocalImageService, 'show', fake_show_none) + self.stubs.Set(local.LocalImageService, 'show_by_name', fake_show_none) + self.assertRaises(NotFound, describe_images, + self.context, ['ami-fake']) def test_console_output(self): instance_type = FLAGS.default_instance_type -- cgit From 7aa0102b2d451ffa87a095ac4471a65260aff3fe Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Tue, 29 Mar 2011 22:55:16 -0700 Subject: make sure that flag is there in compute api --- nova/compute/api.py | 1 + 1 file changed, 1 insertion(+) diff --git a/nova/compute/api.py b/nova/compute/api.py index 7977b07a2..7f358fdfd 100644 --- a/nova/compute/api.py +++ b/nova/compute/api.py @@ -39,6 +39,7 @@ from nova.db import base FLAGS = flags.FLAGS LOG = logging.getLogger('nova.compute.api') +flags.DECLARE('vncproxy_topic', 'nova.vnc') def generate_default_hostname(instance_id): -- cgit From 951ec0d0fb2711e5d5ef4d6e9e78fe74d6c62360 Mon Sep 17 00:00:00 2001 From: Masanori Itoh Date: Thu, 31 Mar 2011 00:45:59 +0900 Subject: Added synchronize_session parameter to a query in fixed_ip_disassociate_all_by_timeout() and fix #735974. --- 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 b2a13a01b..08eb0b7b2 100644 --- a/nova/db/sqlalchemy/api.py +++ b/nova/db/sqlalchemy/api.py @@ -660,7 +660,7 @@ def fixed_ip_disassociate_all_by_timeout(_context, host, time): filter(models.FixedIp.instance_id != None).\ filter_by(allocated=0).\ update({'instance_id': None, - 'leased': 0}) + 'leased': 0}, synchronize_session='fetch') return result -- cgit From c29dc77c6f42c5a345ee6b510a373236d7988440 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Wed, 30 Mar 2011 12:46:22 -0700 Subject: fixed ordering and spacing --- nova/compute/api.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/nova/compute/api.py b/nova/compute/api.py index a5f6afb02..996955fe3 100644 --- a/nova/compute/api.py +++ b/nova/compute/api.py @@ -37,8 +37,11 @@ from nova.compute import instance_types from nova.scheduler import api as scheduler_api from nova.db import base -FLAGS = flags.FLAGS + LOG = logging.getLogger('nova.compute.api') + + +FLAGS = flags.FLAGS flags.DECLARE('vncproxy_topic', 'nova.vnc') -- cgit From a1992ba586acc7545a7edb37130727e19e4d1065 Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Wed, 30 Mar 2011 13:13:04 -0700 Subject: Add ed leafe's code for the inject_file agent plugin method that somehow got lost (fixes bug 741246). Update TimeoutError string for i18n --- plugins/xenserver/xenapi/etc/xapi.d/plugins/agent | 79 +++++++++++++++++++++-- 1 file changed, 75 insertions(+), 4 deletions(-) diff --git a/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent b/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent index 94eaabe73..3522df49d 100755 --- a/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent +++ b/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent @@ -22,6 +22,7 @@ # XenAPI plugin for reading/writing information to xenstore # +import base64 try: import json except ImportError: @@ -31,6 +32,7 @@ import random import subprocess import tempfile import time +import uuid import XenAPIPlugin @@ -102,6 +104,75 @@ def resetnetwork(self, arg_dict): xenstore.write_record(self, arg_dict) +@jsonify +def inject_file(self, arg_dict): + """Expects a file path and the contents of the file to be written. Both + should be base64-encoded in order to eliminate errors as they are passed + through the stack. Writes that information to xenstore for the agent, + which will decode the file and intended path, and create it on the + instance. The original agent munged both of these into a single entry; + the new agent keeps them separate. We will need to test for the new agent, + and write the xenstore records to match the agent version. We will also + need to test to determine if the file injection method on the agent has + been disabled, and raise a NotImplemented error if that is the case. + """ + b64_path = arg_dict["b64_path"] + b64_file = arg_dict["b64_file"] + request_id = arg_dict["id"] + if self._agent_has_method("file_inject"): + # New version of the agent. Agent should receive a 'value' + # key whose value is a dictionary containing 'b64_path' and + # 'b64_file'. See old version below. + arg_dict["value"] = json.dumps({"name": "file_inject", + "value": {"b64_path": b64_path, "b64_file": b64_file}}) + elif self._agent_has_method("injectfile"): + # Old agent requires file path and file contents to be + # combined into one base64 value. + raw_path = base64.b64decode(b64_path) + raw_file = base64.b64decode(b64_file) + new_b64 = base64.b64encode("%s,%s") % (raw_path, raw_file) + arg_dict["value"] = json.dumps({"name": "injectfile", + "value": new_b64}) + else: + # Either the methods don't exist in the agent, or they + # have been disabled. + raise NotImplementedError("NOT IMPLEMENTED: Agent does not support" + " file injection.") + arg_dict["path"] = "data/host/%s" % request_id + xenstore.write_record(self, arg_dict) + try: + resp = _wait_for_agent(self, request_id, arg_dict) + except TimeoutError, e: + raise PluginError("%s" % e) + return resp + + +def _agent_has_method(self, method): + """Check that the agent has a particular method by checking its + features. Cache the features so we don't have to query the agent + every time we need to check. + """ + try: + self._agent_methods + except AttributeError: + self._agent_methods = [] + if not self._agent_methods: + # Haven't been defined + tmp_id = str(uuid.uuid4()) + dct = {} + dct["value"] = json.dumps({"name": "features", "value": ""}) + dct["path"] = "data/host/%s" % tmp_id + xenstore.write_record(self, dct) + try: + resp = _wait_for_agent(self, tmp_id, dct) + except TimeoutError, e: + raise PluginError("%s" % e) + response = json.loads(resp) + # The agent returns a comma-separated list of methods. + self._agent_methods = response.split(",") + return method in self._agent_methods + + def _wait_for_agent(self, request_id, arg_dict): """Periodically checks xenstore for a response from the agent. The request is always written to 'data/host/{id}', and @@ -119,9 +190,8 @@ def _wait_for_agent(self, request_id, arg_dict): # First, delete the request record arg_dict["path"] = "data/host/%s" % request_id xenstore.delete_record(self, arg_dict) - raise TimeoutError( - "TIMEOUT: No response from agent within %s seconds." % - AGENT_TIMEOUT) + raise TimeoutError(_("TIMEOUT: No response from agent within" + " %s seconds.") % AGENT_TIMEOUT) ret = xenstore.read_record(self, arg_dict) # Note: the response for None with be a string that includes # double quotes. @@ -136,4 +206,5 @@ if __name__ == "__main__": XenAPIPlugin.dispatch( {"key_init": key_init, "password": password, - "resetnetwork": resetnetwork}) + "resetnetwork": resetnetwork, + "inject_file": inject_file}) -- cgit From ba5715b46d82498ed30aa146294850a134022617 Mon Sep 17 00:00:00 2001 From: Tushar Patil Date: Wed, 30 Mar 2011 13:32:13 -0700 Subject: Fix for LP Bug #745152 --- nova/network/api.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/nova/network/api.py b/nova/network/api.py index 4ee1148cb..424c3f592 100644 --- a/nova/network/api.py +++ b/nova/network/api.py @@ -66,6 +66,18 @@ class API(base.Base): if isinstance(fixed_ip, str) or isinstance(fixed_ip, unicode): fixed_ip = self.db.fixed_ip_get_by_address(context, fixed_ip) floating_ip = self.db.floating_ip_get_by_address(context, floating_ip) + # Check if the floating ip address is allocated + if floating_ip['project_id'] is None: + raise exception.ApiError(_("Address (%s) is not allocated") + % floating_ip['address']) + # Check if the floating ip address is allocated to the same project + if floating_ip['project_id'] != context.project_id: + LOG.warn(_("Address (%s) is not allocated to your project " + "(%s)"), floating_ip['address'], context.project_id) + raise exception.ApiError(_("Address (%s) is not " + "allocated to your project (%s)") % + (floating_ip['address'], + context.project_id)) # NOTE(vish): Perhaps we should just pass this on to compute and # let compute communicate with network. host = fixed_ip['network']['host'] -- cgit From 1e9cc02d3cb63c9431921064aac23327198d4b8c Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Wed, 30 Mar 2011 13:36:03 -0700 Subject: Change '"%s" % e' to 'e'. --- plugins/xenserver/xenapi/etc/xapi.d/plugins/agent | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent b/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent index 3522df49d..83ac341a7 100755 --- a/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent +++ b/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent @@ -68,7 +68,7 @@ def key_init(self, arg_dict): try: resp = _wait_for_agent(self, request_id, arg_dict) except TimeoutError, e: - raise PluginError("%s" % e) + raise PluginError(e) return resp @@ -89,7 +89,7 @@ def password(self, arg_dict): try: resp = _wait_for_agent(self, request_id, arg_dict) except TimeoutError, e: - raise PluginError("%s" % e) + raise PluginError(e) return resp @@ -143,7 +143,7 @@ def inject_file(self, arg_dict): try: resp = _wait_for_agent(self, request_id, arg_dict) except TimeoutError, e: - raise PluginError("%s" % e) + raise PluginError(e) return resp @@ -166,7 +166,7 @@ def _agent_has_method(self, method): try: resp = _wait_for_agent(self, tmp_id, dct) except TimeoutError, e: - raise PluginError("%s" % e) + raise PluginError(e) response = json.loads(resp) # The agent returns a comma-separated list of methods. self._agent_methods = response.split(",") -- cgit From cf89dea62e777bb3052f3a178e38d0b665c1983d Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Wed, 30 Mar 2011 13:38:10 -0700 Subject: localize NotImplementedError() --- plugins/xenserver/xenapi/etc/xapi.d/plugins/agent | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent b/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent index 83ac341a7..5c5a6d645 100755 --- a/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent +++ b/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent @@ -136,8 +136,8 @@ def inject_file(self, arg_dict): else: # Either the methods don't exist in the agent, or they # have been disabled. - raise NotImplementedError("NOT IMPLEMENTED: Agent does not support" - " file injection.") + raise NotImplementedError(_("NOT IMPLEMENTED: Agent does not" + " support file injection.")) arg_dict["path"] = "data/host/%s" % request_id xenstore.write_record(self, arg_dict) try: -- cgit From bb1c49bc324956241383add85297510842d4464c Mon Sep 17 00:00:00 2001 From: Tushar Patil Date: Wed, 30 Mar 2011 15:00:47 -0700 Subject: fixed review comment for i18n string multiple replacement strings need to use dictionary format --- nova/network/api.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/nova/network/api.py b/nova/network/api.py index 424c3f592..47e56ebc6 100644 --- a/nova/network/api.py +++ b/nova/network/api.py @@ -68,16 +68,20 @@ class API(base.Base): floating_ip = self.db.floating_ip_get_by_address(context, floating_ip) # Check if the floating ip address is allocated if floating_ip['project_id'] is None: - raise exception.ApiError(_("Address (%s) is not allocated") - % floating_ip['address']) + raise exception.ApiError(_("Address (%(address)s) is not " + "allocated") % {'address': + floating_ip['address']}) # Check if the floating ip address is allocated to the same project if floating_ip['project_id'] != context.project_id: - LOG.warn(_("Address (%s) is not allocated to your project " - "(%s)"), floating_ip['address'], context.project_id) - raise exception.ApiError(_("Address (%s) is not " - "allocated to your project (%s)") % - (floating_ip['address'], - context.project_id)) + LOG.warn(_("Address (%(address)s) is not allocated to your " + "project (%(project)s)"), + {'address': floating_ip['address'], + 'project': context.project_id}) + raise exception.ApiError(_("Address (%(address)s) is not " + "allocated to your project" + "(%(project)s)") % + {'address': floating_ip['address'], + 'project': context.project_id}) # NOTE(vish): Perhaps we should just pass this on to compute and # let compute communicate with network. host = fixed_ip['network']['host'] -- cgit From 7d86a9e478c92ac9f79039c4592c6355c91b8b61 Mon Sep 17 00:00:00 2001 From: Tushar Patil Date: Wed, 30 Mar 2011 15:10:55 -0700 Subject: fixed review comment for i18n string multiple replacement strings need to use dictionary format --- nova/network/api.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/nova/network/api.py b/nova/network/api.py index 47e56ebc6..c56e3062b 100644 --- a/nova/network/api.py +++ b/nova/network/api.py @@ -68,9 +68,8 @@ class API(base.Base): floating_ip = self.db.floating_ip_get_by_address(context, floating_ip) # Check if the floating ip address is allocated if floating_ip['project_id'] is None: - raise exception.ApiError(_("Address (%(address)s) is not " - "allocated") % {'address': - floating_ip['address']}) + raise exception.ApiError(_("Address (%s) is not allocated") % + floating_ip['address']) # Check if the floating ip address is allocated to the same project if floating_ip['project_id'] != context.project_id: LOG.warn(_("Address (%(address)s) is not allocated to your " -- cgit From ce5ad4acbc81c8c444d7b6a02400d6bc0ef6b233 Mon Sep 17 00:00:00 2001 From: Devin Carlen Date: Wed, 30 Mar 2011 20:33:56 -0700 Subject: Removed adminclient and referred to pypi nova_adminclient module --- nova/adminclient.py | 473 ----------------------------------------------- smoketests/test_admin.py | 2 +- tools/pip-requires | 1 + 3 files changed, 2 insertions(+), 474 deletions(-) delete mode 100644 nova/adminclient.py diff --git a/nova/adminclient.py b/nova/adminclient.py deleted file mode 100644 index f570e12c2..000000000 --- a/nova/adminclient.py +++ /dev/null @@ -1,473 +0,0 @@ -# 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. -""" -Nova User API client library. -""" - -import base64 -import boto -import boto.exception -import httplib -import re -import string - -from boto.ec2.regioninfo import RegionInfo - - -DEFAULT_CLC_URL = 'http://127.0.0.1:8773' -DEFAULT_REGION = 'nova' - - -class UserInfo(object): - """ - Information about a Nova user, as parsed through SAX. - - **Fields Include** - - * username - * accesskey - * secretkey - * file (optional) containing zip of X509 cert & rc file - - """ - - def __init__(self, connection=None, username=None, endpoint=None): - self.connection = connection - self.username = username - self.endpoint = endpoint - - def __repr__(self): - return 'UserInfo:%s' % self.username - - def startElement(self, name, attrs, connection): - return None - - def endElement(self, name, value, connection): - if name == 'username': - self.username = str(value) - elif name == 'file': - self.file = base64.b64decode(str(value)) - elif name == 'accesskey': - self.accesskey = str(value) - elif name == 'secretkey': - self.secretkey = str(value) - - -class UserRole(object): - """ - Information about a Nova user's role, as parsed through SAX. - - **Fields include** - - * role - - """ - - def __init__(self, connection=None): - self.connection = connection - self.role = None - - def __repr__(self): - return 'UserRole:%s' % self.role - - def startElement(self, name, attrs, connection): - return None - - def endElement(self, name, value, connection): - if name == 'role': - self.role = value - else: - setattr(self, name, str(value)) - - -class ProjectInfo(object): - """ - Information about a Nova project, as parsed through SAX. - - **Fields include** - - * projectname - * description - * projectManagerId - * memberIds - - """ - - def __init__(self, connection=None): - self.connection = connection - self.projectname = None - self.description = None - self.projectManagerId = None - self.memberIds = [] - - def __repr__(self): - return 'ProjectInfo:%s' % self.projectname - - def startElement(self, name, attrs, connection): - return None - - def endElement(self, name, value, connection): - if name == 'projectname': - self.projectname = value - elif name == 'description': - self.description = value - elif name == 'projectManagerId': - self.projectManagerId = value - elif name == 'memberId': - self.memberIds.append(value) - else: - setattr(self, name, str(value)) - - -class ProjectMember(object): - """ - Information about a Nova project member, as parsed through SAX. - - **Fields include** - - * memberId - - """ - - def __init__(self, connection=None): - self.connection = connection - self.memberId = None - - def __repr__(self): - return 'ProjectMember:%s' % self.memberId - - def startElement(self, name, attrs, connection): - return None - - def endElement(self, name, value, connection): - if name == 'member': - self.memberId = value - else: - setattr(self, name, str(value)) - - -class HostInfo(object): - """ - Information about a Nova Host, as parsed through SAX. - - **Fields Include** - - * Hostname - * Compute service status - * Volume service status - * Instance count - * Volume count - """ - - def __init__(self, connection=None): - self.connection = connection - self.hostname = None - self.compute = None - self.volume = None - self.instance_count = 0 - self.volume_count = 0 - - def __repr__(self): - return 'Host:%s' % self.hostname - - # this is needed by the sax parser, so ignore the ugly name - def startElement(self, name, attrs, connection): - return None - - # this is needed by the sax parser, so ignore the ugly name - def endElement(self, name, value, connection): - fixed_name = string.lower(re.sub(r'([A-Z])', r'_\1', name)) - setattr(self, fixed_name, value) - - -class Vpn(object): - """ - Information about a Vpn, as parsed through SAX - - **Fields Include** - - * instance_id - * project_id - * public_ip - * public_port - * created_at - * internal_ip - * state - """ - - def __init__(self, connection=None): - self.connection = connection - self.instance_id = None - self.project_id = None - - def __repr__(self): - return 'Vpn:%s:%s' % (self.project_id, self.instance_id) - - def startElement(self, name, attrs, connection): - return None - - def endElement(self, name, value, connection): - fixed_name = string.lower(re.sub(r'([A-Z])', r'_\1', name)) - setattr(self, fixed_name, value) - - -class InstanceType(object): - """ - Information about a Nova instance type, as parsed through SAX. - - **Fields include** - - * name - * vcpus - * disk_gb - * memory_mb - * flavor_id - - """ - - def __init__(self, connection=None): - self.connection = connection - self.name = None - self.vcpus = None - self.disk_gb = None - self.memory_mb = None - self.flavor_id = None - - def __repr__(self): - return 'InstanceType:%s' % self.name - - def startElement(self, name, attrs, connection): - return None - - def endElement(self, name, value, connection): - if name == "memoryMb": - self.memory_mb = str(value) - elif name == "flavorId": - self.flavor_id = str(value) - elif name == "diskGb": - self.disk_gb = str(value) - else: - setattr(self, name, str(value)) - - -class NovaAdminClient(object): - - def __init__( - self, - clc_url=DEFAULT_CLC_URL, - region=DEFAULT_REGION, - access_key=None, - secret_key=None, - **kwargs): - parts = self.split_clc_url(clc_url) - - self.clc_url = clc_url - self.region = region - self.access = access_key - self.secret = secret_key - self.apiconn = boto.connect_ec2(aws_access_key_id=access_key, - aws_secret_access_key=secret_key, - is_secure=parts['is_secure'], - region=RegionInfo(None, - region, - parts['ip']), - port=parts['port'], - path='/services/Admin', - **kwargs) - self.apiconn.APIVersion = 'nova' - - def connection_for(self, username, project, clc_url=None, region=None, - **kwargs): - """Returns a boto ec2 connection for the given username.""" - if not clc_url: - clc_url = self.clc_url - if not region: - region = self.region - parts = self.split_clc_url(clc_url) - user = self.get_user(username) - access_key = '%s:%s' % (user.accesskey, project) - return boto.connect_ec2(aws_access_key_id=access_key, - aws_secret_access_key=user.secretkey, - is_secure=parts['is_secure'], - region=RegionInfo(None, - self.region, - parts['ip']), - port=parts['port'], - path='/services/Cloud', - **kwargs) - - def split_clc_url(self, clc_url): - """Splits a cloud controller endpoint url.""" - parts = httplib.urlsplit(clc_url) - is_secure = parts.scheme == 'https' - ip, port = parts.netloc.split(':') - return {'ip': ip, 'port': int(port), 'is_secure': is_secure} - - def get_users(self): - """Grabs the list of all users.""" - return self.apiconn.get_list('DescribeUsers', {}, [('item', UserInfo)]) - - def get_user(self, name): - """Grab a single user by name.""" - user = self.apiconn.get_object('DescribeUser', - {'Name': name}, - UserInfo) - if user.username != None: - return user - - def has_user(self, username): - """Determine if user exists.""" - return self.get_user(username) != None - - def create_user(self, username): - """Creates a new user, returning the userinfo object with - access/secret.""" - return self.apiconn.get_object('RegisterUser', {'Name': username}, - UserInfo) - - def delete_user(self, username): - """Deletes a user.""" - return self.apiconn.get_object('DeregisterUser', {'Name': username}, - UserInfo) - - def get_roles(self, project_roles=True): - """Returns a list of available roles.""" - return self.apiconn.get_list('DescribeRoles', - {'ProjectRoles': project_roles}, - [('item', UserRole)]) - - def get_user_roles(self, user, project=None): - """Returns a list of roles for the given user. - - Omitting project will return any global roles that the user has. - Specifying project will return only project specific roles. - - """ - params = {'User': user} - if project: - params['Project'] = project - return self.apiconn.get_list('DescribeUserRoles', - params, - [('item', UserRole)]) - - def add_user_role(self, user, role, project=None): - """Add a role to a user either globally or for a specific project.""" - return self.modify_user_role(user, role, project=project, - operation='add') - - def remove_user_role(self, user, role, project=None): - """Remove a role from a user either globally or for a specific - project.""" - return self.modify_user_role(user, role, project=project, - operation='remove') - - def modify_user_role(self, user, role, project=None, operation='add', - **kwargs): - """Add or remove a role for a user and project.""" - params = {'User': user, - 'Role': role, - 'Project': project, - 'Operation': operation} - return self.apiconn.get_status('ModifyUserRole', params) - - def get_projects(self, user=None): - """Returns a list of all projects.""" - if user: - params = {'User': user} - else: - params = {} - return self.apiconn.get_list('DescribeProjects', - params, - [('item', ProjectInfo)]) - - def get_project(self, name): - """Returns a single project with the specified name.""" - project = self.apiconn.get_object('DescribeProject', - {'Name': name}, - ProjectInfo) - - if project.projectname != None: - return project - - def create_project(self, projectname, manager_user, description=None, - member_users=None): - """Creates a new project.""" - params = {'Name': projectname, - 'ManagerUser': manager_user, - 'Description': description, - 'MemberUsers': member_users} - return self.apiconn.get_object('RegisterProject', params, ProjectInfo) - - def modify_project(self, projectname, manager_user=None, description=None): - """Modifies an existing project.""" - params = {'Name': projectname, - 'ManagerUser': manager_user, - 'Description': description} - return self.apiconn.get_status('ModifyProject', params) - - def delete_project(self, projectname): - """Permanently deletes the specified project.""" - return self.apiconn.get_object('DeregisterProject', - {'Name': projectname}, - ProjectInfo) - - def get_project_members(self, name): - """Returns a list of members of a project.""" - return self.apiconn.get_list('DescribeProjectMembers', - {'Name': name}, - [('item', ProjectMember)]) - - def add_project_member(self, user, project): - """Adds a user to a project.""" - return self.modify_project_member(user, project, operation='add') - - def remove_project_member(self, user, project): - """Removes a user from a project.""" - return self.modify_project_member(user, project, operation='remove') - - def modify_project_member(self, user, project, operation='add'): - """Adds or removes a user from a project.""" - params = {'User': user, - 'Project': project, - 'Operation': operation} - return self.apiconn.get_status('ModifyProjectMember', params) - - def get_zip(self, user, project): - """Returns the content of a zip file containing novarc and access - credentials.""" - params = {'Name': user, 'Project': project} - zip = self.apiconn.get_object('GenerateX509ForUser', params, UserInfo) - return zip.file - - def start_vpn(self, project): - """ - Starts the vpn for a user - """ - return self.apiconn.get_object('StartVpn', {'Project': project}, Vpn) - - def get_vpns(self): - """Return a list of vpn with project name""" - return self.apiconn.get_list('DescribeVpns', {}, [('item', Vpn)]) - - def get_hosts(self): - return self.apiconn.get_list('DescribeHosts', {}, [('item', HostInfo)]) - - def get_instance_types(self): - """Grabs the list of all users.""" - return self.apiconn.get_list('DescribeInstanceTypes', {}, - [('item', InstanceType)]) diff --git a/smoketests/test_admin.py b/smoketests/test_admin.py index 46e5b2233..1b7a8d673 100644 --- a/smoketests/test_admin.py +++ b/smoketests/test_admin.py @@ -30,7 +30,6 @@ possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), if os.path.exists(os.path.join(possible_topdir, 'nova', '__init__.py')): sys.path.insert(0, possible_topdir) -from nova import adminclient from smoketests import flags from smoketests import base @@ -47,6 +46,7 @@ TEST_PROJECTNAME = '%sproject' % TEST_PREFIX class AdminSmokeTestCase(base.SmokeTestCase): def setUp(self): + import nova_adminclient as adminclient self.admin = adminclient.NovaAdminClient( access_key=os.getenv('EC2_ACCESS_KEY'), secret_key=os.getenv('EC2_SECRET_KEY'), diff --git a/tools/pip-requires b/tools/pip-requires index 4ab9644d8..6ea446493 100644 --- a/tools/pip-requires +++ b/tools/pip-requires @@ -30,4 +30,5 @@ sqlalchemy-migrate netaddr sphinx glance +nova-adminclient suds==0.4 -- cgit From b39a0eabd507f804300c1741b768cf3c2584393d Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Thu, 31 Mar 2011 09:01:01 -0700 Subject: need to support python2.4, so can't use uuid module --- plugins/xenserver/xenapi/etc/xapi.d/plugins/agent | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent b/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent index 5c5a6d645..5496a6bd5 100755 --- a/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent +++ b/plugins/xenserver/xenapi/etc/xapi.d/plugins/agent @@ -23,6 +23,7 @@ # import base64 +import commands try: import json except ImportError: @@ -32,7 +33,6 @@ import random import subprocess import tempfile import time -import uuid import XenAPIPlugin @@ -158,7 +158,7 @@ def _agent_has_method(self, method): self._agent_methods = [] if not self._agent_methods: # Haven't been defined - tmp_id = str(uuid.uuid4()) + tmp_id = commands.getoutput("uuidgen") dct = {} dct["value"] = json.dumps({"name": "features", "value": ""}) dct["path"] = "data/host/%s" % tmp_id -- cgit From 45bb2fb1f74c21e9ef8b65f6c4e22965e2c94fbd Mon Sep 17 00:00:00 2001 From: Josh Kearney Date: Thu, 31 Mar 2011 13:08:49 -0500 Subject: More friendly error message --- nova/scheduler/chance.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/nova/scheduler/chance.py b/nova/scheduler/chance.py index 9deaa2777..ae81679e1 100644 --- a/nova/scheduler/chance.py +++ b/nova/scheduler/chance.py @@ -34,5 +34,7 @@ class ChanceScheduler(driver.Scheduler): hosts = self.hosts_up(context, topic) if not hosts: - raise driver.NoValidHost(_("No hosts found")) + raise driver.NoValidHost(_("Scheduler was unable to locate a host" + " for this request. Is the compute node" + " running?")) return hosts[int(random.random() * len(hosts))] -- cgit From 62b52833cc28d203c648585feceb1de3be9eed25 Mon Sep 17 00:00:00 2001 From: Josh Kearney Date: Thu, 31 Mar 2011 14:29:16 -0500 Subject: Review feedback --- nova/scheduler/chance.py | 4 ++-- nova/scheduler/simple.py | 12 +++++++++--- nova/scheduler/zone.py | 5 ++++- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/nova/scheduler/chance.py b/nova/scheduler/chance.py index ae81679e1..f4461cee2 100644 --- a/nova/scheduler/chance.py +++ b/nova/scheduler/chance.py @@ -35,6 +35,6 @@ class ChanceScheduler(driver.Scheduler): hosts = self.hosts_up(context, topic) if not hosts: raise driver.NoValidHost(_("Scheduler was unable to locate a host" - " for this request. Is the compute node" - " running?")) + " for this request. Is the appropriate" + " service running?")) return hosts[int(random.random() * len(hosts))] diff --git a/nova/scheduler/simple.py b/nova/scheduler/simple.py index 0191ceb3d..dd568d2c6 100644 --- a/nova/scheduler/simple.py +++ b/nova/scheduler/simple.py @@ -72,7 +72,9 @@ class SimpleScheduler(chance.ChanceScheduler): {'host': service['host'], 'scheduled_at': now}) return service['host'] - raise driver.NoValidHost(_("No hosts found")) + raise driver.NoValidHost(_("Scheduler was unable to locate a host" + " for this request. Is the appropriate" + " service running?")) def schedule_create_volume(self, context, volume_id, *_args, **_kwargs): """Picks a host that is up and has the fewest volumes.""" @@ -107,7 +109,9 @@ class SimpleScheduler(chance.ChanceScheduler): {'host': service['host'], 'scheduled_at': now}) return service['host'] - raise driver.NoValidHost(_("No hosts found")) + raise driver.NoValidHost(_("Scheduler was unable to locate a host" + " for this request. Is the appropriate" + " service running?")) def schedule_set_network_host(self, context, *_args, **_kwargs): """Picks a host that is up and has the fewest networks.""" @@ -119,4 +123,6 @@ class SimpleScheduler(chance.ChanceScheduler): raise driver.NoValidHost(_("All hosts have too many networks")) if self.service_is_up(service): return service['host'] - raise driver.NoValidHost(_("No hosts found")) + raise driver.NoValidHost(_("Scheduler was unable to locate a host" + " for this request. Is the appropriate" + " service running?")) diff --git a/nova/scheduler/zone.py b/nova/scheduler/zone.py index 49786cd32..44d5a166f 100644 --- a/nova/scheduler/zone.py +++ b/nova/scheduler/zone.py @@ -52,5 +52,8 @@ class ZoneScheduler(driver.Scheduler): zone = _kwargs.get('availability_zone') hosts = self.hosts_up_with_zone(context, topic, zone) if not hosts: - raise driver.NoValidHost(_("No hosts found")) + raise driver.NoValidHost(_("Scheduler was unable to locate a host" + " for this request. Is the appropriate" + " service running?")) + return hosts[int(random.random() * len(hosts))] -- cgit From 82224b6681750819a4ee0d8b081823863cb0523c Mon Sep 17 00:00:00 2001 From: Sandy Walsh Date: Thu, 31 Mar 2011 12:31:35 -0700 Subject: removes excessive logging on rabbitmq failure --- nova/rpc.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/nova/rpc.py b/nova/rpc.py index be7cb3f37..b610cdf9b 100644 --- a/nova/rpc.py +++ b/nova/rpc.py @@ -134,8 +134,6 @@ class Consumer(messaging.Consumer): if not self.failed_connection: LOG.exception(_("Failed to fetch message from queue: %s" % e)) self.failed_connection = True - else: - LOG.exception(_("Unhandled exception %s" % e)) def attach_to_eventlet(self): """Only needed for unit tests!""" -- cgit From 032acaab1fd9a3823e203ddaf9c50857acd25ac7 Mon Sep 17 00:00:00 2001 From: Josh Kearney Date: Thu, 31 Mar 2011 15:32:31 -0500 Subject: Don't include first 4 chars of instance name in adminPass --- nova/api/openstack/servers.py | 3 +-- nova/tests/api/openstack/test_servers.py | 6 ++---- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index f7696d918..d47ea5788 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -180,8 +180,7 @@ class Controller(wsgi.Controller): builder = self._get_view_builder(req) server = builder.build(inst, is_detail=True) - password = "%s%s" % (server['server']['name'][:4], - utils.generate_password(12)) + password = utils.generate_password(16) server['server']['adminPass'] = password self.compute_api.set_admin_password(context, server['server']['id'], password) diff --git a/nova/tests/api/openstack/test_servers.py b/nova/tests/api/openstack/test_servers.py index 130b8c5d5..5fbc9837b 100644 --- a/nova/tests/api/openstack/test_servers.py +++ b/nova/tests/api/openstack/test_servers.py @@ -377,7 +377,6 @@ class ServersTest(test.TestCase): res = req.get_response(fakes.wsgi_app()) server = json.loads(res.body)['server'] - self.assertEqual('serv', server['adminPass'][:4]) self.assertEqual(16, len(server['adminPass'])) self.assertEqual('server_test', server['name']) self.assertEqual(1, server['id']) @@ -486,7 +485,6 @@ class ServersTest(test.TestCase): res = req.get_response(fakes.wsgi_app()) server = json.loads(res.body)['server'] - self.assertEqual('serv', server['adminPass'][:4]) self.assertEqual(16, len(server['adminPass'])) self.assertEqual('server_test', server['name']) self.assertEqual(1, server['id']) @@ -1426,7 +1424,7 @@ class TestServerInstanceCreation(test.TestCase): self.assertEquals(response.status_int, 200) response = json.loads(response.body) self.assertTrue('adminPass' in response['server']) - self.assertTrue(response['server']['adminPass'].startswith('fake')) + self.assertEqual(16, len(response['server']['adminPass'])) def test_create_instance_admin_pass_xml(self): request, response, dummy = \ @@ -1435,7 +1433,7 @@ class TestServerInstanceCreation(test.TestCase): dom = minidom.parseString(response.body) server = dom.childNodes[0] self.assertEquals(server.nodeName, 'server') - self.assertTrue(server.getAttribute('adminPass').startswith('fake')) + self.assertEqual(16, len(server.getAttribute('adminPass'))) class TestGetKernelRamdiskFromImage(test.TestCase): -- cgit From 5d71e187dc6eddab19ecdc0feb97e41263e09a84 Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Thu, 31 Mar 2011 17:19:59 -0400 Subject: Hopefully absolved us of the suds issue? --- nova/virt/vmwareapi/vim.py | 47 ++++++++++++++++++++++------------------------ 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/nova/virt/vmwareapi/vim.py b/nova/virt/vmwareapi/vim.py index 1c850595d..159e16a80 100644 --- a/nova/virt/vmwareapi/vim.py +++ b/nova/virt/vmwareapi/vim.py @@ -22,13 +22,9 @@ Classes for making VMware VI SOAP calls. import httplib try: - suds = True - from suds import WebFault - from suds.client import Client - from suds.plugin import MessagePlugin - from suds.sudsobject import Property + import suds except ImportError: - suds = False + suds = None from nova import flags from nova.virt.vmwareapi import error_util @@ -46,24 +42,25 @@ flags.DEFINE_string('vmwareapi_wsdl_loc', 'Refer readme-vmware to setup') -class VIMMessagePlugin(MessagePlugin): +if suds: + class VIMMessagePlugin(suds.plugin.MessagePlugin): - def addAttributeForValue(self, node): - # suds does not handle AnyType properly. - # VI SDK requires type attribute to be set when AnyType is used - if node.name == 'value': - node.set('xsi:type', 'xsd:string') + def addAttributeForValue(self, node): + # suds does not handle AnyType properly. + # VI SDK requires type attribute to be set when AnyType is used + if node.name == 'value': + node.set('xsi:type', 'xsd:string') - def marshalled(self, context): - """suds will send the specified soap envelope. - Provides the plugin with the opportunity to prune empty - nodes and fixup nodes before sending it to the server. - """ - # suds builds the entire request object based on the wsdl schema. - # VI SDK throws server errors if optional SOAP nodes are sent without - # values, e.g. as opposed to test - context.envelope.prune() - context.envelope.walk(self.addAttributeForValue) + def marshalled(self, context): + """suds will send the specified soap envelope. + Provides the plugin with the opportunity to prune empty + nodes and fixup nodes before sending it to the server. + """ + # suds builds the entire request object based on the wsdl schema. + # VI SDK throws server errors if optional SOAP nodes are sent + # without values, e.g. as opposed to test + context.envelope.prune() + context.envelope.walk(self.addAttributeForValue) class Vim: @@ -91,7 +88,7 @@ class Vim: #wsdl_url = '%s://%s/sdk/vimService.wsdl' % (self._protocol, # self._host_name) url = '%s://%s/sdk' % (self._protocol, self._host_name) - self.client = Client(wsdl_url, location=url, + self.client = suds.client.Client(wsdl_url, location=url, plugins=[VIMMessagePlugin()]) self._service_content = \ self.RetrieveServiceContent("ServiceInstance") @@ -134,7 +131,7 @@ class Vim: # check of the SOAP response except error_util.VimFaultException, excep: raise - except WebFault, excep: + except suds.WebFault, excep: doc = excep.document detail = doc.childAtPath("/Envelope/Body/Fault/detail") fault_list = [] @@ -170,7 +167,7 @@ class Vim: """Builds the request managed object.""" # Request Managed Object Builder if type(managed_object) == type(""): - mo = Property(managed_object) + mo = suds.sudsobject.Property(managed_object) mo._type = managed_object else: mo = managed_object -- cgit From b56c406429e4748f52ba8215beb4076165c6640d Mon Sep 17 00:00:00 2001 From: Soren Hansen Date: Fri, 1 Apr 2011 11:23:05 +0200 Subject: Make euca-get-ajax-console work with Euca2ools 1.3 --- tools/euca-get-ajax-console | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/euca-get-ajax-console b/tools/euca-get-ajax-console index 3df3dcb53..c76d4f39c 100755 --- a/tools/euca-get-ajax-console +++ b/tools/euca-get-ajax-console @@ -93,8 +93,13 @@ def override_connect_ec2(aws_access_key_id=None, aws_secret_access_key, **kwargs) # override boto's connect_ec2 method, so that we can use NovaEC2Connection +# (This is for Euca2ools 1.2) boto.connect_ec2 = override_connect_ec2 +# Override Euca2ools' EC2Connection class (which it gets from boto) +# (This is for Euca2ools 1.3) +euca2ools.EC2Connection = NovaEC2Connection + def usage(status=1): print usage_string -- cgit From 0865cc59c1a525d21937224b7ff1ff61ce43f4b1 Mon Sep 17 00:00:00 2001 From: Soren Hansen Date: Fri, 1 Apr 2011 17:10:06 +0200 Subject: Add euca2ools import --- tools/euca-get-ajax-console | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/euca-get-ajax-console b/tools/euca-get-ajax-console index c76d4f39c..a67c79d90 100755 --- a/tools/euca-get-ajax-console +++ b/tools/euca-get-ajax-console @@ -35,6 +35,7 @@ if os.path.exists(os.path.join(possible_topdir, 'nova', '__init__.py')): import boto import nova from boto.ec2.connection import EC2Connection +import euca2ools from euca2ools import Euca2ool, InstanceValidationError, Util usage_string = """ -- cgit From 007992e57c064c90e6a09f8dac070d3b56dc72a0 Mon Sep 17 00:00:00 2001 From: Masanori Itoh Date: Sat, 2 Apr 2011 00:28:32 +0900 Subject: Added updated_at field to update statement according to Jay's comment. --- nova/db/sqlalchemy/api.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/nova/db/sqlalchemy/api.py b/nova/db/sqlalchemy/api.py index 08eb0b7b2..6da8dac10 100644 --- a/nova/db/sqlalchemy/api.py +++ b/nova/db/sqlalchemy/api.py @@ -660,7 +660,9 @@ def fixed_ip_disassociate_all_by_timeout(_context, host, time): filter(models.FixedIp.instance_id != None).\ filter_by(allocated=0).\ update({'instance_id': None, - 'leased': 0}, synchronize_session='fetch') + 'leased': 0, + 'updated_at': datetime.datetime.utcnow()}, + synchronize_session='fetch') return result -- cgit From d98c61d21f3a60e3368cc723fc6764c66b8176b4 Mon Sep 17 00:00:00 2001 From: Masanori Itoh Date: Sat, 2 Apr 2011 01:05:50 +0900 Subject: Add checking if the floating_ip is allocated or not before appending to result array. --- nova/api/ec2/cloud.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/nova/api/ec2/cloud.py b/nova/api/ec2/cloud.py index 7ba8dfbea..a6bdab808 100644 --- a/nova/api/ec2/cloud.py +++ b/nova/api/ec2/cloud.py @@ -757,19 +757,20 @@ class CloudController(object): iterator = db.floating_ip_get_all_by_project(context, context.project_id) for floating_ip_ref in iterator: - address = floating_ip_ref['address'] - ec2_id = None - if (floating_ip_ref['fixed_ip'] - and floating_ip_ref['fixed_ip']['instance']): - instance_id = floating_ip_ref['fixed_ip']['instance']['id'] - ec2_id = ec2utils.id_to_ec2_id(instance_id) - address_rv = {'public_ip': address, - 'instance_id': ec2_id} - if context.is_admin: - details = "%s (%s)" % (address_rv['instance_id'], - floating_ip_ref['project_id']) - address_rv['instance_id'] = details - addresses.append(address_rv) + if floating_ip_ref['project_id'] is not None: + address = floating_ip_ref['address'] + ec2_id = None + if (floating_ip_ref['fixed_ip'] + and floating_ip_ref['fixed_ip']['instance']): + instance_id = floating_ip_ref['fixed_ip']['instance']['id'] + ec2_id = ec2utils.id_to_ec2_id(instance_id) + address_rv = {'public_ip': address, + 'instance_id': ec2_id} + if context.is_admin: + details = "%s (%s)" % (address_rv['instance_id'], + floating_ip_ref['project_id']) + address_rv['instance_id'] = details + addresses.append(address_rv) return {'addressesSet': addresses} def allocate_address(self, context, **kwargs): -- cgit From ec3b3d6ae97cddce490c2cbeed2f8f9241704ed1 Mon Sep 17 00:00:00 2001 From: Masanori Itoh Date: Sat, 2 Apr 2011 01:44:12 +0900 Subject: Made the fix simpler. --- nova/api/ec2/cloud.py | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/nova/api/ec2/cloud.py b/nova/api/ec2/cloud.py index a6bdab808..425784e8a 100644 --- a/nova/api/ec2/cloud.py +++ b/nova/api/ec2/cloud.py @@ -757,20 +757,21 @@ class CloudController(object): iterator = db.floating_ip_get_all_by_project(context, context.project_id) for floating_ip_ref in iterator: - if floating_ip_ref['project_id'] is not None: - address = floating_ip_ref['address'] - ec2_id = None - if (floating_ip_ref['fixed_ip'] - and floating_ip_ref['fixed_ip']['instance']): - instance_id = floating_ip_ref['fixed_ip']['instance']['id'] - ec2_id = ec2utils.id_to_ec2_id(instance_id) - address_rv = {'public_ip': address, - 'instance_id': ec2_id} - if context.is_admin: - details = "%s (%s)" % (address_rv['instance_id'], - floating_ip_ref['project_id']) - address_rv['instance_id'] = details - addresses.append(address_rv) + if floating_ip_ref['project_id'] is None: + continue + address = floating_ip_ref['address'] + ec2_id = None + if (floating_ip_ref['fixed_ip'] + and floating_ip_ref['fixed_ip']['instance']): + instance_id = floating_ip_ref['fixed_ip']['instance']['id'] + ec2_id = ec2utils.id_to_ec2_id(instance_id) + address_rv = {'public_ip': address, + 'instance_id': ec2_id} + if context.is_admin: + details = "%s (%s)" % (address_rv['instance_id'], + floating_ip_ref['project_id']) + address_rv['instance_id'] = details + addresses.append(address_rv) return {'addressesSet': addresses} def allocate_address(self, context, **kwargs): -- cgit -- cgit From ec30c42b3b4532743c8353c5e9fa04ae00803db3 Mon Sep 17 00:00:00 2001 From: Ilya Alekseyev Date: Mon, 4 Apr 2011 18:31:35 +0400 Subject: network injection check fixed --- nova/virt/libvirt_conn.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/virt/libvirt_conn.py b/nova/virt/libvirt_conn.py index f34ea7225..c952f6f47 100644 --- a/nova/virt/libvirt_conn.py +++ b/nova/virt/libvirt_conn.py @@ -842,7 +842,7 @@ class LibvirtConnection(driver.ComputeDriver): for (network_ref, mapping) in network_info: ifc_num += 1 - if not 'injected' in network_ref: + if not network_ref.injected: continue have_injected_networks = True -- cgit From bd64c4f6bebb50528b87bf6e3f64d7d1cba053df Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Mon, 4 Apr 2011 10:59:44 -0400 Subject: Fixes error which occurs when no name is specified for an image. --- nova/api/openstack/views/images.py | 2 +- nova/tests/api/openstack/test_images.py | 57 +++++++++++++++++++++++++++++++-- 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/nova/api/openstack/views/images.py b/nova/api/openstack/views/images.py index 3807fa95f..d8578ebdd 100644 --- a/nova/api/openstack/views/images.py +++ b/nova/api/openstack/views/images.py @@ -61,7 +61,7 @@ class ViewBuilder(object): image = { "id": image_obj["id"], - "name": image_obj["name"], + "name": image_obj.get("name"), } if "instance_id" in properties: diff --git a/nova/tests/api/openstack/test_images.py b/nova/tests/api/openstack/test_images.py index 57e447dce..69cc3116d 100644 --- a/nova/tests/api/openstack/test_images.py +++ b/nova/tests/api/openstack/test_images.py @@ -263,7 +263,8 @@ class ImageControllerWithGlanceServiceTest(test.TestCase): {'id': 124, 'name': 'queued backup'}, {'id': 125, 'name': 'saving backup'}, {'id': 126, 'name': 'active backup'}, - {'id': 127, 'name': 'killed backup'}] + {'id': 127, 'name': 'killed backup'}, + {'id': 129, 'name': None}] self.assertDictListMatch(response_list, expected) @@ -339,6 +340,24 @@ class ImageControllerWithGlanceServiceTest(test.TestCase): self.assertEqual(expected_image.toxml(), actual_image.toxml()) + def test_get_image_xml_no_name(self): + request = webob.Request.blank('/v1.0/images/129') + request.accept = "application/xml" + response = request.get_response(fakes.wsgi_app()) + + actual_image = minidom.parseString(response.body.replace(" ", "")) + + expected_now = self.NOW_API_FORMAT + expected_image = minidom.parseString(""" + + """ % (locals())) + + self.assertEqual(expected_image.toxml(), actual_image.toxml()) + def test_get_image_v1_1_xml(self): request = webob.Request.blank('/v1.1/images/123') request.accept = "application/xml" @@ -516,6 +535,13 @@ class ImageControllerWithGlanceServiceTest(test.TestCase): 'updated': self.NOW_API_FORMAT, 'created': self.NOW_API_FORMAT, 'status': 'FAILED', + }, + { + 'id': 129, + 'name': None, + 'updated': self.NOW_API_FORMAT, + 'created': self.NOW_API_FORMAT, + 'status': 'ACTIVE', }] self.assertDictListMatch(expected, response_list) @@ -635,7 +661,29 @@ class ImageControllerWithGlanceServiceTest(test.TestCase): "type": "application/xml", "href": "http://localhost/v1.1/images/127", }], - }] + }, + { + 'id': 129, + 'name': None, + 'updated': self.NOW_API_FORMAT, + 'created': self.NOW_API_FORMAT, + 'status': 'ACTIVE', + "links": [{ + "rel": "self", + "href": "http://localhost/v1.1/images/129", + }, + { + "rel": "bookmark", + "type": "application/json", + "href": "http://localhost/v1.1/images/129", + }, + { + "rel": "bookmark", + "type": "application/xml", + "href": "http://localhost/v1.1/images/129", + }], + }, + ] self.assertDictListMatch(expected, response_list) @@ -694,4 +742,9 @@ class ImageControllerWithGlanceServiceTest(test.TestCase): status='active', properties=other_backup_properties) image_id += 1 + # Image without a name + add_fixture(id=image_id, is_public=True, status='active', + properties={}) + image_id += 1 + return fixtures -- cgit From 59d46ada05f47bf477427b932a47c1cf1d91811e Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Mon, 4 Apr 2011 11:19:20 -0400 Subject: Ensure no errors for improper responses from image service. --- nova/api/openstack/views/images.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nova/api/openstack/views/images.py b/nova/api/openstack/views/images.py index d8578ebdd..16195b050 100644 --- a/nova/api/openstack/views/images.py +++ b/nova/api/openstack/views/images.py @@ -60,7 +60,7 @@ class ViewBuilder(object): self._format_status(image_obj) image = { - "id": image_obj["id"], + "id": image_obj.get("id"), "name": image_obj.get("name"), } @@ -72,9 +72,9 @@ class ViewBuilder(object): if detail: image.update({ - "created": image_obj["created_at"], - "updated": image_obj["updated_at"], - "status": image_obj["status"], + "created": image_obj.get("created_at"), + "updated": image_obj.get("updated_at"), + "status": image_obj.get("status"), }) if image["status"] == "SAVING": -- cgit From fc53de592fb903f8a7e3741fa98d03140aca9066 Mon Sep 17 00:00:00 2001 From: Ken Pepple Date: Mon, 4 Apr 2011 09:45:26 -0700 Subject: corrected capitalization of openstack api status and added tests --- nova/api/openstack/views/servers.py | 24 ++++++++++++------------ nova/tests/api/openstack/test_servers.py | 2 ++ 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/nova/api/openstack/views/servers.py b/nova/api/openstack/views/servers.py index 6b471a0f4..d24c025be 100644 --- a/nova/api/openstack/views/servers.py +++ b/nova/api/openstack/views/servers.py @@ -57,27 +57,27 @@ class ViewBuilder(object): def _build_detail(self, inst): """Returns a detailed model of a server.""" power_mapping = { - None: 'build', - power_state.NOSTATE: 'build', - power_state.RUNNING: 'active', - power_state.BLOCKED: 'active', - power_state.SUSPENDED: 'suspended', - power_state.PAUSED: 'paused', - power_state.SHUTDOWN: 'active', - power_state.SHUTOFF: 'active', - power_state.CRASHED: 'error', - power_state.FAILED: 'error'} + None: 'BUILD', + power_state.NOSTATE: 'BUILD', + power_state.RUNNING: 'ACTIVE', + power_state.BLOCKED: 'ACTIVE', + power_state.SUSPENDED: 'SUSPENDED', + power_state.PAUSED: 'PAUSED', + power_state.SHUTDOWN: 'ACTIVE', + power_state.SHUTOFF: 'ACTIVE', + power_state.CRASHED: 'ERROR', + power_state.FAILED: 'ERROR'} inst_dict = { 'id': int(inst['id']), 'name': inst['display_name'], 'addresses': self.addresses_builder.build(inst), - 'status': power_mapping[inst.get('state')].upper()} + 'status': power_mapping[inst.get('state')]} ctxt = nova.context.get_admin_context() compute_api = nova.compute.API() if compute_api.has_finished_migration(ctxt, inst['id']): - inst_dict['status'] = 'resize-confirm'.upper() + inst_dict['status'] = 'RESIZE-CONFIRM' # Return the metadata as a dictionary metadata = {} diff --git a/nova/tests/api/openstack/test_servers.py b/nova/tests/api/openstack/test_servers.py index d32e8eea8..cf55c8383 100644 --- a/nova/tests/api/openstack/test_servers.py +++ b/nova/tests/api/openstack/test_servers.py @@ -631,6 +631,7 @@ class ServersTest(test.TestCase): self.assertEqual(s['name'], 'server%d' % i) self.assertEqual(s['imageId'], '10') self.assertEqual(s['flavorId'], '1') + self.assertEqual(s['status'], 'BUILD') self.assertEqual(s['metadata']['seq'], i) def test_get_all_server_details_v1_1(self): @@ -644,6 +645,7 @@ class ServersTest(test.TestCase): self.assertEqual(s['name'], 'server%d' % i) self.assertEqual(s['imageRef'], 'http://localhost/v1.1/images/10') self.assertEqual(s['flavorRef'], 'http://localhost/v1.1/flavors/1') + self.assertEqual(s['status'], 'BUILD') self.assertEqual(s['metadata']['seq'], i) def test_get_all_server_details_with_host(self): -- cgit From 350aaa819c8f97e0bcbd9e4d0f6f0da41784b630 Mon Sep 17 00:00:00 2001 From: Ilya Alekseyev Date: Mon, 4 Apr 2011 22:39:39 +0400 Subject: working with network_ref like with mapping --- nova/virt/libvirt_conn.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/virt/libvirt_conn.py b/nova/virt/libvirt_conn.py index c952f6f47..babbc610d 100644 --- a/nova/virt/libvirt_conn.py +++ b/nova/virt/libvirt_conn.py @@ -842,7 +842,7 @@ class LibvirtConnection(driver.ComputeDriver): for (network_ref, mapping) in network_info: ifc_num += 1 - if not network_ref.injected: + if not network_ref['injected']: continue have_injected_networks = True -- cgit