From 40a9488b4b96fa809bd18f4a06018186a488507a Mon Sep 17 00:00:00 2001 From: Ilya Alekseyev Date: Thu, 14 Jul 2011 22:34:49 +0400 Subject: added commands --- bin/nova-manage | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/bin/nova-manage b/bin/nova-manage index 7dfe91698..5a934b613 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -518,6 +518,27 @@ class FixedIpCommands(object): fixed_ip['address'], mac_address, hostname, host) + def reserve(self, address): + """Mark fixed ip as reserved + arguments: address""" + self._set_reserved(address, True) + + def waste(self, address): + """Mark fixed ip as free to use + arguments: address""" + self._set_reserved(address, False) + + def _set_reserved(self, address, reserved): + ctxt = context.get_admin_context() + + try: + fixed_ip = db.fixed_ip_get_by_address(ctxt, address) + db.fixed_ip_update(ctxt, fixed_ip['address'], + {'reserved': reserved}) + except exception.NotFound as ex: + print "error: %s" % ex + sys.exit(2) + class FloatingIpCommands(object): """Class for managing floating ip.""" -- cgit From 883095f1e69d70173339ccba64f2b2a8a1d48a5f Mon Sep 17 00:00:00 2001 From: Justin Shepherd Date: Mon, 1 Aug 2011 20:45:30 -0500 Subject: Added @test.skip_unless and @test.skip_if functionality. Also created nova/tests/test_skip_examples.py to show the skip cases usage. --- nova/test.py | 31 +++++++++++++++++++++++++++++++ nova/tests/test_skip_examples.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 nova/tests/test_skip_examples.py diff --git a/nova/test.py b/nova/test.py index 549aa6fcf..afc118100 100644 --- a/nova/test.py +++ b/nova/test.py @@ -67,6 +67,37 @@ class skip_test(object): _skipper.__doc__ = func.__doc__ return _skipper +class skip_if(object): + """Decorator that skips a test if contition is true.""" + def __init__(self, condition, msg): + self.condition = condition + self.message = msg + + def __call__(self, func): + def _skipper(*args, **kw): + """Wrapped skipper function.""" + if self.condition: + raise nose.SkipTest(self.message) + _skipper.__name__ = func.__name__ + _skipper.__doc__ = func.__doc__ + return _skipper + + +class skip_unless(object): + """Decorator that skips a test if condition is false.""" + def __init__(self, condition, msg): + self.condition = condition + self.message = msg + + def __call__(self, func): + def _skipper(*args, **kw): + """Wrapped skipper function.""" + if not self.condition: + raise nose.SkipTest(self.message) + _skipper.__name__ = func.__name__ + _skipper.__doc__ = func.__doc__ + return _skipper + def skip_if_fake(func): """Decorator that skips a test if running in fake mode.""" diff --git a/nova/tests/test_skip_examples.py b/nova/tests/test_skip_examples.py new file mode 100644 index 000000000..dfbaac74b --- /dev/null +++ b/nova/tests/test_skip_examples.py @@ -0,0 +1,37 @@ +# 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. + +import os + +from nova import test + + +class ExampleSkipTestCase(test.TestCase): + @test.skip_test("testing skipping") + def test_skip_test(self): + x = 1 + + @test.skip_if(os.getenv("USER"), + "Skiping -- Environment variable USER exists") + def test_skip_if_env_user_exists(self): + x = 1 + + @test.skip_unless(os.getenv("BLAH"), + "Skipping -- Environment variable BLAH does not exist") + def test_skip_unless_env_blah_exists(self): + x = 1 -- cgit From 44964f41ed591c8ece72dbc36f5d668d2e279274 Mon Sep 17 00:00:00 2001 From: Justin Shepherd Date: Tue, 2 Aug 2011 22:22:34 -0500 Subject: renaming test_skip_unless_env_foo_exists() --- nova/tests/test_skip_examples.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nova/tests/test_skip_examples.py b/nova/tests/test_skip_examples.py index dfbaac74b..b7979d34b 100644 --- a/nova/tests/test_skip_examples.py +++ b/nova/tests/test_skip_examples.py @@ -31,7 +31,7 @@ class ExampleSkipTestCase(test.TestCase): def test_skip_if_env_user_exists(self): x = 1 - @test.skip_unless(os.getenv("BLAH"), - "Skipping -- Environment variable BLAH does not exist") - def test_skip_unless_env_blah_exists(self): + @test.skip_unless(os.getenv("FOO"), + "Skipping -- Environment variable FOO does not exist") + def test_skip_unless_env_foo_exists(self): x = 1 -- cgit From 836c394def93a8589bcb7387862390b24b8fdab8 Mon Sep 17 00:00:00 2001 From: Justin Shepherd Date: Tue, 2 Aug 2011 22:25:23 -0500 Subject: Resolved pep8 errors --- nova/api/openstack/create_instance_helper.py | 2 +- nova/test.py | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/nova/api/openstack/create_instance_helper.py b/nova/api/openstack/create_instance_helper.py index a2d18d37e..333994fcc 100644 --- a/nova/api/openstack/create_instance_helper.py +++ b/nova/api/openstack/create_instance_helper.py @@ -92,7 +92,7 @@ class CreateInstanceHelper(object): image_href = self.controller._image_ref_from_req_data(body) # If the image href was generated by nova api, strip image_href # down to an id and use the default glance connection params - + if str(image_href).startswith(req.application_url): image_href = image_href.split('/').pop() try: diff --git a/nova/test.py b/nova/test.py index afc118100..f1b4050f9 100644 --- a/nova/test.py +++ b/nova/test.py @@ -67,6 +67,7 @@ class skip_test(object): _skipper.__doc__ = func.__doc__ return _skipper + class skip_if(object): """Decorator that skips a test if contition is true.""" def __init__(self, condition, msg): @@ -84,7 +85,7 @@ class skip_if(object): class skip_unless(object): - """Decorator that skips a test if condition is false.""" + """Decorator that skips a test if condition is not true.""" def __init__(self, condition, msg): self.condition = condition self.message = msg -- cgit From d543b9914506b39defbf94ebc63eb95f0d58a8cd Mon Sep 17 00:00:00 2001 From: Justin Shepherd Date: Wed, 3 Aug 2011 09:32:24 -0500 Subject: Removed dependancy on os.getenv. Test cases now raise Exception if they are not properly skipped. --- nova/tests/test_skip_examples.py | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/nova/tests/test_skip_examples.py b/nova/tests/test_skip_examples.py index b7979d34b..e41cd848d 100644 --- a/nova/tests/test_skip_examples.py +++ b/nova/tests/test_skip_examples.py @@ -16,22 +16,18 @@ # License for the specific language governing permissions and limitations # under the License. -import os - from nova import test class ExampleSkipTestCase(test.TestCase): - @test.skip_test("testing skipping") + @test.skip_test("Example usage of @test.skip_test()") def test_skip_test(self): - x = 1 + raise Exception("skip_test failed to work properly.") - @test.skip_if(os.getenv("USER"), - "Skiping -- Environment variable USER exists") + @test.skip_if(True, "Example usage of @test.skip_if()") def test_skip_if_env_user_exists(self): - x = 1 + raise Exception("skip_if failed to work properly.") - @test.skip_unless(os.getenv("FOO"), - "Skipping -- Environment variable FOO does not exist") + @test.skip_unless(False, "Example usage of @test.skip_unless()") def test_skip_unless_env_foo_exists(self): - x = 1 + raise Exception("skip_unless failed to work properly.") -- cgit From c237b762381856b1041be06debf0deed4ae4e2a8 Mon Sep 17 00:00:00 2001 From: Justin Shepherd Date: Wed, 3 Aug 2011 10:44:09 -0500 Subject: replaced raise Exception with self.fail() --- nova/tests/test_skip_examples.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nova/tests/test_skip_examples.py b/nova/tests/test_skip_examples.py index e41cd848d..41c3b1b5f 100644 --- a/nova/tests/test_skip_examples.py +++ b/nova/tests/test_skip_examples.py @@ -22,12 +22,12 @@ from nova import test class ExampleSkipTestCase(test.TestCase): @test.skip_test("Example usage of @test.skip_test()") def test_skip_test(self): - raise Exception("skip_test failed to work properly.") + self.fail("skip_test failed to work properly.") @test.skip_if(True, "Example usage of @test.skip_if()") def test_skip_if_env_user_exists(self): - raise Exception("skip_if failed to work properly.") + self.fail("skip_if failed to work properly.") @test.skip_unless(False, "Example usage of @test.skip_unless()") def test_skip_unless_env_foo_exists(self): - raise Exception("skip_unless failed to work properly.") + self.fail("skip_unless failed to work properly.") -- cgit From 27392e9412c7042b67947dbc103704d121d60e12 Mon Sep 17 00:00:00 2001 From: Justin Shepherd Date: Wed, 3 Aug 2011 20:48:17 -0500 Subject: Conditionals were not actually runing the tests when they were supposed to. Renamed example testcases --- nova/test.py | 2 ++ nova/tests/test_skip_examples.py | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/nova/test.py b/nova/test.py index f1b4050f9..97cd3e0d0 100644 --- a/nova/test.py +++ b/nova/test.py @@ -79,6 +79,7 @@ class skip_if(object): """Wrapped skipper function.""" if self.condition: raise nose.SkipTest(self.message) + func(*args, **kw) _skipper.__name__ = func.__name__ _skipper.__doc__ = func.__doc__ return _skipper @@ -95,6 +96,7 @@ class skip_unless(object): """Wrapped skipper function.""" if not self.condition: raise nose.SkipTest(self.message) + func(*args, **kw) _skipper.__name__ = func.__name__ _skipper.__doc__ = func.__doc__ return _skipper diff --git a/nova/tests/test_skip_examples.py b/nova/tests/test_skip_examples.py index 41c3b1b5f..0ae3576f7 100644 --- a/nova/tests/test_skip_examples.py +++ b/nova/tests/test_skip_examples.py @@ -21,13 +21,13 @@ from nova import test class ExampleSkipTestCase(test.TestCase): @test.skip_test("Example usage of @test.skip_test()") - def test_skip_test(self): + def test_skip_test_example(self): self.fail("skip_test failed to work properly.") @test.skip_if(True, "Example usage of @test.skip_if()") - def test_skip_if_env_user_exists(self): + def test_skip_if_example(self): self.fail("skip_if failed to work properly.") @test.skip_unless(False, "Example usage of @test.skip_unless()") - def test_skip_unless_env_foo_exists(self): + def test_skip_unless_example(self): self.fail("skip_unless failed to work properly.") -- cgit From 144720ce87b3f0f469ed748780af55e32babc821 Mon Sep 17 00:00:00 2001 From: Justin Shepherd Date: Thu, 4 Aug 2011 09:29:43 -0500 Subject: Added in tests that verify tests are skipped appropriately. --- nova/tests/test_skip_examples.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/nova/tests/test_skip_examples.py b/nova/tests/test_skip_examples.py index 0ae3576f7..033f1ea2e 100644 --- a/nova/tests/test_skip_examples.py +++ b/nova/tests/test_skip_examples.py @@ -20,6 +20,8 @@ from nova import test class ExampleSkipTestCase(test.TestCase): + test_counter = 0 + @test.skip_test("Example usage of @test.skip_test()") def test_skip_test_example(self): self.fail("skip_test failed to work properly.") @@ -31,3 +33,15 @@ class ExampleSkipTestCase(test.TestCase): @test.skip_unless(False, "Example usage of @test.skip_unless()") def test_skip_unless_example(self): self.fail("skip_unless failed to work properly.") + + @test.skip_if(False, "This test case should never be skipped.") + def test_001_increase_test_counter(self): + ExampleSkipTestCase.test_counter += 1 + + @test.skip_unless(True, "This test case should never be skipped.") + def test_002_increase_test_counter(self): + ExampleSkipTestCase.test_counter += 1 + + def test_003_verify_test_counter(self): + self.assertEquals(ExampleSkipTestCase.test_counter, 2, + "Tests were not skipped appropriately") -- cgit From f22c19c6f78451074c33fe8da855755574cb6b49 Mon Sep 17 00:00:00 2001 From: Alex Meade Date: Thu, 4 Aug 2011 15:51:41 -0400 Subject: Split serverXMLDeserializers into v1.0 and v1.1 --- nova/api/openstack/create_instance_helper.py | 48 +++++++++++++++++++++++++ nova/api/openstack/servers.py | 7 +++- nova/tests/api/openstack/test_server_actions.py | 4 +-- nova/tests/api/openstack/test_servers.py | 2 +- 4 files changed, 57 insertions(+), 4 deletions(-) diff --git a/nova/api/openstack/create_instance_helper.py b/nova/api/openstack/create_instance_helper.py index 2a8e7fd7e..832c890b6 100644 --- a/nova/api/openstack/create_instance_helper.py +++ b/nova/api/openstack/create_instance_helper.py @@ -304,6 +304,54 @@ class ServerXMLDeserializer(wsgi.XMLDeserializer): metadata_deserializer = common.MetadataXMLDeserializer() + def create(self, string): + """Deserialize an xml-formatted server create request""" + dom = minidom.parseString(string) + server = self._extract_server(dom) + return {'body': {'server': server}} + + def _extract_server(self, node): + """Marshal the server attribute of a parsed request""" + server = {} + server_node = self.find_first_child_named(node, 'server') + + attributes = ["name", "imageId", "flavorId", "adminPass"] + for attr in attributes: + if server_node.getAttribute(attr): + server[attr] = server_node.getAttribute(attr) + + metadata_node = self.find_first_child_named(server_node, "metadata") + server["metadata"] = self.metadata_deserializer.extract_metadata( + metadata_node) + + server["personality"] = self._extract_personality(server_node) + + return server + + def _extract_personality(self, server_node): + """Marshal the personality attribute of a parsed request""" + node = self.find_first_child_named(server_node, "personality") + personality = [] + if node is not None: + for file_node in self.find_children_named(node, "file"): + item = {} + if file_node.hasAttribute("path"): + item["path"] = file_node.getAttribute("path") + item["contents"] = self.extract_text(file_node) + personality.append(item) + return personality + + +class ServerXMLDeserializerV11(wsgi.MetadataXMLDeserializer): + """ + Deserializer to handle xml-formatted server create requests. + + Handles standard server attributes as well as optional metadata + and personality attributes + """ + + metadata_deserializer = common.MetadataXMLDeserializer() + def action(self, string): dom = minidom.parseString(string) action_node = dom.childNodes[0] diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index d17714371..3acc4510e 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -891,8 +891,13 @@ def create_resource(version='1.0'): 'application/xml': xml_serializer, } + xml_deserializer = { + '1.0': helper.ServerXMLDeserializer(), + '1.1': helper.ServerXMLDeserializerV11(), + }[version] + body_deserializers = { - 'application/xml': helper.ServerXMLDeserializer(), + 'application/xml': xml_deserializer, } serializer = wsgi.ResponseSerializer(body_serializers, headers_serializer) diff --git a/nova/tests/api/openstack/test_server_actions.py b/nova/tests/api/openstack/test_server_actions.py index fc08a2d53..8f4cfacf8 100644 --- a/nova/tests/api/openstack/test_server_actions.py +++ b/nova/tests/api/openstack/test_server_actions.py @@ -734,10 +734,10 @@ class ServerActionsTestV11(test.TestCase): self.assertTrue(response.headers['Location']) -class TestServerActionXMLDeserializer(test.TestCase): +class TestServerActionXMLDeserializerV11(test.TestCase): def setUp(self): - self.deserializer = create_instance_helper.ServerXMLDeserializer() + self.deserializer = create_instance_helper.ServerXMLDeserializerV11() def tearDown(self): pass diff --git a/nova/tests/api/openstack/test_servers.py b/nova/tests/api/openstack/test_servers.py index 1349b289d..748573cce 100644 --- a/nova/tests/api/openstack/test_servers.py +++ b/nova/tests/api/openstack/test_servers.py @@ -2181,7 +2181,7 @@ class TestServerCreateRequestXMLDeserializerV11(test.TestCase): def setUp(self): super(TestServerCreateRequestXMLDeserializerV11, self).setUp() - self.deserializer = create_instance_helper.ServerXMLDeserializer() + self.deserializer = create_instance_helper.ServerXMLDeserializerV11() def test_minimal_request(self): serial_request = """ -- cgit From 9ce80fc74b3ea4513369b795d1e6891d6dfa8e03 Mon Sep 17 00:00:00 2001 From: Alex Meade Date: Thu, 4 Aug 2011 16:20:37 -0400 Subject: Updated create image server action to respect 1.1 --- nova/api/openstack/create_instance_helper.py | 23 ++++++++++++++--------- nova/tests/api/openstack/test_server_actions.py | 1 - nova/tests/api/openstack/test_servers.py | 10 ---------- 3 files changed, 14 insertions(+), 20 deletions(-) diff --git a/nova/api/openstack/create_instance_helper.py b/nova/api/openstack/create_instance_helper.py index 832c890b6..eec861428 100644 --- a/nova/api/openstack/create_instance_helper.py +++ b/nova/api/openstack/create_instance_helper.py @@ -380,8 +380,10 @@ class ServerXMLDeserializerV11(wsgi.MetadataXMLDeserializer): if value: data[attribute] = value metadata_node = self.find_first_child_named(node, 'metadata') - metadata = self.metadata_deserializer.extract_metadata(metadata_node) - data['metadata'] = metadata + if metadata_node is not None: + metadata = self.metadata_deserializer.extract_metadata( + metadata_node) + data['metadata'] = metadata return data def create(self, string): @@ -395,29 +397,32 @@ class ServerXMLDeserializerV11(wsgi.MetadataXMLDeserializer): server = {} server_node = self.find_first_child_named(node, 'server') - attributes = ["name", "imageId", "flavorId", "imageRef", - "flavorRef", "adminPass"] + attributes = ["name", "imageRef", "flavorRef", "adminPass"] for attr in attributes: if server_node.getAttribute(attr): server[attr] = server_node.getAttribute(attr) metadata_node = self.find_first_child_named(server_node, "metadata") - server["metadata"] = self.metadata_deserializer.extract_metadata( - metadata_node) + if metadata_node is not None: + server["metadata"] = self.extract_metadata(metadata_node) - server["personality"] = self._extract_personality(server_node) + personality = self._extract_personality(server_node) + if personality is not None: + server["personality"] = personality return server def _extract_personality(self, server_node): """Marshal the personality attribute of a parsed request""" node = self.find_first_child_named(server_node, "personality") - personality = [] if node is not None: + personality = [] for file_node in self.find_children_named(node, "file"): item = {} if file_node.hasAttribute("path"): item["path"] = file_node.getAttribute("path") item["contents"] = self.extract_text(file_node) personality.append(item) - return personality + return personality + else: + return None diff --git a/nova/tests/api/openstack/test_server_actions.py b/nova/tests/api/openstack/test_server_actions.py index 8f4cfacf8..fe627987f 100644 --- a/nova/tests/api/openstack/test_server_actions.py +++ b/nova/tests/api/openstack/test_server_actions.py @@ -750,7 +750,6 @@ class TestServerActionXMLDeserializerV11(test.TestCase): expected = { "createImage": { "name": "new-server-test", - "metadata": {}, }, } self.assertEquals(request['body'], expected) diff --git a/nova/tests/api/openstack/test_servers.py b/nova/tests/api/openstack/test_servers.py index 748573cce..235554afb 100644 --- a/nova/tests/api/openstack/test_servers.py +++ b/nova/tests/api/openstack/test_servers.py @@ -2195,8 +2195,6 @@ class TestServerCreateRequestXMLDeserializerV11(test.TestCase): "name": "new-server-test", "imageRef": "1", "flavorRef": "2", - "metadata": {}, - "personality": [], }, } self.assertEquals(request['body'], expected) @@ -2215,8 +2213,6 @@ class TestServerCreateRequestXMLDeserializerV11(test.TestCase): "imageRef": "1", "flavorRef": "2", "adminPass": "1234", - "metadata": {}, - "personality": [], }, } self.assertEquals(request['body'], expected) @@ -2233,8 +2229,6 @@ class TestServerCreateRequestXMLDeserializerV11(test.TestCase): "name": "new-server-test", "imageRef": "http://localhost:8774/v1.1/images/2", "flavorRef": "3", - "metadata": {}, - "personality": [], }, } self.assertEquals(request['body'], expected) @@ -2251,8 +2245,6 @@ class TestServerCreateRequestXMLDeserializerV11(test.TestCase): "name": "new-server-test", "imageRef": "1", "flavorRef": "http://localhost:8774/v1.1/flavors/3", - "metadata": {}, - "personality": [], }, } self.assertEquals(request['body'], expected) @@ -2296,7 +2288,6 @@ class TestServerCreateRequestXMLDeserializerV11(test.TestCase): "imageRef": "1", "flavorRef": "2", "metadata": {"one": "two", "open": "snack"}, - "personality": [], }, } self.assertEquals(request['body'], expected) @@ -2318,7 +2309,6 @@ class TestServerCreateRequestXMLDeserializerV11(test.TestCase): "name": "new-server-test", "imageRef": "1", "flavorRef": "2", - "metadata": {}, "personality": [ {"path": "/etc/banner.txt", "contents": "MQ=="}, {"path": "/etc/hosts", "contents": "Mg=="}, -- cgit From 0f515d6d31b2c95ed7f1e3ca8d9d67f98fda9fbe Mon Sep 17 00:00:00 2001 From: Alex Meade Date: Thu, 4 Aug 2011 16:26:31 -0400 Subject: Added XML serialization for server actions --- nova/api/openstack/create_instance_helper.py | 46 ++++++++ nova/tests/api/openstack/test_server_actions.py | 144 ++++++++++++++++++++++++ 2 files changed, 190 insertions(+) diff --git a/nova/api/openstack/create_instance_helper.py b/nova/api/openstack/create_instance_helper.py index eec861428..894d47beb 100644 --- a/nova/api/openstack/create_instance_helper.py +++ b/nova/api/openstack/create_instance_helper.py @@ -360,6 +360,12 @@ class ServerXMLDeserializerV11(wsgi.MetadataXMLDeserializer): action_deserializer = { 'createImage': self._action_create_image, 'createBackup': self._action_create_backup, + 'changePassword': self._action_change_password, + 'reboot': self._action_reboot, + 'rebuild': self._action_rebuild, + 'resize': self._action_resize, + 'confirmResize': self._action_confirm_resize, + 'revertResize': self._action_revert_resize, }.get(action_name, self.default) action_data = action_deserializer(action_node) @@ -373,6 +379,46 @@ class ServerXMLDeserializerV11(wsgi.MetadataXMLDeserializer): attributes = ('name', 'backup_type', 'rotation') return self._deserialize_image_action(node, attributes) + def _action_change_password(self, node): + if not node.hasAttribute("adminPass"): + raise AttributeError("No adminPass was specified in request") + return {"adminPass": node.getAttribute("adminPass")} + + def _action_reboot(self, node): + if not node.hasAttribute("type"): + raise AttributeError("No reboot type was specified in request") + return {"type": node.getAttribute("type")} + + def _action_rebuild(self, node): + rebuild = {} + if node.hasAttribute("name"): + rebuild['name'] = node.getAttribute("name") + + metadata_node = self.find_first_child_named(node, "metadata") + if metadata_node is not None: + rebuild["metadata"] = self.extract_metadata(metadata_node) + + personality = self._extract_personality(node) + if personality is not None: + rebuild["personality"] = personality + + if not node.hasAttribute("imageRef"): + raise AttributeError("No imageRef was specified in request") + rebuild["imageRef"] = node.getAttribute("imageRef") + + return rebuild + + def _action_resize(self, node): + if not node.hasAttribute("flavorRef"): + raise AttributeError("No flavorRef was specified in request") + return {"flavorRef": node.getAttribute("flavorRef")} + + def _action_confirm_resize(self, node): + return None + + def _action_revert_resize(self, node): + return None + def _deserialize_image_action(self, node, allowed_attributes): data = {} for attribute in allowed_attributes: diff --git a/nova/tests/api/openstack/test_server_actions.py b/nova/tests/api/openstack/test_server_actions.py index fe627987f..b175a7ff2 100644 --- a/nova/tests/api/openstack/test_server_actions.py +++ b/nova/tests/api/openstack/test_server_actions.py @@ -770,3 +770,147 @@ class TestServerActionXMLDeserializerV11(test.TestCase): }, } self.assertEquals(request['body'], expected) + + def test_change_pass(self): + serial_request = """ + """ + request = self.deserializer.deserialize(serial_request, 'action') + expected = { + "changePassword": { + "adminPass": "1234pass", + }, + } + self.assertEquals(request['body'], expected) + + def test_change_pass_no_pass(self): + serial_request = """ + """ + self.assertRaises(AttributeError, + self.deserializer.deserialize, + serial_request, + 'action') + + def test_reboot(self): + serial_request = """ + """ + request = self.deserializer.deserialize(serial_request, 'action') + expected = { + "reboot": { + "type": "HARD", + }, + } + self.assertEquals(request['body'], expected) + + def test_reboot_no_type(self): + serial_request = """ + """ + self.assertRaises(AttributeError, + self.deserializer.deserialize, + serial_request, + 'action') + + def test_resize(self): + serial_request = """ + """ + request = self.deserializer.deserialize(serial_request, 'action') + expected = { + "resize": { + "flavorRef": "http://localhost/flavors/3" + }, + } + self.assertEquals(request['body'], expected) + + def test_resize_no_flavor_ref(self): + serial_request = """ + """ + self.assertRaises(AttributeError, + self.deserializer.deserialize, + serial_request, + 'action') + + def test_confirm_resize(self): + serial_request = """ + """ + request = self.deserializer.deserialize(serial_request, 'action') + expected = { + "confirmResize": None, + } + self.assertEquals(request['body'], expected) + + def test_revert_resize(self): + serial_request = """ + """ + request = self.deserializer.deserialize(serial_request, 'action') + expected = { + "revertResize": None, + } + self.assertEquals(request['body'], expected) + + def test_rebuild(self): + serial_request = """ + + + Apache1 + + + Mg== + + """ + request = self.deserializer.deserialize(serial_request, 'action') + expected = { + "rebuild": { + "name": "new-server-test", + "imageRef": "http://localhost/images/1", + "metadata": { + "My Server Name": "Apache1", + }, + "personality": [ + {"path": "/etc/banner.txt", "contents": "Mg=="}, + ], + }, + } + self.assertDictEqual(request['body'], expected) + + def test_rebuild_minimum(self): + serial_request = """ + """ + request = self.deserializer.deserialize(serial_request, 'action') + expected = { + "rebuild": { + "imageRef": "http://localhost/images/1", + }, + } + self.assertDictEqual(request['body'], expected) + + def test_rebuild_no_imageRef(self): + serial_request = """ + + + Apache1 + + + Mg== + + """ + self.assertRaises(AttributeError, + self.deserializer.deserialize, + serial_request, + 'action') -- cgit From 5b463f5d14c62f66250d5edc3edbd2ded704e0da Mon Sep 17 00:00:00 2001 From: Alex Meade Date: Thu, 4 Aug 2011 16:38:55 -0400 Subject: Added missing tests for server actions Updated reboot to verify the reboot type is HARD or SOFT Fixed case of having an empty flavorref on resize --- nova/api/openstack/servers.py | 9 +- nova/tests/api/openstack/test_server_actions.py | 107 ++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 1 deletion(-) diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index 3acc4510e..fa4d11e24 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -268,9 +268,13 @@ class Controller(object): def _action_reboot(self, input_dict, req, id): if 'reboot' in input_dict and 'type' in input_dict['reboot']: reboot_type = input_dict['reboot']['type'] + if (not reboot_type == 'HARD') and (not reboot_type == 'SOFT'): + msg = _("Argument 'type' for reboot is not HARD or SOFT") + LOG.exception(msg) + raise exc.HTTPBadRequest() else: LOG.exception(_("Missing argument 'type' for reboot")) - raise exc.HTTPUnprocessableEntity() + raise exc.HTTPBadRequest() try: # TODO(gundlach): pass reboot_type, support soft reboot in # virt driver @@ -646,6 +650,9 @@ class ControllerV11(Controller): """ Resizes a given instance to the flavor size requested """ try: flavor_ref = input_dict["resize"]["flavorRef"] + if not flavor_ref: + msg = _("Resize request has invalid 'flavorRef' attribute.") + raise exc.HTTPBadRequest(explanation=msg) except (KeyError, TypeError): msg = _("Resize requests require 'flavorRef' attribute.") raise exc.HTTPBadRequest(explanation=msg) diff --git a/nova/tests/api/openstack/test_server_actions.py b/nova/tests/api/openstack/test_server_actions.py index b175a7ff2..b5e4246e9 100644 --- a/nova/tests/api/openstack/test_server_actions.py +++ b/nova/tests/api/openstack/test_server_actions.py @@ -479,6 +479,21 @@ class ServerActionsTestV11(test.TestCase): self.assertEqual(mock_method.instance_id, '1') self.assertEqual(mock_method.password, '1234pass') + def test_server_change_password_xml(self): + mock_method = MockSetAdminPassword() + self.stubs.Set(nova.compute.api.API, 'set_admin_password', mock_method) + req = webob.Request.blank('/v1.1/servers/1/action') + req.method = 'POST' + req.content_type = "application/xml" + req.body = """ + """ + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 202) + self.assertEqual(mock_method.instance_id, '1') + self.assertEqual(mock_method.password, '1234pass') + def test_server_change_password_not_a_string(self): body = {'changePassword': {'adminPass': 1234}} req = webob.Request.blank('/v1.1/servers/1/action') @@ -515,6 +530,42 @@ class ServerActionsTestV11(test.TestCase): res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 400) + def test_server_reboot_hard(self): + body = dict(reboot=dict(type="HARD")) + 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) + + def test_server_reboot_soft(self): + body = dict(reboot=dict(type="SOFT")) + 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) + + def test_server_reboot_incorrect_type(self): + body = dict(reboot=dict(type="NOT_A_TYPE")) + 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_missing_type(self): + body = dict(reboot=dict()) + 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_rebuild_accepted_minimum(self): body = { "rebuild": { @@ -657,6 +708,62 @@ class ServerActionsTestV11(test.TestCase): self.assertEqual(res.status_int, 202) self.assertEqual(self.resize_called, True) + def test_resize_server_no_flavor(self): + req = webob.Request.blank('/v1.1/servers/1/action') + req.content_type = 'application/json' + req.method = 'POST' + body_dict = dict(resize=dict()) + req.body = json.dumps(body_dict) + + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 400) + + def test_resize_server_no_flavor_ref(self): + req = webob.Request.blank('/v1.1/servers/1/action') + req.content_type = 'application/json' + req.method = 'POST' + body_dict = dict(resize=dict(flavorRef=None)) + req.body = json.dumps(body_dict) + + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 400) + + def test_confirm_resize_server(self): + req = webob.Request.blank('/v1.1/servers/1/action') + req.content_type = 'application/json' + req.method = 'POST' + body_dict = dict(confirmResize=None) + req.body = json.dumps(body_dict) + + self.confirm_resize_called = False + + def cr_mock(*args): + self.confirm_resize_called = True + + self.stubs.Set(nova.compute.api.API, 'confirm_resize', cr_mock) + + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 204) + self.assertEqual(self.confirm_resize_called, True) + + def test_revert_resize_server(self): + req = webob.Request.blank('/v1.1/servers/1/action') + req.content_type = 'application/json' + req.method = 'POST' + body_dict = dict(revertResize=None) + req.body = json.dumps(body_dict) + + self.revert_resize_called = False + + def revert_mock(*args): + self.revert_resize_called = True + + self.stubs.Set(nova.compute.api.API, 'revert_resize', revert_mock) + + res = req.get_response(fakes.wsgi_app()) + self.assertEqual(res.status_int, 202) + self.assertEqual(self.revert_resize_called, True) + def test_create_image(self): body = { 'createImage': { -- cgit From d470f82ea09214b6f535995aa551a23eb4ccc4ed Mon Sep 17 00:00:00 2001 From: Adam Gandelman Date: Thu, 4 Aug 2011 17:43:37 -0700 Subject: Properly format mapping['dns'] before handing off to template for injection (Fixes LP Bug #821203) --- nova/virt/libvirt/connection.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/virt/libvirt/connection.py b/nova/virt/libvirt/connection.py index f7aae4112..0f0f62588 100644 --- a/nova/virt/libvirt/connection.py +++ b/nova/virt/libvirt/connection.py @@ -880,7 +880,7 @@ class LibvirtConnection(driver.ComputeDriver): 'netmask': netmask, 'gateway': mapping['gateway'], 'broadcast': mapping['broadcast'], - 'dns': mapping['dns'], + 'dns': ' '.join(mapping['dns']), 'address_v6': address_v6, 'gateway6': gateway_v6, 'netmask_v6': netmask_v6} -- cgit From 637dfc0f44cbd5bf0c76d80d708a241e562403ac Mon Sep 17 00:00:00 2001 From: Gabe Westmaas Date: Fri, 5 Aug 2011 01:55:53 +0000 Subject: Added explanations to exceptions and cleaned up reboot types --- nova/api/openstack/servers.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index fa4d11e24..9a55af8ea 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -267,14 +267,16 @@ class Controller(object): def _action_reboot(self, input_dict, req, id): if 'reboot' in input_dict and 'type' in input_dict['reboot']: - reboot_type = input_dict['reboot']['type'] - if (not reboot_type == 'HARD') and (not reboot_type == 'SOFT'): + valid_reboot_types = ['HARD', 'SOFT'] + reboot_type = input_dict['reboot']['type'].upper() + if not valid_reboot_types.count(reboot_type): msg = _("Argument 'type' for reboot is not HARD or SOFT") LOG.exception(msg) - raise exc.HTTPBadRequest() + raise exc.HTTPBadRequest(explanation=msg) else: - LOG.exception(_("Missing argument 'type' for reboot")) - raise exc.HTTPBadRequest() + msg = _("Missing argument 'type' for reboot") + LOG.exception(msg) + raise exc.HTTPBadRequest(explanation=msg) try: # TODO(gundlach): pass reboot_type, support soft reboot in # virt driver -- cgit From b068e1edd79a5382ef1237d0b47e60dc141bae35 Mon Sep 17 00:00:00 2001 From: Ilya Alekseyev Date: Fri, 5 Aug 2011 07:55:22 +0400 Subject: added missing tests --- nova/tests/test_nova_manage.py | 79 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 nova/tests/test_nova_manage.py diff --git a/nova/tests/test_nova_manage.py b/nova/tests/test_nova_manage.py new file mode 100644 index 000000000..ca9ffa222 --- /dev/null +++ b/nova/tests/test_nova_manage.py @@ -0,0 +1,79 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2011 OpenStack LLC +# Copyright 2011 Ilya Alekseyev +# +# 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 os + +TOPDIR = os.path.normpath(os.path.join( + os.path.dirname(os.path.abspath(__file__)), + os.pardir, + os.pardir)) +NOVA_MANAGE_PATH = os.path.join(TOPDIR, 'bin', 'nova-manage') + +import imp +nova_manage = imp.load_source('nova_manage', NOVA_MANAGE_PATH) + +import netaddr +from nova import context +from nova import db +from nova import flags +from nova import test + +FLAGS = flags.FLAGS + + +class FixedIpCommandsTestCase(test.TestCase): + def setUp(self): + super(FixedIpCommandsTestCase, self).setUp() + cidr = '10.0.0.0/24' + net = netaddr.IPNetwork(cidr) + net_info = {'bridge': 'fakebr', + 'bridge_interface': 'fakeeth', + 'dns': FLAGS.flat_network_dns, + 'cidr': cidr, + 'netmask': str(net.netmask), + 'gateway': str(net[1]), + 'broadcast': str(net.broadcast), + 'dhcp_start': str(net[2])} + self.network = db.network_create_safe(context.get_admin_context(), + net_info) + num_ips = len(net) + for index in range(num_ips): + address = str(net[index]) + reserved = (index == 1 or index == 2) + db.fixed_ip_create(context.get_admin_context(), + {'network_id': self.network['id'], + 'address': address, + 'reserved': reserved}) + self.commands = nova_manage.FixedIpCommands() + + def tearDown(self): + db.network_delete_safe(context.get_admin_context(), self.network['id']) + super(FixedIpCommandsTestCase, self).tearDown() + + def test_reserve(self): + self.commands.reserve('10.0.0.100') + address = db.fixed_ip_get_by_address(context.get_admin_context(), + '10.0.0.100') + self.assertEqual(address['reserved'], True) + + def test_waste(self): + db.fixed_ip_update(context.get_admin_context(), '10.0.0.100', + {'reserved': True}) + self.commands.waste('10.0.0.100') + address = db.fixed_ip_get_by_address(context.get_admin_context(), + '10.0.0.100') + self.assertEqual(address['reserved'], False) -- cgit From 625330bbc70b7be0d007c2a5ce1fba4dfcc29bf8 Mon Sep 17 00:00:00 2001 From: Justin Shepherd Date: Thu, 4 Aug 2011 22:59:36 -0500 Subject: utilized functools.wraps --- nova/test.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/nova/test.py b/nova/test.py index 97cd3e0d0..d3b9d3ee2 100644 --- a/nova/test.py +++ b/nova/test.py @@ -60,11 +60,10 @@ class skip_test(object): self.message = msg def __call__(self, func): + @functools.wraps(func) def _skipper(*args, **kw): """Wrapped skipper function.""" raise nose.SkipTest(self.message) - _skipper.__name__ = func.__name__ - _skipper.__doc__ = func.__doc__ return _skipper @@ -75,13 +74,12 @@ class skip_if(object): self.message = msg def __call__(self, func): + @functools.wraps(func) def _skipper(*args, **kw): """Wrapped skipper function.""" if self.condition: raise nose.SkipTest(self.message) func(*args, **kw) - _skipper.__name__ = func.__name__ - _skipper.__doc__ = func.__doc__ return _skipper @@ -92,13 +90,12 @@ class skip_unless(object): self.message = msg def __call__(self, func): + @functools.wraps(func) def _skipper(*args, **kw): """Wrapped skipper function.""" if not self.condition: raise nose.SkipTest(self.message) func(*args, **kw) - _skipper.__name__ = func.__name__ - _skipper.__doc__ = func.__doc__ return _skipper -- cgit From 13fb04effa25e860eaa9e4ebaca2b4d906a140b0 Mon Sep 17 00:00:00 2001 From: Justin Shepherd Date: Thu, 4 Aug 2011 23:01:22 -0500 Subject: fixed pep8 issue --- nova/tests/test_skip_examples.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/tests/test_skip_examples.py b/nova/tests/test_skip_examples.py index 033f1ea2e..8ca203442 100644 --- a/nova/tests/test_skip_examples.py +++ b/nova/tests/test_skip_examples.py @@ -37,7 +37,7 @@ class ExampleSkipTestCase(test.TestCase): @test.skip_if(False, "This test case should never be skipped.") def test_001_increase_test_counter(self): ExampleSkipTestCase.test_counter += 1 - + @test.skip_unless(True, "This test case should never be skipped.") def test_002_increase_test_counter(self): ExampleSkipTestCase.test_counter += 1 -- cgit From 9742ff588d3ce90b1420eaf95e311f02a4e196da Mon Sep 17 00:00:00 2001 From: Soren Hansen Date: Fri, 5 Aug 2011 14:54:56 +0200 Subject: Add generic image service tests. --- nova/image/fake.py | 41 ++++++++++---- nova/tests/test_image.py | 135 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 165 insertions(+), 11 deletions(-) create mode 100644 nova/tests/test_image.py diff --git a/nova/image/fake.py b/nova/image/fake.py index 28e912534..b29ec6517 100644 --- a/nova/image/fake.py +++ b/nova/image/fake.py @@ -45,9 +45,12 @@ class _FakeImageService(service.BaseImageService): 'name': 'fakeimage123456', 'created_at': timestamp, 'updated_at': timestamp, + 'deleted_at': None, + 'deleted': False, 'status': 'active', - 'container_format': 'ami', - 'disk_format': 'raw', + 'is_public': False, +# 'container_format': 'ami', +# 'disk_format': 'raw', 'properties': {'kernel_id': FLAGS.null_kernel, 'ramdisk_id': FLAGS.null_kernel, 'architecture': 'x86_64'}} @@ -56,9 +59,12 @@ class _FakeImageService(service.BaseImageService): 'name': 'fakeimage123456', 'created_at': timestamp, 'updated_at': timestamp, + 'deleted_at': None, + 'deleted': False, 'status': 'active', - 'container_format': 'ami', - 'disk_format': 'raw', + 'is_public': True, +# 'container_format': 'ami', +# 'disk_format': 'raw', 'properties': {'kernel_id': FLAGS.null_kernel, 'ramdisk_id': FLAGS.null_kernel}} @@ -66,9 +72,12 @@ class _FakeImageService(service.BaseImageService): 'name': 'fakeimage123456', 'created_at': timestamp, 'updated_at': timestamp, + 'deleted_at': None, + 'deleted': False, 'status': 'active', - 'container_format': 'ami', - 'disk_format': 'raw', + 'is_public': True, +# 'container_format': 'ami', +# 'disk_format': 'raw', 'properties': {'kernel_id': FLAGS.null_kernel, 'ramdisk_id': FLAGS.null_kernel}} @@ -76,9 +85,12 @@ class _FakeImageService(service.BaseImageService): 'name': 'fakeimage123456', 'created_at': timestamp, 'updated_at': timestamp, + 'deleted_at': None, + 'deleted': False, 'status': 'active', - 'container_format': 'ami', - 'disk_format': 'raw', + 'is_public': True, +# 'container_format': 'ami', +# 'disk_format': 'raw', 'properties': {'kernel_id': FLAGS.null_kernel, 'ramdisk_id': FLAGS.null_kernel}} @@ -86,9 +98,12 @@ class _FakeImageService(service.BaseImageService): 'name': 'fakeimage123456', 'created_at': timestamp, 'updated_at': timestamp, + 'deleted_at': None, + 'deleted': False, 'status': 'active', - 'container_format': 'ami', - 'disk_format': 'raw', + 'is_public': True, +# 'container_format': 'ami', +# 'disk_format': 'raw', 'properties': {'kernel_id': FLAGS.null_kernel, 'ramdisk_id': FLAGS.null_kernel}} @@ -101,7 +116,11 @@ class _FakeImageService(service.BaseImageService): def index(self, context, filters=None, marker=None, limit=None): """Returns list of images.""" - return copy.deepcopy(self.images.values()) + retval = [] + for img in self.images.values(): + retval += [dict([(k, v) for k, v in img.iteritems() + if k in ['id', 'name']])] + return retval def detail(self, context, filters=None, marker=None, limit=None): """Return list of detailed image information.""" diff --git a/nova/tests/test_image.py b/nova/tests/test_image.py new file mode 100644 index 000000000..ba5b93f9b --- /dev/null +++ b/nova/tests/test_image.py @@ -0,0 +1,135 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2011 Linux2Go +# Author: Soren Hansen +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import datetime + +from nova import context +from nova import exception +from nova import test +import nova.image + +class _ImageTestCase(test.TestCase): + def setUp(self): + super(_ImageTestCase, self).setUp() + self.context = context.get_admin_context() + + def test_index(self): + res = self.image_service.index(self.context) + for image in res: + self.assertEquals(set(image.keys()), set(['id', 'name'])) + + def test_detail(self): + res = self.image_service.detail(self.context) + for image in res: + keys = set(image.keys()) + self.assertEquals(keys, set(['id', 'name', 'created_at', + 'updated_at', 'deleted_at', 'deleted', + 'status', 'is_public', 'properties'])) + self.assertTrue(isinstance(image['created_at'], datetime.datetime)) + self.assertTrue(isinstance(image['updated_at'], datetime.datetime)) + + if not (isinstance(image['deleted_at'], datetime.datetime) or + image['deleted_at'] is None): + self.fail('image\'s "deleted_at" attribute was neither a ' + 'datetime object nor None') + + def check_is_bool(image, key): + val = image.get('deleted') + if not isinstance(val, bool): + self.fail('image\'s "%s" attribute wasn\'t ' + 'a bool: %r' % (key, val)) + + check_is_bool(image, 'deleted') + check_is_bool(image, 'is_public') + + def test_index_and_detail_have_same_results(self): + index = self.image_service.index(self.context) + detail = self.image_service.detail(self.context) + index_set = set([(i['id'], i['name']) for i in index]) + detail_set = set([(i['id'], i['name']) for i in detail]) + self.assertEqual(index_set, detail_set) + + def test_show_raises_imagenotfound_for_invalid_id(self): + self.assertRaises(exception.ImageNotFound, + self.image_service.show, + self.context, + 'this image does not exist') + + def test_show_by_name(self): + self.assertRaises(exception.ImageNotFound, + self.image_service.show_by_name, + self.context, + 'this image does not exist') + + def test_create_adds_id(self): + index = self.image_service.index(self.context) + image_count = len(index) + + self.image_service.create(self.context, {}) + + index = self.image_service.index(self.context) + self.assertEquals(len(index), image_count+1) + + self.assertTrue(index[0]['id']) + + + def test_create_keeps_id(self): + self.image_service.create(self.context, {'id': '34'}) + self.image_service.show(self.context, '34') + + + def test_create_rejects_duplicate_ids(self): + self.image_service.create(self.context, {'id': '34'}) + self.assertRaises(exception.Duplicate, + self.image_service.create, + self.context, + {'id': '34'}) + + # Make sure there's still one left + self.image_service.show(self.context, '34') + + def test_update(self): + self.image_service.create(self.context, + {'id': '34', 'foo': 'bar'}) + + self.image_service.update(self.context, '34', + {'id': '34', 'foo': 'baz'}) + + img = self.image_service.show(self.context, '34') + self.assertEquals(img['foo'], 'baz') + + def test_delete(self): + self.image_service.create(self.context, {'id': '34', 'foo': 'bar'}) + self.image_service.delete(self.context, '34') + self.assertRaises(exception.NotFound, + self.image_service.show, + self.context, + '34') + + def test_delete_all(self): + self.image_service.create(self.context, {'id': '32', 'foo': 'bar'}) + self.image_service.create(self.context, {'id': '33', 'foo': 'bar'}) + self.image_service.create(self.context, {'id': '34', 'foo': 'bar'}) + self.image_service.delete_all() + index = self.image_service.index(self.context) + self.assertEquals(len(index), 0) + +class FakeImageTestCase(_ImageTestCase): + def setUp(self): + super(FakeImageTestCase, self).setUp() + self.image_service = nova.image.fake.FakeImageService() + -- cgit From 1e366d9de180347b47675bf7f811ffd5a293ef10 Mon Sep 17 00:00:00 2001 From: Soren Hansen Date: Fri, 5 Aug 2011 15:37:36 +0200 Subject: pep8 --- nova/image/fake.py | 2 +- nova/tests/test_image.py | 7 ++----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/nova/image/fake.py b/nova/image/fake.py index b29ec6517..97af81711 100644 --- a/nova/image/fake.py +++ b/nova/image/fake.py @@ -118,7 +118,7 @@ class _FakeImageService(service.BaseImageService): """Returns list of images.""" retval = [] for img in self.images.values(): - retval += [dict([(k, v) for k, v in img.iteritems() + retval += [dict([(k, v) for k, v in img.iteritems() if k in ['id', 'name']])] return retval diff --git a/nova/tests/test_image.py b/nova/tests/test_image.py index ba5b93f9b..5ec8812f3 100644 --- a/nova/tests/test_image.py +++ b/nova/tests/test_image.py @@ -1,6 +1,6 @@ # vim: tabstop=4 shiftwidth=4 softtabstop=4 -# Copyright 2011 Linux2Go +# Copyright 2011 OpenStack LLC # Author: Soren Hansen # # Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -82,16 +82,14 @@ class _ImageTestCase(test.TestCase): self.image_service.create(self.context, {}) index = self.image_service.index(self.context) - self.assertEquals(len(index), image_count+1) + self.assertEquals(len(index), image_count + 1) self.assertTrue(index[0]['id']) - def test_create_keeps_id(self): self.image_service.create(self.context, {'id': '34'}) self.image_service.show(self.context, '34') - def test_create_rejects_duplicate_ids(self): self.image_service.create(self.context, {'id': '34'}) self.assertRaises(exception.Duplicate, @@ -132,4 +130,3 @@ class FakeImageTestCase(_ImageTestCase): def setUp(self): super(FakeImageTestCase, self).setUp() self.image_service = nova.image.fake.FakeImageService() - -- cgit From 070d832dad062dfb18439e77b4460e6ebe75bdb0 Mon Sep 17 00:00:00 2001 From: Soren Hansen Date: Fri, 5 Aug 2011 15:38:25 +0200 Subject: Make disk_format and container_format optional for libvirt's snapshot implementation. --- nova/virt/libvirt/connection.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/nova/virt/libvirt/connection.py b/nova/virt/libvirt/connection.py index 0b93a8399..3663337e9 100644 --- a/nova/virt/libvirt/connection.py +++ b/nova/virt/libvirt/connection.py @@ -392,9 +392,7 @@ class LibvirtConnection(driver.ComputeDriver): nova.image.get_image_service(image_href) snapshot = snapshot_image_service.show(context, snapshot_image_id) - metadata = {'disk_format': base['disk_format'], - 'container_format': base['container_format'], - 'is_public': False, + metadata = {'is_public': False, 'status': 'active', 'name': snapshot['name'], 'properties': { @@ -409,6 +407,12 @@ class LibvirtConnection(driver.ComputeDriver): arch = base['properties']['architecture'] metadata['properties']['architecture'] = arch + if 'disk_format' in base: + metadata['disk_format'] = base['disk_format'] + + if 'container_format' in base: + metadata['container_format'] = base['container_format'] + # Make the snapshot snapshot_name = uuid.uuid4().hex snapshot_xml = """ -- cgit From 336efaf814c7796b9426d045f82f2d1e30d8db72 Mon Sep 17 00:00:00 2001 From: Dan Prince Date: Fri, 5 Aug 2011 11:17:05 -0400 Subject: Add exception logging for instance IDs in the __public_instance_is_accessible smoke test function. This should help troubleshoot an intermittent failure. --- smoketests/test_netadmin.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/smoketests/test_netadmin.py b/smoketests/test_netadmin.py index 60086f065..de69c98a2 100644 --- a/smoketests/test_netadmin.py +++ b/smoketests/test_netadmin.py @@ -115,7 +115,8 @@ class SecurityGroupTests(base.UserSmokeTestCase): if not instance_id: return False if instance_id != self.data['instance'].id: - raise Exception("Wrong instance id") + raise Exception("Wrong instance id. Expected: %s, Got: %s" % + (self.data['instance'].id, instance_id)) return True def test_001_can_create_security_group(self): -- cgit From a77f10ee052fdafeb9d52407695719397c52e68d Mon Sep 17 00:00:00 2001 From: Ilya Alekseyev Date: Fri, 5 Aug 2011 19:45:17 +0400 Subject: methods renamed --- bin/nova-manage | 2 +- nova/tests/test_nova_manage.py | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/bin/nova-manage b/bin/nova-manage index ba08f136b..6f71bc403 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -601,7 +601,7 @@ class FixedIpCommands(object): @args('--address', dest="address", metavar='', help='IP address') - def waste(self, address): + def unreserve(self, address): """Mark fixed ip as free to use arguments: address""" self._set_reserved(address, False) diff --git a/nova/tests/test_nova_manage.py b/nova/tests/test_nova_manage.py index ca9ffa222..9c6563f14 100644 --- a/nova/tests/test_nova_manage.py +++ b/nova/tests/test_nova_manage.py @@ -16,6 +16,7 @@ # under the License. import os +import sys TOPDIR = os.path.normpath(os.path.join( os.path.dirname(os.path.abspath(__file__)), @@ -23,8 +24,10 @@ TOPDIR = os.path.normpath(os.path.join( os.pardir)) NOVA_MANAGE_PATH = os.path.join(TOPDIR, 'bin', 'nova-manage') +sys.dont_write_bytecode = True import imp -nova_manage = imp.load_source('nova_manage', NOVA_MANAGE_PATH) +nova_manage = imp.load_source('nova_manage.py', NOVA_MANAGE_PATH) +sys.dont_write_bytecode = False import netaddr from nova import context @@ -70,10 +73,10 @@ class FixedIpCommandsTestCase(test.TestCase): '10.0.0.100') self.assertEqual(address['reserved'], True) - def test_waste(self): + def test_unreserve(self): db.fixed_ip_update(context.get_admin_context(), '10.0.0.100', {'reserved': True}) - self.commands.waste('10.0.0.100') + self.commands.unreserve('10.0.0.100') address = db.fixed_ip_get_by_address(context.get_admin_context(), '10.0.0.100') self.assertEqual(address['reserved'], False) -- cgit From 9602a558b6be6e6812626b986c0f9557a3862fe6 Mon Sep 17 00:00:00 2001 From: Brian Waldon Date: Fri, 5 Aug 2011 11:59:14 -0400 Subject: glance image service pagination --- nova/api/openstack/images.py | 4 +-- nova/exception.py | 4 +++ nova/image/glance.py | 82 +++++++++++++++++++++++++++++--------------- 3 files changed, 61 insertions(+), 29 deletions(-) diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index c76738d30..b9bc83fde 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -143,7 +143,7 @@ class ControllerV10(Controller): """ context = req.environ['nova.context'] filters = self._get_filters(req) - images = self._image_service.index(context, filters) + images = self._image_service.index(context, filters=filters) images = common.limited(images, req) builder = self.get_builder(req).build return dict(images=[builder(image, detail=False) for image in images]) @@ -156,7 +156,7 @@ class ControllerV10(Controller): """ context = req.environ['nova.context'] filters = self._get_filters(req) - images = self._image_service.detail(context, filters) + images = self._image_service.detail(context, filters=filters) images = common.limited(images, req) builder = self.get_builder(req).build return dict(images=[builder(image, detail=True) for image in images]) diff --git a/nova/exception.py b/nova/exception.py index 68e6ac937..792e306c1 100644 --- a/nova/exception.py +++ b/nova/exception.py @@ -150,6 +150,10 @@ class NovaException(Exception): return self._error_string +class ImagePaginationFailed(NovaException): + message = _("Failed to paginate through images from image service") + + class VirtualInterfaceCreateException(NovaException): message = _("Virtual Interface creation failed") diff --git a/nova/image/glance.py b/nova/image/glance.py index 44a3c6f83..ccb1b7ec0 100644 --- a/nova/image/glance.py +++ b/nova/image/glance.py @@ -87,42 +87,70 @@ class GlanceImageService(service.BaseImageService): """Sets the client's auth token.""" self.client.set_auth_token(context.auth_token) - def index(self, context, filters=None, marker=None, limit=None): + def index(self, context, **kwargs): """Calls out to Glance for a list of images available.""" - # NOTE(sirp): We need to use `get_images_detailed` and not - # `get_images` here because we need `is_public` and `properties` - # included so we can filter by user - self._set_client_context(context) - filtered = [] - filters = filters or {} - if 'is_public' not in filters: - # NOTE(vish): don't filter out private images - filters['is_public'] = 'none' - image_metas = self.client.get_images_detailed(filters=filters, - marker=marker, - limit=limit) + params = self._extract_query_params(kwargs) + image_metas = self._get_images(context, **params) + + images = [] for image_meta in image_metas: + # NOTE(sirp): We need to use `get_images_detailed` and not + # `get_images` here because we need `is_public` and `properties` + # included so we can filter by user if self._is_image_available(context, image_meta): meta_subset = utils.subset_dict(image_meta, ('id', 'name')) - filtered.append(meta_subset) - return filtered + images.append(meta_subset) + return images - def detail(self, context, filters=None, marker=None, limit=None): + def detail(self, context, **kwargs): """Calls out to Glance for a list of detailed image information.""" - self._set_client_context(context) - filtered = [] - filters = filters or {} - if 'is_public' not in filters: - # NOTE(vish): don't filter out private images - filters['is_public'] = 'none' - image_metas = self.client.get_images_detailed(filters=filters, - marker=marker, - limit=limit) + params = self._extract_query_params(kwargs) + image_metas = self._get_images(context, **params) + + images = [] for image_meta in image_metas: if self._is_image_available(context, image_meta): base_image_meta = self._translate_to_base(image_meta) - filtered.append(base_image_meta) - return filtered + images.append(base_image_meta) + return images + + def _extract_query_params(self, params): + _params = {} + accepted_params = ('filters', 'marker', 'limit') + #'sort_key', 'sort_dir') + for param in accepted_params: + _params[param] = params.get(param) + + return _params + + def _get_images(self, context, **kwargs): + """Get image entitites from images service""" + self._set_client_context(context) + + # ensure filters is a dict + kwargs['filters'] = kwargs['filters'] or {} + # NOTE(vish): don't filter out private images + kwargs['filters'].setdefault('is_public', 'none') + + return self._fetch_images(self.client.get_images_detailed, **kwargs) + + def _fetch_images(self, fetch_func, **kwargs): + """Paginate through results from glance server""" + images = fetch_func(**kwargs) + + for image in images: + yield image + else: + # break out of recursive loop to end pagination + return + + try: + # attempt to advance the marker in order to fetch next page + kwargs['marker'] = images[-1]['id'] + except KeyError: + raise exception.ImagePaginationFailed() + + self._fetch_images(fetch_func, **kwargs) def show(self, context, image_id): """Returns a dict with image data for the given opaque image id.""" -- cgit -- cgit From 149153085027237c343cc325e163979f1cd31a21 Mon Sep 17 00:00:00 2001 From: Gabe Westmaas Date: Fri, 5 Aug 2011 16:22:21 +0000 Subject: Moving from assertDictEqual to assertDictMatch --- nova/tests/api/openstack/test_server_actions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nova/tests/api/openstack/test_server_actions.py b/nova/tests/api/openstack/test_server_actions.py index 005923f4e..7e24d24fd 100644 --- a/nova/tests/api/openstack/test_server_actions.py +++ b/nova/tests/api/openstack/test_server_actions.py @@ -986,7 +986,7 @@ class TestServerActionXMLDeserializerV11(test.TestCase): ], }, } - self.assertDictEqual(request['body'], expected) + self.assertDictMatch(request['body'], expected) def test_rebuild_minimum(self): serial_request = """ @@ -999,7 +999,7 @@ class TestServerActionXMLDeserializerV11(test.TestCase): "imageRef": "http://localhost/images/1", }, } - self.assertDictEqual(request['body'], expected) + self.assertDictMatch(request['body'], expected) def test_rebuild_no_imageRef(self): serial_request = """ -- cgit From 681d3e2bfac2aa8e19cb393591b99efcbcdd8230 Mon Sep 17 00:00:00 2001 From: Brian Waldon Date: Fri, 5 Aug 2011 14:15:53 -0400 Subject: re-enabling sort_key/sort_dir and fixing filters line --- nova/image/glance.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/nova/image/glance.py b/nova/image/glance.py index ccb1b7ec0..23749e560 100644 --- a/nova/image/glance.py +++ b/nova/image/glance.py @@ -116,10 +116,11 @@ class GlanceImageService(service.BaseImageService): def _extract_query_params(self, params): _params = {} - accepted_params = ('filters', 'marker', 'limit') - #'sort_key', 'sort_dir') + accepted_params = ('filters', 'marker', 'limit', + 'sort_key', 'sort_dir') for param in accepted_params: - _params[param] = params.get(param) + if param in params: + _params[param] = params.get(param) return _params @@ -128,7 +129,7 @@ class GlanceImageService(service.BaseImageService): self._set_client_context(context) # ensure filters is a dict - kwargs['filters'] = kwargs['filters'] or {} + kwargs['filters'] = kwargs.get('filters', {}) # NOTE(vish): don't filter out private images kwargs['filters'].setdefault('is_public', 'none') -- cgit From a3e618bdc64f5e2cbb62fcf4a5b2df0e437c4fd9 Mon Sep 17 00:00:00 2001 From: Brian Waldon Date: Fri, 5 Aug 2011 15:02:18 -0400 Subject: fixing filters get --- nova/image/glance.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/image/glance.py b/nova/image/glance.py index 23749e560..da93f0d1c 100644 --- a/nova/image/glance.py +++ b/nova/image/glance.py @@ -129,7 +129,7 @@ class GlanceImageService(service.BaseImageService): self._set_client_context(context) # ensure filters is a dict - kwargs['filters'] = kwargs.get('filters', {}) + kwargs['filters'] = kwargs.get('filters') or {} # NOTE(vish): don't filter out private images kwargs['filters'].setdefault('is_public', 'none') -- cgit From f03c926a7d28ee35789048ea53c36cd452ed3571 Mon Sep 17 00:00:00 2001 From: Josh Kearney Date: Fri, 5 Aug 2011 14:28:22 -0500 Subject: Allow actions queries by UUID and PEP8 fixes. --- nova/api/direct.py | 1 + nova/api/openstack/common.py | 3 ++- nova/db/sqlalchemy/api.py | 10 ++++++++-- nova/tests/test_image.py | 2 ++ nova/tests/test_xenapi.py | 1 - 5 files changed, 13 insertions(+), 4 deletions(-) diff --git a/nova/api/direct.py b/nova/api/direct.py index 139c46d63..fdd2943d2 100644 --- a/nova/api/direct.py +++ b/nova/api/direct.py @@ -48,6 +48,7 @@ import nova.api.openstack.wsgi # Global storage for registering modules. ROUTES = {} + def register_service(path, handle): """Register a service handle at a given path. diff --git a/nova/api/openstack/common.py b/nova/api/openstack/common.py index 715b9e4a4..4548c2c75 100644 --- a/nova/api/openstack/common.py +++ b/nova/api/openstack/common.py @@ -154,7 +154,8 @@ def remove_version_from_href(href): """ parsed_url = urlparse.urlsplit(href) - new_path = re.sub(r'^/v[0-9]+\.[0-9]+(/|$)', r'\1', parsed_url.path, count=1) + new_path = re.sub(r'^/v[0-9]+\.[0-9]+(/|$)', r'\1', parsed_url.path, + count=1) if new_path == parsed_url.path: msg = _('href %s does not contain version') % href diff --git a/nova/db/sqlalchemy/api.py b/nova/db/sqlalchemy/api.py index ce12ba4e0..f469dc0e5 100644 --- a/nova/db/sqlalchemy/api.py +++ b/nova/db/sqlalchemy/api.py @@ -1426,9 +1426,14 @@ def instance_action_create(context, values): def instance_get_actions(context, instance_id): """Return the actions associated to the given instance id""" session = get_session() + + if utils.is_uuid_like(instance_id): + instance = instance_get_by_uuid(context, instance_id, session) + instance_id = instance.id + return session.query(models.InstanceActions).\ filter_by(instance_id=instance_id).\ - all() + all() ################### @@ -3301,7 +3306,8 @@ def instance_type_extra_specs_delete(context, instance_type_id, key): @require_context -def instance_type_extra_specs_get_item(context, instance_type_id, key, session=None): +def instance_type_extra_specs_get_item(context, instance_type_id, key, + session=None): if not session: session = get_session() diff --git a/nova/tests/test_image.py b/nova/tests/test_image.py index 5ec8812f3..9680d6f2b 100644 --- a/nova/tests/test_image.py +++ b/nova/tests/test_image.py @@ -22,6 +22,7 @@ from nova import exception from nova import test import nova.image + class _ImageTestCase(test.TestCase): def setUp(self): super(_ImageTestCase, self).setUp() @@ -126,6 +127,7 @@ class _ImageTestCase(test.TestCase): index = self.image_service.index(self.context) self.assertEquals(len(index), 0) + class FakeImageTestCase(_ImageTestCase): def setUp(self): super(FakeImageTestCase, self).setUp() diff --git a/nova/tests/test_xenapi.py b/nova/tests/test_xenapi.py index 8048e5341..dfc1eeb0a 100644 --- a/nova/tests/test_xenapi.py +++ b/nova/tests/test_xenapi.py @@ -767,7 +767,6 @@ class XenAPIMigrateInstance(test.TestCase): conn = xenapi_conn.get_connection(False) conn.migrate_disk_and_power_off(instance, '127.0.0.1') - def test_revert_migrate(self): instance = db.instance_create(self.context, self.values) self.called = False -- cgit From 9633e9877c7836c18c30b51c8494abfb025e64ca Mon Sep 17 00:00:00 2001 From: Rick Harris Date: Fri, 5 Aug 2011 22:14:15 +0000 Subject: Adding flag around image-create for v1.0 --- nova/api/openstack/__init__.py | 3 +++ nova/api/openstack/images.py | 6 ++++++ nova/tests/api/openstack/test_images.py | 10 ++++++++++ 3 files changed, 19 insertions(+) diff --git a/nova/api/openstack/__init__.py b/nova/api/openstack/__init__.py index d6a98c2cd..4d49df2ad 100644 --- a/nova/api/openstack/__init__.py +++ b/nova/api/openstack/__init__.py @@ -50,6 +50,9 @@ FLAGS = flags.FLAGS flags.DEFINE_bool('allow_admin_api', False, 'When True, this API service will accept admin operations.') +flags.DEFINE_bool('allow_instance_snapshots', + True, + 'When True, this API service will permit instance snapshot operations.') class FaultWrapper(base_wsgi.Middleware): diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index b9bc83fde..7b738e1f3 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -108,6 +108,12 @@ class ControllerV10(Controller): def create(self, req, body): """Snapshot a server instance and save the image.""" + if not FLAGS.allow_instance_snapshots: + LOG.warn(_('Rejecting snapshot request, snapshots currently' + ' disabled')) + msg = _("Instance Snapshots are not permitted at this time.") + raise webob.exc.HTTPBadRequest(explanation=msg) + try: image = body["image"] except (KeyError, TypeError): diff --git a/nova/tests/api/openstack/test_images.py b/nova/tests/api/openstack/test_images.py index 8e2e3f390..38495bbe7 100644 --- a/nova/tests/api/openstack/test_images.py +++ b/nova/tests/api/openstack/test_images.py @@ -1049,6 +1049,16 @@ class ImageControllerWithGlanceServiceTest(test.TestCase): response = req.get_response(fakes.wsgi_app()) self.assertEqual(400, response.status_int) + def test_create_image_snapshots_disabled(self): + self.flags(allow_instance_snapshots=False) + body = dict(image=dict(serverId='123', name='Snapshot 1')) + req = webob.Request.blank('/v1.0/images') + req.method = 'POST' + req.body = json.dumps(body) + req.headers["content-type"] = "application/json" + response = req.get_response(fakes.wsgi_app()) + self.assertEqual(400, response.status_int) + @classmethod def _make_image_fixtures(cls): image_id = 123 -- cgit From 8a87a3ecc0bc9fe524f42950ec0d50124bb5b2b6 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Fri, 5 Aug 2011 15:25:12 -0700 Subject: Pass a real context object into image service calls --- bin/nova-manage | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/bin/nova-manage b/bin/nova-manage index f272351c2..7b4923021 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -1235,11 +1235,12 @@ class ImageCommands(object): is_public, architecture) def _lookup(self, old_image_id): + elevated = context.get_admin_context() try: internal_id = ec2utils.ec2_id_to_id(old_image_id) - image = self.image_service.show(context, internal_id) + image = self.image_service.show(elevated, internal_id) except (exception.InvalidEc2Id, exception.ImageNotFound): - image = self.image_service.show_by_name(context, old_image_id) + image = self.image_service.show_by_name(elevated, old_image_id) return image['id'] def _old_to_new(self, old): -- cgit From c49e99a7fc590c2dde6125843d904895ca8861a3 Mon Sep 17 00:00:00 2001 From: Rick Harris Date: Fri, 5 Aug 2011 22:29:28 +0000 Subject: Disable flag for V1 Openstack API --- nova/api/openstack/servers.py | 6 ++++++ nova/tests/api/openstack/test_server_actions.py | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index 1051ba571..391c7d644 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -691,6 +691,12 @@ class ControllerV11(Controller): def _action_create_image(self, input_dict, req, instance_id): """Snapshot a server instance.""" + if not FLAGS.allow_instance_snapshots: + LOG.warn(_('Rejecting snapshot request, snapshots currently' + ' disabled')) + msg = _("Instance Snapshots are not permitted at this time.") + raise webob.exc.HTTPBadRequest(explanation=msg) + entity = input_dict.get("createImage", {}) try: diff --git a/nova/tests/api/openstack/test_server_actions.py b/nova/tests/api/openstack/test_server_actions.py index 7e24d24fd..bf18bc1b0 100644 --- a/nova/tests/api/openstack/test_server_actions.py +++ b/nova/tests/api/openstack/test_server_actions.py @@ -458,6 +458,7 @@ class ServerActionsTestV11(test.TestCase): self.service.delete_all() self.sent_to_glance = {} fakes.stub_out_glance_add_image(self.stubs, self.sent_to_glance) + self.flags(allow_instance_snapshots=True) def tearDown(self): self.stubs.UnsetAll() @@ -775,6 +776,23 @@ class ServerActionsTestV11(test.TestCase): location = response.headers['Location'] self.assertEqual('http://localhost/v1.1/images/123', location) + def test_create_image_snapshots_disabled(self): + """Don't permit a snapshot if the allow_instance_snapshots flag is + False + """ + self.flags(allow_instance_snapshots=False) + body = { + 'createImage': { + 'name': 'Snapshot 1', + }, + } + req = webob.Request.blank('/v1.1/servers/1/action') + req.method = 'POST' + req.body = json.dumps(body) + req.headers["content-type"] = "application/json" + response = req.get_response(fakes.wsgi_app()) + self.assertEqual(400, response.status_int) + def test_create_image_with_metadata(self): body = { 'createImage': { -- cgit From bdabdd50845279cbca11f510dd5da6a5aa110528 Mon Sep 17 00:00:00 2001 From: Rick Harris Date: Fri, 5 Aug 2011 22:56:08 +0000 Subject: Using decorator for snapshots enabled check --- nova/api/openstack/common.py | 14 ++++++++++++++ nova/api/openstack/images.py | 7 +------ nova/api/openstack/servers.py | 7 +------ 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/nova/api/openstack/common.py b/nova/api/openstack/common.py index 4548c2c75..ec9368140 100644 --- a/nova/api/openstack/common.py +++ b/nova/api/openstack/common.py @@ -15,6 +15,7 @@ # License for the specific language governing permissions and limitations # under the License. +import functools import re import urlparse from xml.dom import minidom @@ -280,3 +281,16 @@ class MetadataXMLSerializer(wsgi.XMLDictSerializer): def default(self, *args, **kwargs): return '' + + +def check_snapshots_enabled(f): + @functools.wraps(f) + def inner(*args, **kwargs): + if not FLAGS.allow_instance_snapshots: + LOG.warn(_('Rejecting snapshot request, snapshots currently' + ' disabled')) + msg = _("Instance Snapshots are not permitted at this time.") + raise webob.exc.HTTPBadRequest(explanation=msg) + return f(*args, **kwargs) + return inner + diff --git a/nova/api/openstack/images.py b/nova/api/openstack/images.py index 7b738e1f3..0aabb9e56 100644 --- a/nova/api/openstack/images.py +++ b/nova/api/openstack/images.py @@ -106,14 +106,9 @@ class Controller(object): class ControllerV10(Controller): """Version 1.0 specific controller logic.""" + @common.check_snapshots_enabled def create(self, req, body): """Snapshot a server instance and save the image.""" - if not FLAGS.allow_instance_snapshots: - LOG.warn(_('Rejecting snapshot request, snapshots currently' - ' disabled')) - msg = _("Instance Snapshots are not permitted at this time.") - raise webob.exc.HTTPBadRequest(explanation=msg) - try: image = body["image"] except (KeyError, TypeError): diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index 391c7d644..4d6518598 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -689,14 +689,9 @@ class ControllerV11(Controller): return webob.Response(status_int=202) + @common.check_snapshots_enabled def _action_create_image(self, input_dict, req, instance_id): """Snapshot a server instance.""" - if not FLAGS.allow_instance_snapshots: - LOG.warn(_('Rejecting snapshot request, snapshots currently' - ' disabled')) - msg = _("Instance Snapshots are not permitted at this time.") - raise webob.exc.HTTPBadRequest(explanation=msg) - entity = input_dict.get("createImage", {}) try: -- cgit From b15535a20b7f717aa23f5bc6d695e574bb86c407 Mon Sep 17 00:00:00 2001 From: Rick Harris Date: Fri, 5 Aug 2011 23:26:08 +0000 Subject: Adding check to stub method --- nova/api/openstack/common.py | 2 +- nova/api/openstack/servers.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/nova/api/openstack/common.py b/nova/api/openstack/common.py index ec9368140..375304930 100644 --- a/nova/api/openstack/common.py +++ b/nova/api/openstack/common.py @@ -289,7 +289,7 @@ def check_snapshots_enabled(f): if not FLAGS.allow_instance_snapshots: LOG.warn(_('Rejecting snapshot request, snapshots currently' ' disabled')) - msg = _("Instance Snapshots are not permitted at this time.") + msg = _("Instance snapshots are not permitted at this time.") raise webob.exc.HTTPBadRequest(explanation=msg) return f(*args, **kwargs) return inner diff --git a/nova/api/openstack/servers.py b/nova/api/openstack/servers.py index 4d6518598..f1a27a98c 100644 --- a/nova/api/openstack/servers.py +++ b/nova/api/openstack/servers.py @@ -240,6 +240,7 @@ class Controller(object): resp.headers['Location'] = image_ref return resp + @common.check_snapshots_enabled def _action_create_image(self, input_dict, req, id): return exc.HTTPNotImplemented() -- cgit From 8c6ccfd51698bffe0d56193bc4137ad80708e6d3 Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Fri, 5 Aug 2011 16:41:03 -0700 Subject: zone_aware_scheduler classes couldn't build instances due to a change to compute api's create_db_entry_for_new_instance call. now passing image argument down to the scheduler and through to the call. updated a existing test to cover this --- nova/compute/api.py | 4 ++++ nova/scheduler/zone_aware_scheduler.py | 3 ++- nova/tests/scheduler/test_zone_aware_scheduler.py | 27 ++++++++++++++++++----- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/nova/compute/api.py b/nova/compute/api.py index 80d54d029..752f29384 100644 --- a/nova/compute/api.py +++ b/nova/compute/api.py @@ -360,6 +360,7 @@ class API(base.Base): instance_type, zone_blob, availability_zone, injected_files, admin_password, + image, instance_id=None, num_instances=1): """Send the run_instance request to the schedulers for processing.""" pid = context.project_id @@ -373,6 +374,7 @@ class API(base.Base): filter_class = 'nova.scheduler.host_filter.InstanceTypeFilter' request_spec = { + 'image': image, 'instance_properties': base_options, 'instance_type': instance_type, 'filter': filter_class, @@ -415,6 +417,7 @@ class API(base.Base): instance_type, zone_blob, availability_zone, injected_files, admin_password, + image, num_instances=num_instances) return base_options['reservation_id'] @@ -463,6 +466,7 @@ class API(base.Base): instance_type, zone_blob, availability_zone, injected_files, admin_password, + image, instance_id=instance_id) return [dict(x.iteritems()) for x in instances] diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index d99d7214c..a47bf7fe7 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -58,12 +58,13 @@ class ZoneAwareScheduler(driver.Scheduler): """Create the requested resource in this Zone.""" host = build_plan_item['hostname'] base_options = request_spec['instance_properties'] + image = request_spec['image'] # TODO(sandy): I guess someone needs to add block_device_mapping # support at some point? Also, OS API has no concept of security # groups. instance = compute_api.API().create_db_entry_for_new_instance(context, - base_options, None, []) + image, base_options, None, []) instance_id = instance['id'] kwargs['instance_id'] = instance_id diff --git a/nova/tests/scheduler/test_zone_aware_scheduler.py b/nova/tests/scheduler/test_zone_aware_scheduler.py index 7833028c3..788efca52 100644 --- a/nova/tests/scheduler/test_zone_aware_scheduler.py +++ b/nova/tests/scheduler/test_zone_aware_scheduler.py @@ -21,7 +21,9 @@ import json import nova.db from nova import exception +from nova import rpc from nova import test +from nova.compute import api as compute_api from nova.scheduler import driver from nova.scheduler import zone_aware_scheduler from nova.scheduler import zone_manager @@ -114,7 +116,7 @@ def fake_provision_resource_from_blob(context, item, instance_id, def fake_decrypt_blob_returns_local_info(blob): - return {'foo': True} # values aren't important. + return {'hostname': 'foooooo'} # values aren't important. def fake_decrypt_blob_returns_child_info(blob): @@ -283,14 +285,29 @@ class ZoneAwareSchedulerTestCase(test.TestCase): global was_called sched = FakeZoneAwareScheduler() was_called = False + + def fake_create_db_entry_for_new_instance(self, context, + image, base_options, security_group, + block_device_mapping, num=1): + global was_called + was_called = True + # return fake instances + return {'id': 1, 'uuid': 'f874093c-7b17-49c0-89c3-22a5348497f9'} + + def fake_rpc_cast(*args, **kwargs): + pass + self.stubs.Set(sched, '_decrypt_blob', fake_decrypt_blob_returns_local_info) - self.stubs.Set(sched, '_provision_resource_locally', - fake_provision_resource_locally) + self.stubs.Set(compute_api.API, + 'create_db_entry_for_new_instance', + fake_create_db_entry_for_new_instance) + self.stubs.Set(rpc, 'cast', fake_rpc_cast) - request_spec = {'blob': "Non-None blob data"} + build_plan_item = {'blob': "Non-None blob data"} + request_spec = {'image': {}, 'instance_properties': {}} - sched._provision_resource_from_blob(None, request_spec, 1, + sched._provision_resource_from_blob(None, build_plan_item, 1, request_spec, {}) self.assertTrue(was_called) -- cgit From 7a5bb39ef11d630df26f2fcfbf249f0c34e9fa55 Mon Sep 17 00:00:00 2001 From: Rick Harris Date: Fri, 5 Aug 2011 18:51:17 -0500 Subject: Pep8 fix --- nova/api/openstack/common.py | 1 - 1 file changed, 1 deletion(-) diff --git a/nova/api/openstack/common.py b/nova/api/openstack/common.py index 375304930..5226cdf9a 100644 --- a/nova/api/openstack/common.py +++ b/nova/api/openstack/common.py @@ -293,4 +293,3 @@ def check_snapshots_enabled(f): raise webob.exc.HTTPBadRequest(explanation=msg) return f(*args, **kwargs) return inner - -- cgit