From a1c499578eebe5946a1d62161fbde0a3fe8c1729 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Mon, 17 Jan 2011 19:40:35 -0500 Subject: [PATCH 001/105] Stubbed-out code for working with provider-firewalls. --- nova/adminclient.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/nova/adminclient.py b/nova/adminclient.py index b2609c8c..90ad4d9d 100644 --- a/nova/adminclient.py +++ b/nova/adminclient.py @@ -190,6 +190,22 @@ class HostInfo(object): setattr(self, name, value) +class SimpleResponse(object): + def __init__(self, connection=None): + self.connection = connection + self.status = None + self.message = '' + + def __repr__(self): + return 'Status:%s' % self.status + + def startElement(self, name, attrs, connection): + return None + + def endElement(self, name, value, connection): + setattr(self, name.lower(), str(value)) + + class NovaAdminClient(object): def __init__( @@ -373,3 +389,8 @@ class NovaAdminClient(object): def get_hosts(self): return self.apiconn.get_list('DescribeHosts', {}, [('item', HostInfo)]) + + def block_ips(self, cidr): + """Block incoming traffic from specified hosts.""" + return self.apiconn.get_object('BlockExternalAddresses', + {'Cidr': cidr}, SimpleResponse) From caa6bce872bfc4bfb1d03d970d22dd1bfe66c3e8 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Wed, 19 Jan 2011 15:16:12 -0500 Subject: [PATCH 002/105] Whitespace (pep8) cleanups. --- nova/adminclient.py | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/nova/adminclient.py b/nova/adminclient.py index 90ad4d9d..0cdb8c6f 100644 --- a/nova/adminclient.py +++ b/nova/adminclient.py @@ -190,20 +190,20 @@ class HostInfo(object): setattr(self, name, value) -class SimpleResponse(object): - def __init__(self, connection=None): - self.connection = connection - self.status = None +class SimpleResponse(object): + def __init__(self, connection=None): + self.connection = connection + self.status = None self.message = '' - - def __repr__(self): - return 'Status:%s' % self.status - - def startElement(self, name, attrs, connection): - return None - - def endElement(self, name, value, connection): - setattr(self, name.lower(), str(value)) + + def __repr__(self): + return 'Status:%s' % self.status + + def startElement(self, name, attrs, connection): + return None + + def endElement(self, name, value, connection): + setattr(self, name.lower(), str(value)) class NovaAdminClient(object): @@ -224,8 +224,7 @@ class NovaAdminClient(object): 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, + region=RegionInfo(None, region, parts['ip']), port=parts['port'], path='/services/Admin', From 4c686217d35740b2e9ca9515ac6f13510fa6c9b4 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Wed, 26 Jan 2011 22:54:39 -0800 Subject: [PATCH 003/105] A couple of bugfixes. --- nova/adminclient.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/nova/adminclient.py b/nova/adminclient.py index 9b43995f..9652dcb9 100644 --- a/nova/adminclient.py +++ b/nova/adminclient.py @@ -230,7 +230,8 @@ class InstanceType(object): class SimpleResponse(object): - def __init__(self): + def __init__(self, connection=None): + self.connection = connection self.status = None self.message = '' From 1ab45721988e4d488bd9c4b8a8936014aeec2783 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Wed, 26 Jan 2011 22:56:34 -0800 Subject: [PATCH 004/105] Apply lp:707675 to this branch to be able to test. --- nova/tests/test_virt.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/nova/tests/test_virt.py b/nova/tests/test_virt.py index 0b9b847a..1008f32a 100644 --- a/nova/tests/test_virt.py +++ b/nova/tests/test_virt.py @@ -221,7 +221,12 @@ class IptablesFirewallTestCase(test.TestCase): self.project = self.manager.create_project('fake', 'fake', 'fake') self.context = context.RequestContext('fake', 'fake') self.network = utils.import_object(FLAGS.network_manager) - self.fw = libvirt_conn.IptablesFirewallDriver() + + class FakeLibvirtConnection(object): + pass + self.fake_libvirt_connection = FakeLibvirtConnection() + self.fw = libvirt_conn.IptablesFirewallDriver( + get_connection=lambda: self.fake_libvirt_connection) def tearDown(self): self.manager.delete_project(self.project) From 66decd17af0c64c6160f5920ff08b70d4bc4dc28 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Tue, 5 Apr 2011 15:17:17 -0400 Subject: [PATCH 005/105] Remove file leftover from conflict. --- nova/adminclient.py.THIS | 451 --------------------------------------- 1 file changed, 451 deletions(-) delete mode 100644 nova/adminclient.py.THIS diff --git a/nova/adminclient.py.THIS b/nova/adminclient.py.THIS deleted file mode 100644 index c96d6e1f..00000000 --- a/nova/adminclient.py.THIS +++ /dev/null @@ -1,451 +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 - -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** - - * Disk stats - * Running Instances - * Memory stats - * CPU stats - * Network address info - * Firewall info - * Bridge and devices - - """ - - def __init__(self, connection=None): - self.connection = connection - self.hostname = None - - 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): - setattr(self, 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 SimpleResponse(object): - def __init__(self, connection=None): - self.connection = connection - self.status = None - self.message = '' - - def __repr__(self): - return 'Status:%s' % self.status - - def startElement(self, name, attrs, connection): - return None - - def endElement(self, name, value, connection): - setattr(self, name.lower(), 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.""" - try: - return self.apiconn.get_object('DescribeUser', - {'Name': name}, - UserInfo) - except boto.exception.BotoServerError, e: - if e.status == 400 and e.error_code == 'NotFound': - return None - raise - - 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 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)]) - - def block_ips(self, cidr): - """Block incoming traffic from specified hosts.""" - return self.apiconn.get_object('BlockExternalAddresses', - {'Cidr': cidr}, SimpleResponse) From c5b600b95fa04dba70a29933d6cc3e2e25718863 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Tue, 5 Apr 2011 20:03:29 -0400 Subject: [PATCH 006/105] Testing for iptables manager changes. --- nova/tests/test_network.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/nova/tests/test_network.py b/nova/tests/test_network.py index 77f6aaff..a67c846d 100644 --- a/nova/tests/test_network.py +++ b/nova/tests/test_network.py @@ -164,3 +164,33 @@ class IptablesManagerTestCase(test.TestCase): self.assertTrue('-A %s -j run_tests.py-%s' \ % (chain, chain) in new_lines, "Built-in chain %s not wrapped" % (chain,)) + + def test_will_empty_chain(self): + self.manager.ipv4['filter'].add_chain('test-chain') + self.manager.ipv4['filter'].add_rule('test-chain', '-j DROP') + old_count = len(self.manager.ipv4['filter'].rules) + self.manager.ipv4['filter'].empty_chain('test-chain') + self.assertEqual(old_count - 1, len(self.manager.ipv4['filter'].rules)) + + def test_will_empty_unwrapped_chain(self): + self.manager.ipv4['filter'].add_chain('test-chain', wrap=False) + self.manager.ipv4['filter'].add_rule('test-chain', '-j DROP', + wrap=False) + old_count = len(self.manager.ipv4['filter'].rules) + self.manager.ipv4['filter'].empty_chain('test-chain', wrap=False) + self.assertEqual(old_count - 1, len(self.manager.ipv4['filter'].rules)) + + def test_will_not_empty_wrapped_when_unwrapped(self): + self.manager.ipv4['filter'].add_chain('test-chain') + self.manager.ipv4['filter'].add_rule('test-chain', '-j DROP') + old_count = len(self.manager.ipv4['filter'].rules) + self.manager.ipv4['filter'].empty_chain('test-chain', wrap=False) + self.assertEqual(old_count, len(self.manager.ipv4['filter'].rules)) + + def test_will_not_empty_unwrapped_when_wrapped(self): + self.manager.ipv4['filter'].add_chain('test-chain', wrap=False) + self.manager.ipv4['filter'].add_rule('test-chain', '-j DROP', + wrap=False) + old_count = len(self.manager.ipv4['filter'].rules) + self.manager.ipv4['filter'].empty_chain('test-chain') + self.assertEqual(old_count, len(self.manager.ipv4['filter'].rules)) From 1b5837cdd4404bb37cd4e0fc8c8aae39e413e7be Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Thu, 7 Apr 2011 01:42:49 -0400 Subject: [PATCH 007/105] test provider fw rules at the virt/ipteables layer. lowercase protocol names in admin api to match what the firewall driver expects. add provider fw rule chain in iptables6 as well. fix a couple of small typos and copy-paste errors. --- nova/tests/test_virt.py | 65 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/nova/tests/test_virt.py b/nova/tests/test_virt.py index 958c8e3e..34ecd09c 100644 --- a/nova/tests/test_virt.py +++ b/nova/tests/test_virt.py @@ -566,7 +566,9 @@ class IptablesFirewallTestCase(test.TestCase): self.network = utils.import_object(FLAGS.network_manager) class FakeLibvirtConnection(object): - pass + def nwfilterDefineXML(*args, **kwargs): + """setup_basic_rules in nwfilter calls this.""" + pass self.fake_libvirt_connection = FakeLibvirtConnection() self.fw = libvirt_conn.IptablesFirewallDriver( get_connection=lambda: self.fake_libvirt_connection) @@ -728,6 +730,67 @@ class IptablesFirewallTestCase(test.TestCase): "TCP port 80/81 acceptance rule wasn't added") db.instance_destroy(admin_ctxt, instance_ref['id']) + def test_provider_firewall_rules(self): + # keep from changing state of actual firewall + #def fake_function(*args, **kwargs): + # pass + #self.fw.iptables.apply = fake_function + #self.fw.nwfilter.setup_basic_filtering = fake_function + + # setup basic instance data + instance_ref = db.instance_create(self.context, + {'user_id': 'fake', + 'project_id': 'fake', + 'mac_address': '56:12:12:12:12:12'}) + ip = '10.11.12.13' + network_ref = db.project_get_network(self.context, 'fake') + admin_ctxt = context.get_admin_context() + fixed_ip = {'address': ip, 'network_id': network_ref['id']} + db.fixed_ip_create(admin_ctxt, fixed_ip) + db.fixed_ip_update(admin_ctxt, ip, {'allocated': True, + 'instance_id': instance_ref['id']}) + # FRAGILE: peeks at how the firewall names chains + chain_name = 'inst-%s' % instance_ref['id'] + + # create a firewall via setup_basic_filtering like libvirt_conn.spawn + # should have a chain with 0 rules + self.fw.setup_basic_filtering(instance_ref, network_info=None) + self.assertTrue('provider' in self.fw.iptables.ipv4['filter'].chains) + rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules + if rule.chain == 'provider'] + self.assertEqual(0, len(rules)) + + # add a rule and send the update message, check for 1 rule + provider_fw0 = db.provider_fw_rule_create(admin_ctxt, + {'protocol': 'tcp', + 'cidr': '10.99.99.99/32', + 'from_port': 1, + 'to_port': 65535}) + self.fw.refresh_provider_fw_rules() + rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules + if rule.chain == 'provider'] + self.assertEqual(1, len(rules)) + + # Add another, refresh, and make sure number of rules goes to two + provider_fw1 = db.provider_fw_rule_create(admin_ctxt, + {'protocol': 'udp', + 'cidr': '10.99.99.99/32', + 'from_port': 1, + 'to_port': 65535}) + self.fw.refresh_provider_fw_rules() + rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules + if rule.chain == 'provider'] + self.assertEqual(2, len(rules)) + + # create the instance filter and make sure it has a jump rule + self.fw.prepare_instance_filter(instance_ref, network_info=None) + self.fw.apply_instance_filter(instance_ref) + inst_rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules + if rule.chain == chain_name] + jump_rules = [rule for rule in inst_rules if '-j' in rule.rule] + prov_rules = [rule for rule in jump_rules if 'provider' in rule.rule] + self.assertEqual(1, len(prov_rules)) + class NWFilterTestCase(test.TestCase): def setUp(self): From 274594323f767c8d6c83171672a7a210aea1a42f Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Thu, 7 Apr 2011 13:22:03 -0400 Subject: [PATCH 008/105] remove unused code. --- nova/tests/test_virt.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/nova/tests/test_virt.py b/nova/tests/test_virt.py index 34ecd09c..7c3dbf65 100644 --- a/nova/tests/test_virt.py +++ b/nova/tests/test_virt.py @@ -731,12 +731,6 @@ class IptablesFirewallTestCase(test.TestCase): db.instance_destroy(admin_ctxt, instance_ref['id']) def test_provider_firewall_rules(self): - # keep from changing state of actual firewall - #def fake_function(*args, **kwargs): - # pass - #self.fw.iptables.apply = fake_function - #self.fw.nwfilter.setup_basic_filtering = fake_function - # setup basic instance data instance_ref = db.instance_create(self.context, {'user_id': 'fake', From e283358ca051dbb02e13b47a8c8ef3ed8d769d5d Mon Sep 17 00:00:00 2001 From: Lorin Hochstein Date: Wed, 25 May 2011 15:48:03 -0400 Subject: [PATCH 009/105] Initial tests --- nova/tests/test_instance_types_metadata.py | 62 ++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 nova/tests/test_instance_types_metadata.py diff --git a/nova/tests/test_instance_types_metadata.py b/nova/tests/test_instance_types_metadata.py new file mode 100644 index 00000000..a22bf2b7 --- /dev/null +++ b/nova/tests/test_instance_types_metadata.py @@ -0,0 +1,62 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2011 University of Southern California +# 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. +""" +Unit Tests for instance types metadata code +""" + + +from nova import test +from nova.db.sqlalchemy.session import get_session +from nova.db.sqlalchemy import models + + +class InstanceTypeMetadataTestCase(test.TestCase): + + def setUp(self): + super(InstanceTypeMetadataTestCase, self).setUp() + values = dict(memory_mb=22000, + vcpus=8, + local_gb=1690, + flavorid=105) + metadata = dict(cpu_arch="x86_64", + cpu_info=dict(model="Nehalem"), + xpu_arch="fermi", + xpus=2, + xpu_info=dict(model="Tesla 2050", gcores="448"), + net_arch="ethernet", + net_mbps=10000) + + metadata_refs = [] + for k,v in metadata.iteritems(): + metadata_ref = models.InstanceTypeMetadata() + metadata_ref['key'] = k + metadata_ref['value'] = v + metadata_refs.append(metadata_ref) + values['metadata'] = metadata_refs + + instance_type_ref = models.InstanceTypes() + instance_type_ref.update(values) + + session = get_session() + with session.begin(): + instance_type_ref.save(session=session) + # Add cg1.4xlarge + + + def test_foo(self): + # Add a new instance type cg1 + # Add the metadata + # Retrieve the metadata + pass From 58da78419204b92c4bf25e5b23038eab699adc9e Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Thu, 26 May 2011 12:09:04 -0400 Subject: [PATCH 010/105] Make a cleaner log message and use [] instead of . to get database fields. --- nova/tests/test_libvirt.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/nova/tests/test_libvirt.py b/nova/tests/test_libvirt.py index 1743b09a..0eaf069f 100644 --- a/nova/tests/test_libvirt.py +++ b/nova/tests/test_libvirt.py @@ -884,10 +884,7 @@ class IptablesFirewallTestCase(test.TestCase): def test_provider_firewall_rules(self): # setup basic instance data - instance_ref = db.instance_create(self.context, - {'user_id': 'fake', - 'project_id': 'fake', - 'mac_address': '56:12:12:12:12:12'}) + instance_ref = self._create_instance_ref() ip = '10.11.12.13' network_ref = db.project_get_network(self.context, 'fake') admin_ctxt = context.get_admin_context() From af891695b017a8151b4044c01c79ac518e62d71c Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Thu, 26 May 2011 12:48:07 -0400 Subject: [PATCH 011/105] Test tweaks. --- nova/tests/test_libvirt.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/nova/tests/test_libvirt.py b/nova/tests/test_libvirt.py index 0eaf069f..bb7c8cf3 100644 --- a/nova/tests/test_libvirt.py +++ b/nova/tests/test_libvirt.py @@ -885,6 +885,7 @@ class IptablesFirewallTestCase(test.TestCase): def test_provider_firewall_rules(self): # setup basic instance data instance_ref = self._create_instance_ref() + nw_info = _create_network_info(1) ip = '10.11.12.13' network_ref = db.project_get_network(self.context, 'fake') admin_ctxt = context.get_admin_context() @@ -897,7 +898,7 @@ class IptablesFirewallTestCase(test.TestCase): # create a firewall via setup_basic_filtering like libvirt_conn.spawn # should have a chain with 0 rules - self.fw.setup_basic_filtering(instance_ref, network_info=None) + self.fw.setup_basic_filtering(instance_ref, network_info=nw_info) self.assertTrue('provider' in self.fw.iptables.ipv4['filter'].chains) rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules if rule.chain == 'provider'] @@ -926,13 +927,17 @@ class IptablesFirewallTestCase(test.TestCase): self.assertEqual(2, len(rules)) # create the instance filter and make sure it has a jump rule - self.fw.prepare_instance_filter(instance_ref, network_info=None) + self.fw.prepare_instance_filter(instance_ref, network_info=nw_info) self.fw.apply_instance_filter(instance_ref) inst_rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules if rule.chain == chain_name] jump_rules = [rule for rule in inst_rules if '-j' in rule.rule] - prov_rules = [rule for rule in jump_rules if 'provider' in rule.rule] - self.assertEqual(1, len(prov_rules)) + provjump_rules = [] + # IptablesTable doesn't make rules unique internally + for rule in jump_rules: + if 'provider' in rule.rule and rule not in provjump_rules: + provjump_rules.append(rule) + self.assertEqual(1, len(provjump_rules)) class NWFilterTestCase(test.TestCase): From 076b9e3b33c5a66e332cd2cc6b36194772029ed0 Mon Sep 17 00:00:00 2001 From: Lorin Hochstein Date: Fri, 27 May 2011 13:10:19 -0400 Subject: [PATCH 012/105] Adding test code --- nova/tests/test_instance_types_metadata.py | 26 +++++++++++++--------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/nova/tests/test_instance_types_metadata.py b/nova/tests/test_instance_types_metadata.py index a22bf2b7..06c11a7c 100644 --- a/nova/tests/test_instance_types_metadata.py +++ b/nova/tests/test_instance_types_metadata.py @@ -16,7 +16,9 @@ Unit Tests for instance types metadata code """ +import nova.db.api +from nova import context from nova import test from nova.db.sqlalchemy.session import get_session from nova.db.sqlalchemy import models @@ -26,15 +28,16 @@ class InstanceTypeMetadataTestCase(test.TestCase): def setUp(self): super(InstanceTypeMetadataTestCase, self).setUp() - values = dict(memory_mb=22000, + values = dict(name="cg1.4xlarge", + memory_mb=22000, vcpus=8, local_gb=1690, flavorid=105) metadata = dict(cpu_arch="x86_64", - cpu_info=dict(model="Nehalem"), + cpu_model="Nehalem", xpu_arch="fermi", xpus=2, - xpu_info=dict(model="Tesla 2050", gcores="448"), + xpu_model="Tesla 2050", net_arch="ethernet", net_mbps=10000) @@ -44,19 +47,22 @@ class InstanceTypeMetadataTestCase(test.TestCase): metadata_ref['key'] = k metadata_ref['value'] = v metadata_refs.append(metadata_ref) - values['metadata'] = metadata_refs + values['meta'] = metadata_refs instance_type_ref = models.InstanceTypes() instance_type_ref.update(values) + session = get_session() with session.begin(): instance_type_ref.save(session=session) - # Add cg1.4xlarge + self.instance_type_id = instance_type_ref.id + def test_instance_type_metadata_get(self): + self.assertEquals( \ + nova.db.api.instance_type_metadata_get(context.get_admin_context(), + self.instance_type_id), + {'foo' : 'bar'}) - def test_foo(self): - # Add a new instance type cg1 - # Add the metadata - # Retrieve the metadata - pass + + \ No newline at end of file From 518b779e8bc74870099bf296e130956a67979a34 Mon Sep 17 00:00:00 2001 From: Lorin Hochstein Date: Fri, 27 May 2011 13:29:51 -0400 Subject: [PATCH 013/105] Added a unit test --- nova/tests/test_instance_types_metadata.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/nova/tests/test_instance_types_metadata.py b/nova/tests/test_instance_types_metadata.py index 06c11a7c..5d8364c3 100644 --- a/nova/tests/test_instance_types_metadata.py +++ b/nova/tests/test_instance_types_metadata.py @@ -16,9 +16,8 @@ Unit Tests for instance types metadata code """ -import nova.db.api - from nova import context +from nova import db from nova import test from nova.db.sqlalchemy.session import get_session from nova.db.sqlalchemy import models @@ -59,10 +58,17 @@ class InstanceTypeMetadataTestCase(test.TestCase): self.instance_type_id = instance_type_ref.id def test_instance_type_metadata_get(self): - self.assertEquals( \ - nova.db.api.instance_type_metadata_get(context.get_admin_context(), - self.instance_type_id), - {'foo' : 'bar'}) + expected_metadata = dict(cpu_arch="x86_64", + cpu_model="Nehalem", + xpu_arch="fermi", + xpus="2", + xpu_model="Tesla 2050", + net_arch="ethernet", + net_mbps="10000") + retrieved_metadata = db.api.instance_type_metadata_get( + context.get_admin_context(), + self.instance_type_id) + self.assertEquals(expected_metadata, retrieved_metadata) \ No newline at end of file From 79c73fbc65334646c8c60d907cbe93fc4b1d8cda Mon Sep 17 00:00:00 2001 From: Lorin Hochstein Date: Fri, 27 May 2011 13:39:37 -0400 Subject: [PATCH 014/105] Added delete instance metadata unit test --- nova/tests/test_instance_types_metadata.py | 25 +++++++++++++++------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/nova/tests/test_instance_types_metadata.py b/nova/tests/test_instance_types_metadata.py index 5d8364c3..c83c5bfc 100644 --- a/nova/tests/test_instance_types_metadata.py +++ b/nova/tests/test_instance_types_metadata.py @@ -47,11 +47,8 @@ class InstanceTypeMetadataTestCase(test.TestCase): metadata_ref['value'] = v metadata_refs.append(metadata_ref) values['meta'] = metadata_refs - instance_type_ref = models.InstanceTypes() instance_type_ref.update(values) - - session = get_session() with session.begin(): instance_type_ref.save(session=session) @@ -65,10 +62,22 @@ class InstanceTypeMetadataTestCase(test.TestCase): xpu_model="Tesla 2050", net_arch="ethernet", net_mbps="10000") - retrieved_metadata = db.api.instance_type_metadata_get( + actual_metadata = db.api.instance_type_metadata_get( context.get_admin_context(), self.instance_type_id) - self.assertEquals(expected_metadata, retrieved_metadata) - - - \ No newline at end of file + self.assertEquals(expected_metadata, actual_metadata) + + def test_instance_type_metadata_delete(self): + expected_metadata = dict(cpu_arch="x86_64", + cpu_model="Nehalem", + xpu_arch="fermi", + xpus="2", + net_arch="ethernet", + net_mbps="10000") + db.api.instance_type_metadata_delete(context.get_admin_context(), + self.instance_type_id, + "xpu_model") + actual_metadata = db.api.instance_type_metadata_get( + context.get_admin_context(), + self.instance_type_id) + self.assertEquals(expected_metadata, actual_metadata) \ No newline at end of file From c02bbf3cc4b5aa83a6fa54a64bf1ddd752394fef Mon Sep 17 00:00:00 2001 From: Lorin Hochstein Date: Fri, 27 May 2011 13:44:40 -0400 Subject: [PATCH 015/105] Added test for instance type metadata update --- nova/tests/test_instance_types_metadata.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/nova/tests/test_instance_types_metadata.py b/nova/tests/test_instance_types_metadata.py index c83c5bfc..d72a72e0 100644 --- a/nova/tests/test_instance_types_metadata.py +++ b/nova/tests/test_instance_types_metadata.py @@ -80,4 +80,24 @@ class InstanceTypeMetadataTestCase(test.TestCase): actual_metadata = db.api.instance_type_metadata_get( context.get_admin_context(), self.instance_type_id) - self.assertEquals(expected_metadata, actual_metadata) \ No newline at end of file + self.assertEquals(expected_metadata, actual_metadata) + + def test_instance_type_metadata_update(self): + expected_metadata = dict(cpu_arch="x86_64", + cpu_model="Sandy Bridge", + xpu_arch="fermi", + xpus="2", + xpu_model="Tesla 2050", + net_arch="ethernet", + net_mbps="10000") + db.api.instance_type_metadata_update_or_create( + context.get_admin_context(), + self.instance_type_id, + dict(cpu_model="Sandy Bridge")) + actual_metadata = db.api.instance_type_metadata_get( + context.get_admin_context(), + self.instance_type_id) + self.assertEquals(expected_metadata, actual_metadata) + + + \ No newline at end of file From 3c63c854129ff069645ba356a3a6fb8ed13e931f Mon Sep 17 00:00:00 2001 From: Lorin Hochstein Date: Fri, 27 May 2011 13:54:19 -0400 Subject: [PATCH 016/105] Added test for instance type metadata create --- nova/tests/test_instance_types_metadata.py | 44 ++++++++++++++-------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/nova/tests/test_instance_types_metadata.py b/nova/tests/test_instance_types_metadata.py index d72a72e0..085a951a 100644 --- a/nova/tests/test_instance_types_metadata.py +++ b/nova/tests/test_instance_types_metadata.py @@ -36,10 +36,7 @@ class InstanceTypeMetadataTestCase(test.TestCase): cpu_model="Nehalem", xpu_arch="fermi", xpus=2, - xpu_model="Tesla 2050", - net_arch="ethernet", - net_mbps=10000) - + xpu_model="Tesla 2050") metadata_refs = [] for k,v in metadata.iteritems(): metadata_ref = models.InstanceTypeMetadata() @@ -54,14 +51,18 @@ class InstanceTypeMetadataTestCase(test.TestCase): instance_type_ref.save(session=session) self.instance_type_id = instance_type_ref.id + def tearDown(self): + # Remove the instance from the database + db.api.instance_type_purge(context.get_admin_context(), "cg1.4xlarge") + super(InstanceTypeMetadataTestCase, self).tearDown() + + def test_instance_type_metadata_get(self): expected_metadata = dict(cpu_arch="x86_64", cpu_model="Nehalem", xpu_arch="fermi", xpus="2", - xpu_model="Tesla 2050", - net_arch="ethernet", - net_mbps="10000") + xpu_model="Tesla 2050") actual_metadata = db.api.instance_type_metadata_get( context.get_admin_context(), self.instance_type_id) @@ -71,9 +72,7 @@ class InstanceTypeMetadataTestCase(test.TestCase): expected_metadata = dict(cpu_arch="x86_64", cpu_model="Nehalem", xpu_arch="fermi", - xpus="2", - net_arch="ethernet", - net_mbps="10000") + xpus="2") db.api.instance_type_metadata_delete(context.get_admin_context(), self.instance_type_id, "xpu_model") @@ -87,9 +86,7 @@ class InstanceTypeMetadataTestCase(test.TestCase): cpu_model="Sandy Bridge", xpu_arch="fermi", xpus="2", - xpu_model="Tesla 2050", - net_arch="ethernet", - net_mbps="10000") + xpu_model="Tesla 2050") db.api.instance_type_metadata_update_or_create( context.get_admin_context(), self.instance_type_id, @@ -98,6 +95,21 @@ class InstanceTypeMetadataTestCase(test.TestCase): context.get_admin_context(), self.instance_type_id) self.assertEquals(expected_metadata, actual_metadata) - - - \ No newline at end of file + + def test_instance_type_metadata_create(self): + expected_metadata = dict(cpu_arch="x86_64", + cpu_model="Nehalem", + xpu_arch="fermi", + xpus="2", + xpu_model="Tesla 2050", + net_arch="ethernet", + net_mbps="10000") + db.api.instance_type_metadata_update_or_create( + context.get_admin_context(), + self.instance_type_id, + dict(net_arch="ethernet", + net_mbps=10000)) + actual_metadata = db.api.instance_type_metadata_get( + context.get_admin_context(), + self.instance_type_id) + self.assertEquals(expected_metadata, actual_metadata) From 9a3e0294bfd58ca7d3f49d6d51afbef7dff780eb Mon Sep 17 00:00:00 2001 From: Lorin Hochstein Date: Fri, 27 May 2011 14:20:08 -0400 Subject: [PATCH 017/105] Modified instance_type_create to take metadata --- nova/tests/test_instance_types_metadata.py | 23 +++++++--------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/nova/tests/test_instance_types_metadata.py b/nova/tests/test_instance_types_metadata.py index 085a951a..5263b1cb 100644 --- a/nova/tests/test_instance_types_metadata.py +++ b/nova/tests/test_instance_types_metadata.py @@ -27,6 +27,7 @@ class InstanceTypeMetadataTestCase(test.TestCase): def setUp(self): super(InstanceTypeMetadataTestCase, self).setUp() + self.context = context.get_admin_context() values = dict(name="cg1.4xlarge", memory_mb=22000, vcpus=8, @@ -36,27 +37,17 @@ class InstanceTypeMetadataTestCase(test.TestCase): cpu_model="Nehalem", xpu_arch="fermi", xpus=2, - xpu_model="Tesla 2050") - metadata_refs = [] - for k,v in metadata.iteritems(): - metadata_ref = models.InstanceTypeMetadata() - metadata_ref['key'] = k - metadata_ref['value'] = v - metadata_refs.append(metadata_ref) - values['meta'] = metadata_refs - instance_type_ref = models.InstanceTypes() - instance_type_ref.update(values) - session = get_session() - with session.begin(): - instance_type_ref.save(session=session) - self.instance_type_id = instance_type_ref.id + xpu_model="Tesla 2050") + values['meta'] = metadata + ref = db.api.instance_type_create(self.context, + values) + self.instance_type_id = ref.id def tearDown(self): - # Remove the instance from the database + # Remove the instance type from the database db.api.instance_type_purge(context.get_admin_context(), "cg1.4xlarge") super(InstanceTypeMetadataTestCase, self).tearDown() - def test_instance_type_metadata_get(self): expected_metadata = dict(cpu_arch="x86_64", cpu_model="Nehalem", From 5a2a97874f031eb2e08d8ba1be9b5175a164743c Mon Sep 17 00:00:00 2001 From: Lorin Hochstein Date: Fri, 27 May 2011 14:29:23 -0400 Subject: [PATCH 018/105] Fixing pep8 problems --- nova/tests/test_instance_types_metadata.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/nova/tests/test_instance_types_metadata.py b/nova/tests/test_instance_types_metadata.py index 5263b1cb..1c418588 100644 --- a/nova/tests/test_instance_types_metadata.py +++ b/nova/tests/test_instance_types_metadata.py @@ -24,7 +24,7 @@ from nova.db.sqlalchemy import models class InstanceTypeMetadataTestCase(test.TestCase): - + def setUp(self): super(InstanceTypeMetadataTestCase, self).setUp() self.context = context.get_admin_context() @@ -42,12 +42,12 @@ class InstanceTypeMetadataTestCase(test.TestCase): ref = db.api.instance_type_create(self.context, values) self.instance_type_id = ref.id - + def tearDown(self): # Remove the instance type from the database db.api.instance_type_purge(context.get_admin_context(), "cg1.4xlarge") super(InstanceTypeMetadataTestCase, self).tearDown() - + def test_instance_type_metadata_get(self): expected_metadata = dict(cpu_arch="x86_64", cpu_model="Nehalem", @@ -58,20 +58,20 @@ class InstanceTypeMetadataTestCase(test.TestCase): context.get_admin_context(), self.instance_type_id) self.assertEquals(expected_metadata, actual_metadata) - + def test_instance_type_metadata_delete(self): expected_metadata = dict(cpu_arch="x86_64", cpu_model="Nehalem", xpu_arch="fermi", xpus="2") - db.api.instance_type_metadata_delete(context.get_admin_context(), + db.api.instance_type_metadata_delete(context.get_admin_context(), self.instance_type_id, "xpu_model") actual_metadata = db.api.instance_type_metadata_get( context.get_admin_context(), self.instance_type_id) self.assertEquals(expected_metadata, actual_metadata) - + def test_instance_type_metadata_update(self): expected_metadata = dict(cpu_arch="x86_64", cpu_model="Sandy Bridge", @@ -86,13 +86,13 @@ class InstanceTypeMetadataTestCase(test.TestCase): context.get_admin_context(), self.instance_type_id) self.assertEquals(expected_metadata, actual_metadata) - + def test_instance_type_metadata_create(self): expected_metadata = dict(cpu_arch="x86_64", cpu_model="Nehalem", xpu_arch="fermi", xpus="2", - xpu_model="Tesla 2050", + xpu_model="Tesla 2050", net_arch="ethernet", net_mbps="10000") db.api.instance_type_metadata_update_or_create( From 9b0241441af6dc03c47fd844219698b98189f1b1 Mon Sep 17 00:00:00 2001 From: Chuck Short Date: Mon, 6 Jun 2011 15:32:48 -0400 Subject: [PATCH 019/105] Remove ipy from nova-manage and use netaddr --- bin/nova-manage | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bin/nova-manage b/bin/nova-manage index b0cd343f..5ac0b8a0 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -56,11 +56,11 @@ import gettext import glob import json +import netaddr import os import sys import time -import IPy # If ../nova/__init__.py exists, add ../ to Python search path, so that # it will override what happens to be installed in /usr/(local/)lib/python... @@ -513,7 +513,7 @@ class FloatingIpCommands(object): def create(self, host, range): """Creates floating ips for host by range arguments: host ip_range""" - for address in IPy.IP(range): + for address in netaddr.IPRange(range): db.floating_ip_create(context.get_admin_context(), {'address': str(address), 'host': host}) @@ -521,7 +521,7 @@ class FloatingIpCommands(object): def delete(self, ip_range): """Deletes floating ips by range arguments: range""" - for address in IPy.IP(ip_range): + for address in netaddr.IPRange(ip_range): db.floating_ip_destroy(context.get_admin_context(), str(address)) From 7da398be120870e9d3e433aae0157f48d1527d21 Mon Sep 17 00:00:00 2001 From: Chuck Short Date: Mon, 6 Jun 2011 15:34:51 -0400 Subject: [PATCH 020/105] Remove ipy from network code and replace with netaddr --- nova/tests/test_flat_network.py | 6 +++--- nova/tests/test_vlan_network.py | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/nova/tests/test_flat_network.py b/nova/tests/test_flat_network.py index dcc617e2..8544019c 100644 --- a/nova/tests/test_flat_network.py +++ b/nova/tests/test_flat_network.py @@ -18,7 +18,7 @@ """ Unit Tests for flat network code """ -import IPy +import netaddr import os import unittest @@ -45,8 +45,8 @@ class FlatNetworkTestCase(base.NetworkTestCase): self.context._project = self.projects[0] self.context.project_id = self.projects[0].id - pubnet = IPy.IP(flags.FLAGS.floating_range) - address = str(pubnet[0]) + pubnet = netaddr.IPRange(flags.FLAGS.floating_range) + address = str(list(pubnet)[0]) try: db.floating_ip_get_by_address(context.get_admin_context(), address) except exception.NotFound: diff --git a/nova/tests/test_vlan_network.py b/nova/tests/test_vlan_network.py index 063b8183..a1c8ab11 100644 --- a/nova/tests/test_vlan_network.py +++ b/nova/tests/test_vlan_network.py @@ -18,7 +18,7 @@ """ Unit Tests for vlan network code """ -import IPy +import netaddr import os from nova import context @@ -44,8 +44,8 @@ class VlanNetworkTestCase(base.NetworkTestCase): # TODO(vish): better way of adding floating ips self.context._project = self.projects[0] self.context.project_id = self.projects[0].id - pubnet = IPy.IP(flags.FLAGS.floating_range) - address = str(pubnet[0]) + pubnet = netaddr.IPNetwork(flags.FLAGS.floating_range) + address = str(list(pubnet)[0]) try: db.floating_ip_get_by_address(context.get_admin_context(), address) except exception.NotFound: From e5b4bb6b119d725046a12ba4fb605eabc4bcfaf2 Mon Sep 17 00:00:00 2001 From: Chuck Short Date: Mon, 6 Jun 2011 17:03:50 -0400 Subject: [PATCH 021/105] Convert stray import IPy --- nova/tests/test_network.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/tests/test_network.py b/nova/tests/test_network.py index 77f6aaff..da92f206 100644 --- a/nova/tests/test_network.py +++ b/nova/tests/test_network.py @@ -18,7 +18,7 @@ """ Unit Tests for network code """ -import IPy +import netaddr import os from nova import test From 24ead0e03877c1d40d67714d97c2d9f790b17ac9 Mon Sep 17 00:00:00 2001 From: Chuck Short Date: Tue, 7 Jun 2011 10:39:30 -0400 Subject: [PATCH 022/105] Use IPNetwork rather than IPRange --- bin/nova-manage | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/nova-manage b/bin/nova-manage index 5ac0b8a0..1f8ccf26 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -513,7 +513,7 @@ class FloatingIpCommands(object): def create(self, host, range): """Creates floating ips for host by range arguments: host ip_range""" - for address in netaddr.IPRange(range): + for address in netaddr.IPNetwork(range): db.floating_ip_create(context.get_admin_context(), {'address': str(address), 'host': host}) @@ -521,7 +521,7 @@ class FloatingIpCommands(object): def delete(self, ip_range): """Deletes floating ips by range arguments: range""" - for address in netaddr.IPRange(ip_range): + for address in netaddr.IPNetwork(ip_range): db.floating_ip_destroy(context.get_admin_context(), str(address)) From 7612141d8fd7509d2db95d3918b1b4705bd94793 Mon Sep 17 00:00:00 2001 From: Johannes Erdfelt Date: Thu, 9 Jun 2011 20:11:55 +0000 Subject: [PATCH 023/105] Record architecture of image for matching to agent build later. Add code to automatically update agent running on instance on instance creation. --- bin/nova-manage | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/bin/nova-manage b/bin/nova-manage index 0147ae21..c004a36c 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -1082,6 +1082,50 @@ class ImageCommands(object): self._convert_images(machine_images) +class AgentBuildCommands(object): + """Class for managing agent builds.""" + + def create(self, os, architecture, version, url, md5hash, hypervisor='xen'): + """creates a new agent build + arguments: os architecture version url md5hash [hypervisor='xen']""" + ctxt = context.get_admin_context() + agent_build = db.agent_build_create(ctxt, + {'hypervisor': hypervisor, + 'os': os, + 'architecture': architecture, + 'version': version, + 'url': url, + 'md5hash': md5hash}) + + def delete(self, os, architecture, hypervisor='xen'): + """deletes an existing agent build + arguments: os architecture [hypervisor='xen']""" + ctxt = context.get_admin_context() + agent_build_ref = db.agent_build_get_by_triple(ctxt, + hypervisor, os, architecture) + db.agent_build_destroy(ctxt, agent_build_ref['id']) + + def list(self): + """lists all agent builds + arguments: """ + # TODO(johannes.erdfelt): Make the output easier to read + ctxt = context.get_admin_context() + for agent_build in db.agent_build_get_all(ctxt): + print agent_build.hypervisor, agent_build.os, agent_build.architecture, agent_build.version, agent_build.url, agent_build.md5hash + + def modify(self, os, architecture, version, url, md5hash, hypervisor='xen'): + """update an existing agent build + arguments: os architecture version url md5hash [hypervisor='xen'] + """ + ctxt = context.get_admin_context() + agent_build_ref = db.agent_build_get_by_triple(ctxt, + hypervisor, os, architecture) + db.agent_build_update(ctxt, agent_build_ref['id'], + {'version': version, + 'url': url, + 'md5hash': md5hash}) + + class ConfigCommands(object): """Class for exposing the flags defined by flag_file(s).""" @@ -1094,6 +1138,7 @@ class ConfigCommands(object): CATEGORIES = [ ('account', AccountCommands), + ('agent', AgentBuildCommands), ('config', ConfigCommands), ('db', DbCommands), ('fixed', FixedIpCommands), From 11e295b8cb93a1eb1c7151e11518ba6c95de7a14 Mon Sep 17 00:00:00 2001 From: Johannes Erdfelt Date: Thu, 9 Jun 2011 22:04:32 +0000 Subject: [PATCH 024/105] Add test for agent update --- nova/tests/test_compute.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/nova/tests/test_compute.py b/nova/tests/test_compute.py index b4ac2dbc..dd06e571 100644 --- a/nova/tests/test_compute.py +++ b/nova/tests/test_compute.py @@ -266,6 +266,14 @@ class ComputeTestCase(test.TestCase): "File Contents") self.compute.terminate_instance(self.context, instance_id) + def test_agent_update(self): + """Ensure instance can have its agent updated""" + instance_id = self._create_instance() + self.compute.run_instance(self.context, instance_id) + self.compute.agent_update(self.context, instance_id, + 'http://127.0.0.1/agent', '00112233445566778899aabbccddeeff') + self.compute.terminate_instance(self.context, instance_id) + def test_snapshot(self): """Ensure instance can be snapshotted""" instance_id = self._create_instance() From 4c3a63737af8cb78ee74f8ee9e62c3cdcb696c18 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Sat, 11 Jun 2011 15:14:46 -0400 Subject: [PATCH 025/105] pep 8 whitespace fix. --- nova/tests/test_libvirt.py | 1 - 1 file changed, 1 deletion(-) diff --git a/nova/tests/test_libvirt.py b/nova/tests/test_libvirt.py index 07c8e81f..ee94d3c1 100644 --- a/nova/tests/test_libvirt.py +++ b/nova/tests/test_libvirt.py @@ -1058,7 +1058,6 @@ class IptablesFirewallTestCase(test.TestCase): db.instance_destroy(admin_ctxt, instance_ref['id']) - def test_provider_firewall_rules(self): # setup basic instance data instance_ref = self._create_instance_ref() From 2cf42caded6c6a8f693459a6a3105ff2c0d8d510 Mon Sep 17 00:00:00 2001 From: Johannes Erdfelt Date: Wed, 15 Jun 2011 14:41:09 +0000 Subject: [PATCH 026/105] PEP8 cleanups --- bin/nova-manage | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bin/nova-manage b/bin/nova-manage index c004a36c..62eb8bf1 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -1085,7 +1085,8 @@ class ImageCommands(object): class AgentBuildCommands(object): """Class for managing agent builds.""" - def create(self, os, architecture, version, url, md5hash, hypervisor='xen'): + def create(self, os, architecture, version, url, md5hash, + hypervisor='xen'): """creates a new agent build arguments: os architecture version url md5hash [hypervisor='xen']""" ctxt = context.get_admin_context() From 36f2848b4f63aa051647c426b3d4cdcd5e73370b Mon Sep 17 00:00:00 2001 From: Johannes Erdfelt Date: Wed, 15 Jun 2011 15:21:20 +0000 Subject: [PATCH 027/105] Print list of agent builds a bit prettier --- bin/nova-manage | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/bin/nova-manage b/bin/nova-manage index 62eb8bf1..184d1d73 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -1106,15 +1106,34 @@ class AgentBuildCommands(object): hypervisor, os, architecture) db.agent_build_destroy(ctxt, agent_build_ref['id']) - def list(self): + def list(self, hypervisor=None): """lists all agent builds arguments: """ - # TODO(johannes.erdfelt): Make the output easier to read + fmt = "%-10s %-8s %12s %s" ctxt = context.get_admin_context() + by_hypervisor = {} for agent_build in db.agent_build_get_all(ctxt): - print agent_build.hypervisor, agent_build.os, agent_build.architecture, agent_build.version, agent_build.url, agent_build.md5hash + buildlist = by_hypervisor.get(agent_build.hypervisor) + if not buildlist: + buildlist = by_hypervisor[agent_build.hypervisor] = [] - def modify(self, os, architecture, version, url, md5hash, hypervisor='xen'): + buildlist.append(agent_build) + + for key, buildlist in by_hypervisor.iteritems(): + if hypervisor and key != hypervisor: + continue + + print "Hypervisor: %s" % key + print fmt % ('-' * 10, '-' * 8, '-' * 12, '-' * 32) + for agent_build in buildlist: + print fmt % (agent_build.os, agent_build.architecture, + agent_build.version, agent_build.md5hash) + print ' %s' % agent_build.url + + print + + def modify(self, os, architecture, version, url, md5hash, + hypervisor='xen'): """update an existing agent build arguments: os architecture version url md5hash [hypervisor='xen'] """ From 266b876efaa3d6e94302bc30a951755af5e28558 Mon Sep 17 00:00:00 2001 From: Rick Harris Date: Wed, 15 Jun 2011 21:12:37 +0000 Subject: [PATCH 028/105] Prep-work to begin on reroute_compute --- nova/scheduler/api.py | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/nova/scheduler/api.py b/nova/scheduler/api.py index ffe59d2c..28410f53 100644 --- a/nova/scheduler/api.py +++ b/nova/scheduler/api.py @@ -200,9 +200,27 @@ class RedirectResult(exception.Error): class reroute_compute(object): - """Decorator used to indicate that the method should - delegate the call the child zones if the db query - can't find anything.""" + """ + reroute_compute is responsible for trying to lookup a resource in the + current zone and if it's not found there, delegating the call to the + child zones. + + Since reroute_compute will be making 'cross-zone' calls, the ID for the + object must come in as a UUID-- if we receive an integer ID, we bail. + + The steps involved are: + + 1. Validate that item_id is UUID like + + 2. Lookup item by UUID in the zone local database + + 3. If the item was found, then extract integer ID, and pass that to + the wrapped method. (This ensures that zone-local code can + continue to use integer IDs). + + 4. If the item was not found, we delgate the call to a child zone + using the UUID. + """ def __init__(self, method_name): self.method_name = method_name From 0267e05f1ff77b5ee3df104337104e9a7de6a1c6 Mon Sep 17 00:00:00 2001 From: Rick Harris Date: Wed, 15 Jun 2011 21:50:36 +0000 Subject: [PATCH 029/105] First attempt to rewrite reroute_compute --- nova/scheduler/api.py | 80 +++++++++++++++++++++++++++++++------------ 1 file changed, 59 insertions(+), 21 deletions(-) diff --git a/nova/scheduler/api.py b/nova/scheduler/api.py index 28410f53..0cc8a113 100644 --- a/nova/scheduler/api.py +++ b/nova/scheduler/api.py @@ -24,6 +24,7 @@ from nova import exception from nova import flags from nova import log as logging from nova import rpc +from nova import utils from eventlet import greenpool @@ -224,32 +225,57 @@ class reroute_compute(object): def __init__(self, method_name): self.method_name = method_name + + def _route_local(): + pass + + def _route_to_child_zones(context, collection, item_uuid): + if not FLAGS.enable_zone_routing: + raise InstanceNotFound(instance_id=item_uuid) + + zones = db.zone_get_all(context) + if not zones: + raise InstanceNotFound(instance_id=item_uuid) + + # Ask the children to provide an answer ... + LOG.debug(_("Asking child zones ...")) + result = self._call_child_zones(zones, + wrap_novaclient_function(_issue_novaclient_command, + collection, self.method_name, item_uuid)) + # Scrub the results and raise another exception + # so the API layers can bail out gracefully ... + raise RedirectResult(self.unmarshall_result(result)) + def __call__(self, f): def wrapped_f(*args, **kwargs): - collection, context, item_id = \ + collection, context, item_id_or_uuid = \ self.get_collection_context_and_id(args, kwargs) - try: - # Call the original function ... + + attempt_reroute = False + if utils.is_uuid_like(item_id_or_uuid): + item_uuid = item_id_or_uuid + try: + instance = self.db.instance_get_by_uuid( + context, item_uuid) + except exception.InstanceNotFound, e: + # NOTE(sirp): since a UUID was passed in, we can attempt + # to reroute to a child zone + attempt_reroute = True + LOG.debug(_("Instance %(item_uuid)s not found " + "locally: '%(e)s'" % locals())) + else: + # NOTE(sirp): since we're not re-routing in this case, and we + # we were passed a UUID, we need to replace that UUID with an + # integer ID in the argument list so that the zone-local code + # can continue to use integer IDs. + item_id = instance['id'] + self.replace_uuid_with_id(args, kwargs, replacement_id) + + if attempt_reroute: + self._route_to_child_zones(context, collection, item_uuid) + else: return f(*args, **kwargs) - except exception.InstanceNotFound, e: - LOG.debug(_("Instance %(item_id)s not found " - "locally: '%(e)s'" % locals())) - if not FLAGS.enable_zone_routing: - raise - - zones = db.zone_get_all(context) - if not zones: - raise - - # Ask the children to provide an answer ... - LOG.debug(_("Asking child zones ...")) - result = self._call_child_zones(zones, - wrap_novaclient_function(_issue_novaclient_command, - collection, self.method_name, item_id)) - # Scrub the results and raise another exception - # so the API layers can bail out gracefully ... - raise RedirectResult(self.unmarshall_result(result)) return wrapped_f def _call_child_zones(self, zones, function): @@ -268,6 +294,18 @@ class reroute_compute(object): instance_id = args[2] return ("servers", context, instance_id) + @staticmethod + def replace_uuid_with_id(args, kwargs, replacement_id): + """ + Extracts the UUID parameter from the arg or kwarg list and replaces + it with an integer ID. + """ + if 'instance_id' in kwargs: + kwargs['instance_id'] = replacement_id + elif len(args) > 1: + args.pop(2) + args.insert(2, replacement_id) + def unmarshall_result(self, zone_responses): """Result is a list of responses from each child zone. Each decorator derivation is responsible to turning this From 38249457dbf1b28d194efb5311ce99f9f3f44691 Mon Sep 17 00:00:00 2001 From: Rick Harris Date: Thu, 16 Jun 2011 15:02:18 +0000 Subject: [PATCH 031/105] Small tweaks --- nova/scheduler/api.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/nova/scheduler/api.py b/nova/scheduler/api.py index 0cc8a113..8bf6a159 100644 --- a/nova/scheduler/api.py +++ b/nova/scheduler/api.py @@ -225,10 +225,6 @@ class reroute_compute(object): def __init__(self, method_name): self.method_name = method_name - - def _route_local(): - pass - def _route_to_child_zones(context, collection, item_uuid): if not FLAGS.enable_zone_routing: raise InstanceNotFound(instance_id=item_uuid) @@ -255,8 +251,7 @@ class reroute_compute(object): if utils.is_uuid_like(item_id_or_uuid): item_uuid = item_id_or_uuid try: - instance = self.db.instance_get_by_uuid( - context, item_uuid) + instance = db.instance_get_by_uuid(context, item_uuid) except exception.InstanceNotFound, e: # NOTE(sirp): since a UUID was passed in, we can attempt # to reroute to a child zone @@ -269,10 +264,11 @@ class reroute_compute(object): # integer ID in the argument list so that the zone-local code # can continue to use integer IDs. item_id = instance['id'] - self.replace_uuid_with_id(args, kwargs, replacement_id) + args = list(args) # needs to be mutable to replace + self.replace_uuid_with_id(args, kwargs, item_id) if attempt_reroute: - self._route_to_child_zones(context, collection, item_uuid) + return self._route_to_child_zones(context, collection, item_uuid) else: return f(*args, **kwargs) @@ -303,6 +299,8 @@ class reroute_compute(object): if 'instance_id' in kwargs: kwargs['instance_id'] = replacement_id elif len(args) > 1: + # NOTE(sirp): args comes in as a tuple, so we need to convert it + # to a list to mutate it, and then convert it back to a tuple args.pop(2) args.insert(2, replacement_id) From 4ec4e388a99de1767e3413d57b569b4ca8e320ec Mon Sep 17 00:00:00 2001 From: Johannes Erdfelt Date: Thu, 16 Jun 2011 15:56:06 +0000 Subject: [PATCH 032/105] Clean up docstrings to match HACKING --- bin/nova-manage | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/bin/nova-manage b/bin/nova-manage index 184d1d73..04d4ae48 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -1087,7 +1087,7 @@ class AgentBuildCommands(object): def create(self, os, architecture, version, url, md5hash, hypervisor='xen'): - """creates a new agent build + """Creates a new agent build. arguments: os architecture version url md5hash [hypervisor='xen']""" ctxt = context.get_admin_context() agent_build = db.agent_build_create(ctxt, @@ -1099,7 +1099,7 @@ class AgentBuildCommands(object): 'md5hash': md5hash}) def delete(self, os, architecture, hypervisor='xen'): - """deletes an existing agent build + """Deletes an existing agent build. arguments: os architecture [hypervisor='xen']""" ctxt = context.get_admin_context() agent_build_ref = db.agent_build_get_by_triple(ctxt, @@ -1107,7 +1107,7 @@ class AgentBuildCommands(object): db.agent_build_destroy(ctxt, agent_build_ref['id']) def list(self, hypervisor=None): - """lists all agent builds + """Lists all agent builds. arguments: """ fmt = "%-10s %-8s %12s %s" ctxt = context.get_admin_context() @@ -1134,7 +1134,7 @@ class AgentBuildCommands(object): def modify(self, os, architecture, version, url, md5hash, hypervisor='xen'): - """update an existing agent build + """Update an existing agent build. arguments: os architecture version url md5hash [hypervisor='xen'] """ ctxt = context.get_admin_context() From 711e7633fff1cb5097572bd09493abf61e873658 Mon Sep 17 00:00:00 2001 From: Rick Harris Date: Thu, 16 Jun 2011 17:27:36 +0000 Subject: [PATCH 033/105] Fixing test_servers_by_uuid --- nova/scheduler/api.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/nova/scheduler/api.py b/nova/scheduler/api.py index 8bf6a159..a363a311 100644 --- a/nova/scheduler/api.py +++ b/nova/scheduler/api.py @@ -218,20 +218,20 @@ class reroute_compute(object): 3. If the item was found, then extract integer ID, and pass that to the wrapped method. (This ensures that zone-local code can continue to use integer IDs). - + 4. If the item was not found, we delgate the call to a child zone using the UUID. """ def __init__(self, method_name): self.method_name = method_name - def _route_to_child_zones(context, collection, item_uuid): + def _route_to_child_zones(self, context, collection, item_uuid): if not FLAGS.enable_zone_routing: - raise InstanceNotFound(instance_id=item_uuid) + raise exception.InstanceNotFound(instance_id=item_uuid) zones = db.zone_get_all(context) if not zones: - raise InstanceNotFound(instance_id=item_uuid) + raise exception.InstanceNotFound(instance_id=item_uuid) # Ask the children to provide an answer ... LOG.debug(_("Asking child zones ...")) @@ -247,7 +247,7 @@ class reroute_compute(object): collection, context, item_id_or_uuid = \ self.get_collection_context_and_id(args, kwargs) - attempt_reroute = False + attempt_reroute = False if utils.is_uuid_like(item_id_or_uuid): item_uuid = item_id_or_uuid try: From 4166cf9416d258f1144140bdee24c954bdff509e Mon Sep 17 00:00:00 2001 From: Rick Harris Date: Thu, 16 Jun 2011 17:52:34 +0000 Subject: [PATCH 034/105] PEP8 cleanup. --- nova/scheduler/api.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/nova/scheduler/api.py b/nova/scheduler/api.py index a363a311..6e5471d7 100644 --- a/nova/scheduler/api.py +++ b/nova/scheduler/api.py @@ -259,16 +259,17 @@ class reroute_compute(object): LOG.debug(_("Instance %(item_uuid)s not found " "locally: '%(e)s'" % locals())) else: - # NOTE(sirp): since we're not re-routing in this case, and we - # we were passed a UUID, we need to replace that UUID with an - # integer ID in the argument list so that the zone-local code - # can continue to use integer IDs. + # NOTE(sirp): since we're not re-routing in this case, and + # we we were passed a UUID, we need to replace that UUID + # with an integer ID in the argument list so that the + # zone-local code can continue to use integer IDs. item_id = instance['id'] args = list(args) # needs to be mutable to replace self.replace_uuid_with_id(args, kwargs, item_id) if attempt_reroute: - return self._route_to_child_zones(context, collection, item_uuid) + return self._route_to_child_zones(context, collection, + item_uuid) else: return f(*args, **kwargs) From 2a276dde81b9a638427e25c06436e73dc4b77a06 Mon Sep 17 00:00:00 2001 From: Rick Harris Date: Thu, 16 Jun 2011 14:42:50 -0500 Subject: [PATCH 035/105] Renaming to _build_instance_get --- nova/scheduler/api.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/nova/scheduler/api.py b/nova/scheduler/api.py index 6e5471d7..8ef893be 100644 --- a/nova/scheduler/api.py +++ b/nova/scheduler/api.py @@ -300,8 +300,6 @@ class reroute_compute(object): if 'instance_id' in kwargs: kwargs['instance_id'] = replacement_id elif len(args) > 1: - # NOTE(sirp): args comes in as a tuple, so we need to convert it - # to a list to mutate it, and then convert it back to a tuple args.pop(2) args.insert(2, replacement_id) From 02ced950567c366b04f617ba73d3c05e50795cb3 Mon Sep 17 00:00:00 2001 From: Lorin Hochstein Date: Thu, 16 Jun 2011 16:33:29 -0400 Subject: [PATCH 036/105] Rename: intance_type_metadata -> instance_type_extra_specs --- nova/tests/test_instance_types_metadata.py | 106 --------------------- 1 file changed, 106 deletions(-) delete mode 100644 nova/tests/test_instance_types_metadata.py diff --git a/nova/tests/test_instance_types_metadata.py b/nova/tests/test_instance_types_metadata.py deleted file mode 100644 index 1c418588..00000000 --- a/nova/tests/test_instance_types_metadata.py +++ /dev/null @@ -1,106 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2011 University of Southern California -# 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. -""" -Unit Tests for instance types metadata code -""" - -from nova import context -from nova import db -from nova import test -from nova.db.sqlalchemy.session import get_session -from nova.db.sqlalchemy import models - - -class InstanceTypeMetadataTestCase(test.TestCase): - - def setUp(self): - super(InstanceTypeMetadataTestCase, self).setUp() - self.context = context.get_admin_context() - values = dict(name="cg1.4xlarge", - memory_mb=22000, - vcpus=8, - local_gb=1690, - flavorid=105) - metadata = dict(cpu_arch="x86_64", - cpu_model="Nehalem", - xpu_arch="fermi", - xpus=2, - xpu_model="Tesla 2050") - values['meta'] = metadata - ref = db.api.instance_type_create(self.context, - values) - self.instance_type_id = ref.id - - def tearDown(self): - # Remove the instance type from the database - db.api.instance_type_purge(context.get_admin_context(), "cg1.4xlarge") - super(InstanceTypeMetadataTestCase, self).tearDown() - - def test_instance_type_metadata_get(self): - expected_metadata = dict(cpu_arch="x86_64", - cpu_model="Nehalem", - xpu_arch="fermi", - xpus="2", - xpu_model="Tesla 2050") - actual_metadata = db.api.instance_type_metadata_get( - context.get_admin_context(), - self.instance_type_id) - self.assertEquals(expected_metadata, actual_metadata) - - def test_instance_type_metadata_delete(self): - expected_metadata = dict(cpu_arch="x86_64", - cpu_model="Nehalem", - xpu_arch="fermi", - xpus="2") - db.api.instance_type_metadata_delete(context.get_admin_context(), - self.instance_type_id, - "xpu_model") - actual_metadata = db.api.instance_type_metadata_get( - context.get_admin_context(), - self.instance_type_id) - self.assertEquals(expected_metadata, actual_metadata) - - def test_instance_type_metadata_update(self): - expected_metadata = dict(cpu_arch="x86_64", - cpu_model="Sandy Bridge", - xpu_arch="fermi", - xpus="2", - xpu_model="Tesla 2050") - db.api.instance_type_metadata_update_or_create( - context.get_admin_context(), - self.instance_type_id, - dict(cpu_model="Sandy Bridge")) - actual_metadata = db.api.instance_type_metadata_get( - context.get_admin_context(), - self.instance_type_id) - self.assertEquals(expected_metadata, actual_metadata) - - def test_instance_type_metadata_create(self): - expected_metadata = dict(cpu_arch="x86_64", - cpu_model="Nehalem", - xpu_arch="fermi", - xpus="2", - xpu_model="Tesla 2050", - net_arch="ethernet", - net_mbps="10000") - db.api.instance_type_metadata_update_or_create( - context.get_admin_context(), - self.instance_type_id, - dict(net_arch="ethernet", - net_mbps=10000)) - actual_metadata = db.api.instance_type_metadata_get( - context.get_admin_context(), - self.instance_type_id) - self.assertEquals(expected_metadata, actual_metadata) From 2fb55611baa5b008f592824362423a4dd039bfc4 Mon Sep 17 00:00:00 2001 From: Johannes Erdfelt Date: Fri, 17 Jun 2011 17:32:45 +0000 Subject: [PATCH 037/105] Add some documentation for cmp_version Add test cases for cmp_version --- nova/tests/test_xenapi.py | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/nova/tests/test_xenapi.py b/nova/tests/test_xenapi.py index d1c88287..5504e802 100644 --- a/nova/tests/test_xenapi.py +++ b/nova/tests/test_xenapi.py @@ -36,9 +36,8 @@ from nova.compute import power_state from nova.virt import xenapi_conn from nova.virt.xenapi import fake as xenapi_fake from nova.virt.xenapi import volume_utils +from nova.virt.xenapi import vmops from nova.virt.xenapi import vm_utils -from nova.virt.xenapi.vmops import SimpleDH -from nova.virt.xenapi.vmops import VMOps from nova.tests.db import fakes as db_fakes from nova.tests.xenapi import stubs from nova.tests.glance import stubs as glance_stubs @@ -191,7 +190,7 @@ class XenAPIVMTestCase(test.TestCase): stubs.stubout_get_this_vm_uuid(self.stubs) stubs.stubout_stream_disk(self.stubs) stubs.stubout_is_vdi_pv(self.stubs) - self.stubs.Set(VMOps, 'reset_network', reset_network) + self.stubs.Set(vmops.VMOps, 'reset_network', reset_network) stubs.stub_out_vm_methods(self.stubs) glance_stubs.stubout_glance_client(self.stubs) fake_utils.stub_out_utils_execute(self.stubs) @@ -581,8 +580,8 @@ class XenAPIDiffieHellmanTestCase(test.TestCase): """Unit tests for Diffie-Hellman code.""" def setUp(self): super(XenAPIDiffieHellmanTestCase, self).setUp() - self.alice = SimpleDH() - self.bob = SimpleDH() + self.alice = vmops.SimpleDH() + self.bob = vmops.SimpleDH() def test_shared(self): alice_pub = self.alice.get_public() @@ -729,6 +728,28 @@ class XenAPIDetermineDiskImageTestCase(test.TestCase): self.assert_disk_type(vm_utils.ImageType.DISK_VHD) +class CompareVersionTestCase(test.TestCase): + def test_less_than(self): + """Test that cmp_version compares a as less than b""" + self.assert_(vmops.cmp_version('1.2.3.4', '1.2.3.5') < 0) + + def test_greater_than(self): + """Test that cmp_version compares a as greater than b""" + self.assert_(vmops.cmp_version('1.2.3.5', '1.2.3.4') > 0) + + def test_equal(self): + """Test that cmp_version compares a as equal to b""" + self.assert_(vmops.cmp_version('1.2.3.4', '1.2.3.4') == 0) + + def test_non_lexical(self): + """Test that cmp_version compares non-lexically""" + self.assert_(vmops.cmp_version('1.2.3.10', '1.2.3.4') > 0) + + def test_length(self): + """Test that cmp_version compares by length as last resort""" + self.assert_(vmops.cmp_version('1.2.3', '1.2.3.4') < 0) + + class FakeXenApi(object): """Fake XenApi for testing HostState.""" From 2160a99d3f59025d0421142ae13666d70970dcdc Mon Sep 17 00:00:00 2001 From: Johannes Erdfelt Date: Fri, 17 Jun 2011 18:47:57 +0000 Subject: [PATCH 038/105] Add new architecture attribute along with os_type --- nova/tests/test_xenapi.py | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/nova/tests/test_xenapi.py b/nova/tests/test_xenapi.py index 5504e802..b3364a45 100644 --- a/nova/tests/test_xenapi.py +++ b/nova/tests/test_xenapi.py @@ -83,7 +83,8 @@ class XenAPIVolumeTestCase(test.TestCase): 'ramdisk_id': 3, 'instance_type_id': '3', # m1.large 'mac_address': 'aa:bb:cc:dd:ee:ff', - 'os_type': 'linux'} + 'os_type': 'linux', + 'architecture': 'x86-64'} def _create_volume(self, size='0'): """Create a volume object.""" @@ -210,7 +211,8 @@ class XenAPIVMTestCase(test.TestCase): 'ramdisk_id': 3, 'instance_type_id': '3', # m1.large 'mac_address': 'aa:bb:cc:dd:ee:ff', - 'os_type': 'linux'} + 'os_type': 'linux', + 'architecture': 'x86-64'} instance = db.instance_create(self.context, values) self.conn.spawn(instance) @@ -351,7 +353,8 @@ class XenAPIVMTestCase(test.TestCase): def _test_spawn(self, image_ref, kernel_id, ramdisk_id, instance_type_id="3", os_type="linux", - instance_id=1, check_injection=False): + architecture="x86-64", instance_id=1, + check_injection=False): stubs.stubout_loopingcall_start(self.stubs) values = {'id': instance_id, 'project_id': self.project.id, @@ -361,7 +364,8 @@ class XenAPIVMTestCase(test.TestCase): 'ramdisk_id': ramdisk_id, 'instance_type_id': instance_type_id, 'mac_address': 'aa:bb:cc:dd:ee:ff', - 'os_type': os_type} + 'os_type': os_type, + 'architecture': architecture} instance = db.instance_create(self.context, values) self.conn.spawn(instance) self.create_vm_record(self.conn, os_type, instance_id) @@ -390,7 +394,7 @@ class XenAPIVMTestCase(test.TestCase): def test_spawn_vhd_glance_linux(self): FLAGS.xenapi_image_service = 'glance' self._test_spawn(glance_stubs.FakeGlance.IMAGE_VHD, None, None, - os_type="linux") + os_type="linux", architecture="x86-64") self.check_vm_params_for_linux() def test_spawn_vhd_glance_swapdisk(self): @@ -419,7 +423,7 @@ class XenAPIVMTestCase(test.TestCase): def test_spawn_vhd_glance_windows(self): FLAGS.xenapi_image_service = 'glance' self._test_spawn(glance_stubs.FakeGlance.IMAGE_VHD, None, None, - os_type="windows") + os_type="windows", architecture="i386") self.check_vm_params_for_windows() def test_spawn_glance(self): @@ -570,7 +574,8 @@ class XenAPIVMTestCase(test.TestCase): 'ramdisk_id': 3, 'instance_type_id': '3', # m1.large 'mac_address': 'aa:bb:cc:dd:ee:ff', - 'os_type': 'linux'} + 'os_type': 'linux', + 'architecture': 'x86-64'} instance = db.instance_create(self.context, values) self.conn.spawn(instance) return instance @@ -645,7 +650,8 @@ class XenAPIMigrateInstance(test.TestCase): 'local_gb': 5, 'instance_type_id': '3', # m1.large 'mac_address': 'aa:bb:cc:dd:ee:ff', - 'os_type': 'linux'} + 'os_type': 'linux', + 'architecture': 'x86-64'} fake_utils.stub_out_utils_execute(self.stubs) stubs.stub_out_migration_methods(self.stubs) @@ -684,6 +690,7 @@ class XenAPIDetermineDiskImageTestCase(test.TestCase): self.fake_instance = FakeInstance() self.fake_instance.id = 42 self.fake_instance.os_type = 'linux' + self.fake_instance.architecture = 'x86-64' def assert_disk_type(self, disk_type): dt = vm_utils.VMHelper.determine_disk_image_type( From 84efb31e4b8f889603ad50e88b5ec7a720ca38c6 Mon Sep 17 00:00:00 2001 From: Johannes Erdfelt Date: Fri, 17 Jun 2011 21:03:12 +0000 Subject: [PATCH 039/105] Ensure os_type and architecture get set correctly --- nova/tests/test_xenapi.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/nova/tests/test_xenapi.py b/nova/tests/test_xenapi.py index b3364a45..54e82592 100644 --- a/nova/tests/test_xenapi.py +++ b/nova/tests/test_xenapi.py @@ -370,6 +370,8 @@ class XenAPIVMTestCase(test.TestCase): self.conn.spawn(instance) self.create_vm_record(self.conn, os_type, instance_id) self.check_vm_record(self.conn, check_injection) + self.assert_(instance.os_type) + self.assert_(instance.architecture) def test_spawn_not_enough_memory(self): FLAGS.xenapi_image_service = 'glance' From b7fe156f3de0f8b0e3d395ec814317b12335db47 Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Sat, 18 Jun 2011 23:10:41 -0400 Subject: [PATCH 040/105] General cleanup and refactor of a lot of the API/WSGI service code. --- bin/nova-api | 18 ++++++++++++++++-- nova/log.py | 13 +++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/bin/nova-api b/bin/nova-api index a1088c23..6db68be9 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -24,6 +24,8 @@ import gettext import os import sys +import eventlet.pool + # If ../nova/__init__.py exists, add ../ to Python search path, so that # it will override what happens to be installed in /usr/(local/)lib/python... possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), @@ -46,6 +48,13 @@ LOG = logging.getLogger('nova.api') FLAGS = flags.FLAGS + +def launch(service_name): + _service = service.WSGIService(service_name) + _service.start() + _service.wait() + + if __name__ == '__main__': utils.default_flagfile() FLAGS(sys.argv) @@ -57,5 +66,10 @@ if __name__ == '__main__': flag_get = FLAGS.get(flag, None) LOG.debug("%(flag)s : %(flag_get)s" % locals()) - service = service.serve_wsgi(service.ApiService) - service.wait() + + pool = eventlet.pool.Pool() + pool.execute(launch, "ec2") + pool.execute(launch, "osapi") + pool.wait_all() + + print >>sys.stderr, "Exiting..." diff --git a/nova/log.py b/nova/log.py index 6909916a..d3bffdb2 100644 --- a/nova/log.py +++ b/nova/log.py @@ -314,3 +314,16 @@ logging.setLoggerClass(NovaLogger) def audit(msg, *args, **kwargs): """Shortcut for logging to root log with sevrity 'AUDIT'.""" logging.root.log(AUDIT, msg, *args, **kwargs) + + +class WritableLogger(object): + """A thin wrapper that responds to `write` and logs.""" + + def __init__(self, logger, level=logging.DEBUG): + self.logger = logger + self.level = level + + def write(self, msg): + self.logger.log(self.level, msg) + + From 056e48767cb10c1813f1411984ace8689b31bcc6 Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Sun, 19 Jun 2011 14:09:09 -0400 Subject: [PATCH 041/105] Removed debugging, made objectstore tests pass again. --- bin/nova-api | 3 --- nova/log.py | 2 -- 2 files changed, 5 deletions(-) diff --git a/bin/nova-api b/bin/nova-api index 6db68be9..90c8b69a 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -66,10 +66,7 @@ if __name__ == '__main__': flag_get = FLAGS.get(flag, None) LOG.debug("%(flag)s : %(flag_get)s" % locals()) - pool = eventlet.pool.Pool() pool.execute(launch, "ec2") pool.execute(launch, "osapi") pool.wait_all() - - print >>sys.stderr, "Exiting..." diff --git a/nova/log.py b/nova/log.py index d3bffdb2..3080daee 100644 --- a/nova/log.py +++ b/nova/log.py @@ -325,5 +325,3 @@ class WritableLogger(object): def write(self, msg): self.logger.log(self.level, msg) - - From 6b1029efbe274db586b11dff81400f44d50222c3 Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Sun, 19 Jun 2011 14:41:42 -0400 Subject: [PATCH 042/105] Cleaned up nova-api binary and logging a bit. --- bin/nova-api | 32 +++++++++----------------------- 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/bin/nova-api b/bin/nova-api index 90c8b69a..7d80b0b7 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -20,33 +20,20 @@ """Starter script for Nova API.""" -import gettext -import os import sys import eventlet.pool -# If ../nova/__init__.py exists, add ../ to Python search path, so that -# it will override what happens to be installed in /usr/(local/)lib/python... -possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), - os.pardir, - os.pardir)) -if os.path.exists(os.path.join(possible_topdir, 'nova', '__init__.py')): - sys.path.insert(0, possible_topdir) - -gettext.install('nova', unicode=1) - from nova import flags from nova import log as logging from nova import service from nova import utils from nova import version -from nova import wsgi -LOG = logging.getLogger('nova.api') - +LOG = logging.getLogger("nova.api") FLAGS = flags.FLAGS +VERSION = version.version_string_with_vcs() def launch(service_name): @@ -55,18 +42,17 @@ def launch(service_name): _service.wait() -if __name__ == '__main__': +def main(): utils.default_flagfile() FLAGS(sys.argv) - logging.setup() - LOG.audit(_("Starting nova-api node (version %s)"), - version.version_string_with_vcs()) - LOG.debug(_("Full set of FLAGS:")) - for flag in FLAGS: - flag_get = FLAGS.get(flag, None) - LOG.debug("%(flag)s : %(flag_get)s" % locals()) +# logging.setup() + LOG.audit(_("Starting nova-api node (version %s)") % VERSION) pool = eventlet.pool.Pool() pool.execute(launch, "ec2") pool.execute(launch, "osapi") pool.wait_all() + + +if __name__ == '__main__': + sys.exit(main()) From ffaa6f28a936e5f15a17bcb291d15059dc83945c Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Sun, 19 Jun 2011 16:27:46 -0400 Subject: [PATCH 043/105] Further nova-api cleanup. --- bin/nova-api | 65 ++++++++++++++++++++++++++++++---------------------- nova/log.py | 2 +- 2 files changed, 39 insertions(+), 28 deletions(-) diff --git a/bin/nova-api b/bin/nova-api index 7d80b0b7..ff4aa83d 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -1,7 +1,5 @@ #!/usr/bin/env python -# pylint: disable=C0103 -# 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. @@ -18,40 +16,53 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Starter script for Nova API.""" +"""Starter script for Nova API. + +Starts both the EC2 and OpenStack APIs in separate processes. Pylint warnings +about re-imports should be ignored. + +""" + +# pylint: disable=W0404 import sys +import multiprocessing -import eventlet.pool - -from nova import flags -from nova import log as logging -from nova import service -from nova import utils -from nova import version - - -LOG = logging.getLogger("nova.api") -FLAGS = flags.FLAGS -VERSION = version.version_string_with_vcs() +import nova.flags +import nova.log +import nova.service +import nova.version +import nova.utils def launch(service_name): - _service = service.WSGIService(service_name) - _service.start() - _service.wait() + """Launch WSGI service with name matching 'paste' config file section.""" + service = nova.service.WSGIService(service_name) + service.start() + try: + service.wait() + except KeyboardInterrupt: + service.stop() def main(): - utils.default_flagfile() - FLAGS(sys.argv) -# logging.setup() - LOG.audit(_("Starting nova-api node (version %s)") % VERSION) + """Begin process of launching both EC2 and OSAPI services.""" + version = nova.version.version_string_with_vcs() + logger = nova.log.getLogger("nova.api") + logger.audit(_("Starting nova-api node (version %s)") % version) - pool = eventlet.pool.Pool() - pool.execute(launch, "ec2") - pool.execute(launch, "osapi") - pool.wait_all() + nova.flags.FLAGS(sys.argv) + nova.utils.default_flagfile() + + pool = multiprocessing.Pool(2) + pool.map_async(launch, ["ec2", "osapi"]) + pool.close() + + try: + pool.join() + except KeyboardInterrupt: + logger.audit(_("Exiting...")) + pool.terminate() if __name__ == '__main__': diff --git a/nova/log.py b/nova/log.py index 3080daee..f8c0ba68 100644 --- a/nova/log.py +++ b/nova/log.py @@ -319,7 +319,7 @@ def audit(msg, *args, **kwargs): class WritableLogger(object): """A thin wrapper that responds to `write` and logs.""" - def __init__(self, logger, level=logging.DEBUG): + def __init__(self, logger, level=logging.INFO): self.logger = logger self.level = level From 76d5b3f03de9c64decfd27e6b9febb22272791d2 Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Sun, 19 Jun 2011 18:00:38 -0400 Subject: [PATCH 044/105] Cleanup of the cleanup. --- bin/nova-api | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/bin/nova-api b/bin/nova-api index ff4aa83d..1fcda24f 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -1,4 +1,5 @@ #!/usr/bin/env python +# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. @@ -18,13 +19,10 @@ """Starter script for Nova API. -Starts both the EC2 and OpenStack APIs in separate processes. Pylint warnings -about re-imports should be ignored. +Starts both the EC2 and OpenStack APIs in separate processes. """ -# pylint: disable=W0404 - import sys import multiprocessing From db798a12a077735269e4bc36fd64a7a55c9bac07 Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Sun, 19 Jun 2011 20:18:29 -0400 Subject: [PATCH 045/105] Introduced Loader concept, for paste decouple. --- bin/nova-api | 2 ++ 1 file changed, 2 insertions(+) diff --git a/bin/nova-api b/bin/nova-api index 1fcda24f..885fb0ba 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -51,6 +51,8 @@ def main(): nova.flags.FLAGS(sys.argv) nova.utils.default_flagfile() + +# launch("osapi") pool = multiprocessing.Pool(2) pool.map_async(launch, ["ec2", "osapi"]) From 09bba14ef76c0131d574f9e3d5b9a3fa114386be Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Mon, 20 Jun 2011 10:12:43 -0400 Subject: [PATCH 046/105] Cleanup and addition of tests for WSGI server. --- bin/nova-api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/nova-api b/bin/nova-api index 885fb0ba..89112a15 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -1,6 +1,6 @@ #!/usr/bin/env python # 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. From 7ada255d992fbd0516b2302ef366f896d75e0a8d Mon Sep 17 00:00:00 2001 From: Johannes Erdfelt Date: Mon, 20 Jun 2011 18:42:04 +0000 Subject: [PATCH 047/105] assert_ -> assertTrue since assert_ is deprecated --- nova/tests/test_xenapi.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/nova/tests/test_xenapi.py b/nova/tests/test_xenapi.py index 54e82592..93e6e544 100644 --- a/nova/tests/test_xenapi.py +++ b/nova/tests/test_xenapi.py @@ -370,8 +370,8 @@ class XenAPIVMTestCase(test.TestCase): self.conn.spawn(instance) self.create_vm_record(self.conn, os_type, instance_id) self.check_vm_record(self.conn, check_injection) - self.assert_(instance.os_type) - self.assert_(instance.architecture) + self.assertTrue(instance.os_type) + self.assertTrue(instance.architecture) def test_spawn_not_enough_memory(self): FLAGS.xenapi_image_service = 'glance' @@ -740,23 +740,23 @@ class XenAPIDetermineDiskImageTestCase(test.TestCase): class CompareVersionTestCase(test.TestCase): def test_less_than(self): """Test that cmp_version compares a as less than b""" - self.assert_(vmops.cmp_version('1.2.3.4', '1.2.3.5') < 0) + self.assertTrue(vmops.cmp_version('1.2.3.4', '1.2.3.5') < 0) def test_greater_than(self): """Test that cmp_version compares a as greater than b""" - self.assert_(vmops.cmp_version('1.2.3.5', '1.2.3.4') > 0) + self.assertTrue(vmops.cmp_version('1.2.3.5', '1.2.3.4') > 0) def test_equal(self): """Test that cmp_version compares a as equal to b""" - self.assert_(vmops.cmp_version('1.2.3.4', '1.2.3.4') == 0) + self.assertTrue(vmops.cmp_version('1.2.3.4', '1.2.3.4') == 0) def test_non_lexical(self): """Test that cmp_version compares non-lexically""" - self.assert_(vmops.cmp_version('1.2.3.10', '1.2.3.4') > 0) + self.assertTrue(vmops.cmp_version('1.2.3.10', '1.2.3.4') > 0) def test_length(self): """Test that cmp_version compares by length as last resort""" - self.assert_(vmops.cmp_version('1.2.3', '1.2.3.4') < 0) + self.assertTrue(vmops.cmp_version('1.2.3', '1.2.3.4') < 0) class FakeXenApi(object): From aee6affeffb79acc75fdefaa75ffb331e4d51e56 Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Mon, 20 Jun 2011 14:54:53 -0400 Subject: [PATCH 048/105] pep8 fixes --- bin/nova-api | 2 -- 1 file changed, 2 deletions(-) diff --git a/bin/nova-api b/bin/nova-api index 89112a15..2345b3f2 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -51,8 +51,6 @@ def main(): nova.flags.FLAGS(sys.argv) nova.utils.default_flagfile() - -# launch("osapi") pool = multiprocessing.Pool(2) pool.map_async(launch, ["ec2", "osapi"]) From 3a0feec3a6c254ca36688a707e1618a8cfbb49a5 Mon Sep 17 00:00:00 2001 From: John Tran Date: Mon, 20 Jun 2011 15:28:34 -0700 Subject: [PATCH 049/105] nova-manage checks if user is member of proj, prior to adding role for that project --- bin/nova-manage | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/bin/nova-manage b/bin/nova-manage index dbdb798a..7226fcfa 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -257,6 +257,11 @@ class RoleCommands(object): """adds role to user if project is specified, adds project specific role arguments: user, role [project]""" + if project: + projobj = self.manager.get_project(project) + if not projobj.has_member(user): + print "%s not a member of %s" % (user, project) + return self.manager.add_role(user, role, project) def has(self, user, role, project=None): From 5630fae25da028de6a7af87c4805f6dbc8e80acf Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Mon, 20 Jun 2011 19:32:18 -0400 Subject: [PATCH 050/105] Removed logging logic from __init__, added concept of Launcher...no tests for it yet. --- bin/nova-api | 38 ++++++++++---------------------------- 1 file changed, 10 insertions(+), 28 deletions(-) diff --git a/bin/nova-api b/bin/nova-api index 2345b3f2..563d7c09 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -24,44 +24,26 @@ Starts both the EC2 and OpenStack APIs in separate processes. """ import sys -import multiprocessing -import nova.flags import nova.log import nova.service import nova.version -import nova.utils - - -def launch(service_name): - """Launch WSGI service with name matching 'paste' config file section.""" - service = nova.service.WSGIService(service_name) - service.start() - try: - service.wait() - except KeyboardInterrupt: - service.stop() def main(): - """Begin process of launching both EC2 and OSAPI services.""" - version = nova.version.version_string_with_vcs() - logger = nova.log.getLogger("nova.api") - logger.audit(_("Starting nova-api node (version %s)") % version) - - nova.flags.FLAGS(sys.argv) - nova.utils.default_flagfile() - - pool = multiprocessing.Pool(2) - pool.map_async(launch, ["ec2", "osapi"]) - pool.close() + """Launch EC2 and OSAPI services.""" + ec2 = nova.service.WSGIService("ec2") + osapi = nova.service.WSGIService("osapi") + launcher = nova.service.Launcher(sys.argv) + launcher.launch_service(ec2) + launcher.launch_service(osapi) + try: - pool.join() + launcher.wait() except KeyboardInterrupt: - logger.audit(_("Exiting...")) - pool.terminate() - + launcher.stop() + if __name__ == '__main__': sys.exit(main()) From dc9cfe2f167befb2d56223850ca1f86b48230c9d Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Tue, 21 Jun 2011 00:21:33 -0400 Subject: [PATCH 051/105] Tests for WSGI/Launcher --- bin/nova-api | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/nova-api b/bin/nova-api index 563d7c09..20ad4bfa 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -38,12 +38,12 @@ def main(): launcher = nova.service.Launcher(sys.argv) launcher.launch_service(ec2) launcher.launch_service(osapi) - + try: launcher.wait() except KeyboardInterrupt: launcher.stop() - + if __name__ == '__main__': sys.exit(main()) From 99a91caee7b88a7d74ad5362092015b97070526f Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Tue, 21 Jun 2011 00:32:31 -0400 Subject: [PATCH 052/105] Removed unneeded import. --- bin/nova-api | 1 - 1 file changed, 1 deletion(-) diff --git a/bin/nova-api b/bin/nova-api index 20ad4bfa..b94928c7 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -27,7 +27,6 @@ import sys import nova.log import nova.service -import nova.version def main(): From 330f470992bd74079b4fb74fa87fdc7244f62365 Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Tue, 21 Jun 2011 11:25:44 -0400 Subject: [PATCH 053/105] Very small alterations, switched from using start() to pass host/port, to just defining them up front in init. Doesn't make sense to set them in start because we can't start more than once any way. Also, unbroke binaries. --- bin/nova-ajax-console-proxy | 5 +++-- bin/nova-direct-api | 7 +++++-- bin/nova-objectstore | 7 +++++-- bin/nova-vncproxy | 7 +++++-- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/bin/nova-ajax-console-proxy b/bin/nova-ajax-console-proxy index d88f59e4..21cf6800 100755 --- a/bin/nova-ajax-console-proxy +++ b/bin/nova-ajax-console-proxy @@ -137,8 +137,9 @@ if __name__ == '__main__': utils.default_flagfile() FLAGS(sys.argv) logging.setup() - server = wsgi.Server() + acp_port = FLAGS.ajax_console_proxy_port acp = AjaxConsoleProxy() acp.register_listeners() - server.start(acp, FLAGS.ajax_console_proxy_port, host='0.0.0.0') + server = wsgi.Server("AJAX Console Proxy", acp, port=acp_port) + server.start() server.wait() diff --git a/bin/nova-direct-api b/bin/nova-direct-api index 83ec7272..5d63eb87 100755 --- a/bin/nova-direct-api +++ b/bin/nova-direct-api @@ -93,6 +93,9 @@ if __name__ == '__main__': with_req = direct.PostParamsMiddleware(with_json) with_auth = direct.DelegatedAuthMiddleware(with_req) - server = wsgi.Server() - server.start(with_auth, FLAGS.direct_port, host=FLAGS.direct_host) + server = wsgi.Server("Direct API", + with_auth, + host=FLAGS.direct_host, + port=FLAGS.direct_port) + server.start() server.wait() diff --git a/bin/nova-objectstore b/bin/nova-objectstore index 6ef841b8..aa0dc063 100755 --- a/bin/nova-objectstore +++ b/bin/nova-objectstore @@ -50,6 +50,9 @@ if __name__ == '__main__': FLAGS(sys.argv) logging.setup() router = s3server.S3Application(FLAGS.buckets_path) - server = wsgi.Server() - server.start(router, FLAGS.s3_port, host=FLAGS.s3_host) + server = wsgi.Server("S3 Objectstore", + router, + port=FLAGS.s3_port, + host=FLAGS.s3_host) + server.start() server.wait() diff --git a/bin/nova-vncproxy b/bin/nova-vncproxy index ccb97e3a..62d3b948 100755 --- a/bin/nova-vncproxy +++ b/bin/nova-vncproxy @@ -96,6 +96,9 @@ if __name__ == "__main__": service.serve() - server = wsgi.Server() - server.start(with_auth, FLAGS.vncproxy_port, host=FLAGS.vncproxy_host) + server = wsgi.Server("VNC Proxy", + with_auth, + host=FLAGS.vncproxy_host, + port=FLAGS.vncproxy_port) + server.start() server.wait() From d5a5df9b839d164d72c6a089946b2736dc790c6b Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Tue, 21 Jun 2011 12:03:27 -0400 Subject: [PATCH 054/105] Removed whitespace. --- bin/nova-direct-api | 4 ++-- bin/nova-objectstore | 6 +++--- bin/nova-vncproxy | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/bin/nova-direct-api b/bin/nova-direct-api index 5d63eb87..c6cf9b2f 100755 --- a/bin/nova-direct-api +++ b/bin/nova-direct-api @@ -93,8 +93,8 @@ if __name__ == '__main__': with_req = direct.PostParamsMiddleware(with_json) with_auth = direct.DelegatedAuthMiddleware(with_req) - server = wsgi.Server("Direct API", - with_auth, + server = wsgi.Server("Direct API", + with_auth, host=FLAGS.direct_host, port=FLAGS.direct_port) server.start() diff --git a/bin/nova-objectstore b/bin/nova-objectstore index aa0dc063..1aef3a25 100755 --- a/bin/nova-objectstore +++ b/bin/nova-objectstore @@ -50,9 +50,9 @@ if __name__ == '__main__': FLAGS(sys.argv) logging.setup() router = s3server.S3Application(FLAGS.buckets_path) - server = wsgi.Server("S3 Objectstore", - router, - port=FLAGS.s3_port, + server = wsgi.Server("S3 Objectstore", + router, + port=FLAGS.s3_port, host=FLAGS.s3_host) server.start() server.wait() diff --git a/bin/nova-vncproxy b/bin/nova-vncproxy index 62d3b948..72271df3 100755 --- a/bin/nova-vncproxy +++ b/bin/nova-vncproxy @@ -96,7 +96,7 @@ if __name__ == "__main__": service.serve() - server = wsgi.Server("VNC Proxy", + server = wsgi.Server("VNC Proxy", with_auth, host=FLAGS.vncproxy_host, port=FLAGS.vncproxy_port) From df17ceea98d975f61779ab56e2bb46cb2f3d09df Mon Sep 17 00:00:00 2001 From: Alex Meade Date: Wed, 22 Jun 2011 15:22:25 -0400 Subject: [PATCH 055/105] fixed incorrect exception --- bin/nova-manage | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/nova-manage b/bin/nova-manage index 48d57693..000e834f 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -873,7 +873,7 @@ class InstanceTypeCommands(object): try: instance_types.create(name, memory, vcpus, local_gb, flavorid, swap, rxtx_quota, rxtx_cap) - except exception.InvalidInputException: + except exception.InvalidInput: print "Must supply valid parameters to create instance_type" print e sys.exit(1) From 1e2acef020d2c48f2d65a0ad72c7efa695d5ca58 Mon Sep 17 00:00:00 2001 From: Mark Washenberger Date: Wed, 22 Jun 2011 23:27:49 -0400 Subject: [PATCH 056/105] run launcher first since it initializes global flags and logging --- bin/nova-api | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bin/nova-api b/bin/nova-api index b94928c7..121f6f9a 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -31,10 +31,11 @@ import nova.service def main(): """Launch EC2 and OSAPI services.""" + launcher = nova.service.Launcher(sys.argv) + ec2 = nova.service.WSGIService("ec2") osapi = nova.service.WSGIService("osapi") - launcher = nova.service.Launcher(sys.argv) launcher.launch_service(ec2) launcher.launch_service(osapi) From dacbb341dce52428d20a4d1fb141383935118e8c Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Thu, 23 Jun 2011 01:22:50 -0700 Subject: [PATCH 057/105] Add some resource checking for memory available when scheduling Various changes to d-sched to plan for scheduling on different topics, which cleans up some of the resource checking. Re-compute weights when building more than 1 instance, accounting for resources that would be consumed. --- nova/scheduler/host_filter.py | 10 ++- nova/scheduler/least_cost.py | 39 +++++++---- nova/scheduler/zone_aware_scheduler.py | 92 +++++++++++++++++++++----- 3 files changed, 106 insertions(+), 35 deletions(-) diff --git a/nova/scheduler/host_filter.py b/nova/scheduler/host_filter.py index bd6b2660..818ae4a3 100644 --- a/nova/scheduler/host_filter.py +++ b/nova/scheduler/host_filter.py @@ -305,8 +305,11 @@ class HostFilterScheduler(zone_aware_scheduler.ZoneAwareScheduler): 'instance_type': } """ - def filter_hosts(self, num, request_spec): + def filter_hosts(self, topic, request_spec, hosts): """Filter the full host list (from the ZoneManager)""" + + if hosts: + return hosts filter_name = request_spec.get('filter', None) host_filter = choose_host_filter(filter_name) @@ -317,8 +320,9 @@ class HostFilterScheduler(zone_aware_scheduler.ZoneAwareScheduler): name, query = host_filter.instance_type_to_filter(instance_type) return host_filter.filter_hosts(self.zone_manager, query) - def weigh_hosts(self, num, request_spec, hosts): + def weigh_hosts(self, topic, request_spec, hosts): """Derived classes must override this method and return a lists of hosts in [{weight, hostname}] format. """ - return [dict(weight=1, hostname=host) for host, caps in hosts] + return [dict(weight=1, hostname=hostname, capabilities=caps) + for hostname, caps in hosts] diff --git a/nova/scheduler/least_cost.py b/nova/scheduler/least_cost.py index 629fe2e4..72db2fd1 100644 --- a/nova/scheduler/least_cost.py +++ b/nova/scheduler/least_cost.py @@ -48,25 +48,36 @@ def noop_cost_fn(host): return 1 -flags.DEFINE_integer('fill_first_cost_fn_weight', 1, +flags.DEFINE_integer('compute_fill_first_cost_fn_weight', 1, 'How much weight to give the fill-first cost function') -def fill_first_cost_fn(host): +def compute_fill_first_cost_fn(host): """Prefer hosts that have less ram available, filter_hosts will exclude hosts that don't have enough ram""" hostname, caps = host - free_mem = caps['compute']['host_memory_free'] + free_mem = caps['host_memory_free'] return free_mem class LeastCostScheduler(zone_aware_scheduler.ZoneAwareScheduler): - def get_cost_fns(self): + def __init__(self, *args, **kwargs): + self.cost_fns_cache = {} + super(LeastCoastScheduler, self).__init__(*args, **kwargs) + + def get_cost_fns(self, topic): """Returns a list of tuples containing weights and cost functions to use for weighing hosts """ + + if topic in self.cost_fns_cache: + return self.cost_fns_cache[topic] + cost_fns = [] for cost_fn_str in FLAGS.least_cost_scheduler_cost_functions: + if not cost_fn_str.startswith('%s_' % topic) and \ + not cost_fn_str.startswith('noop'): + continue try: # NOTE(sirp): import_class is somewhat misnamed since it can @@ -84,23 +95,23 @@ class LeastCostScheduler(zone_aware_scheduler.ZoneAwareScheduler): cost_fns.append((weight, cost_fn)) + self.cost_fns_cache[topic] = cost_fns return cost_fns - def weigh_hosts(self, num, request_spec, hosts): + def weigh_hosts(self, topic, request_spec, hosts): """Returns a list of dictionaries of form: - [ {weight: weight, hostname: hostname} ]""" + [ {weight: weight, hostname: hostname, capabilities: capabs} ] + """ - # FIXME(sirp): weigh_hosts should handle more than just instances - hostnames = [hostname for hostname, caps in hosts] - - cost_fns = self.get_cost_fns() + cost_fns = self.get_cost_fns(topic) costs = weighted_sum(domain=hosts, weighted_fns=cost_fns) weighted = [] weight_log = [] - for cost, hostname in zip(costs, hostnames): + for cost, (hostname, caps) in zip(costs, hosts): weight_log.append("%s: %s" % (hostname, "%.2f" % cost)) - weight_dict = dict(weight=cost, hostname=hostname) + weight_dict = dict(weight=cost, hostname=hostname, + capabilities=caps) weighted.append(weight_dict) LOG.debug(_("Weighted Costs => %s") % weight_log) @@ -127,7 +138,8 @@ def weighted_sum(domain, weighted_fns, normalize=True): weighted_fns - list of weights and functions like: [(weight, objective-functions)] - Returns an unsorted of scores. To pair with hosts do: zip(scores, hosts) + Returns an unsorted list of scores. To pair with hosts do: + zip(scores, hosts) """ # Table of form: # { domain1: [score1, score2, ..., scoreM] @@ -150,7 +162,6 @@ def weighted_sum(domain, weighted_fns, normalize=True): domain_scores = [] for idx in sorted(score_table): elem_score = sum(score_table[idx]) - elem = domain[idx] domain_scores.append(elem_score) return domain_scores diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index e7bff2fa..d4d3d041 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -224,18 +224,34 @@ class ZoneAwareScheduler(driver.Scheduler): raise NotImplemented(_("Zone Aware Scheduler only understands " "Compute nodes (for now)")) - #TODO(sandy): how to infer this from OS API params? - num_instances = 1 + num_instances = request_spec['num_instances'] + instance_type = request_spec['instance_type'] - # Filter local hosts based on requirements ... - host_list = self.filter_hosts(num_instances, request_spec) + weighted = [] + host_list = None - # TODO(sirp): weigh_hosts should also be a function of 'topic' or - # resources, so that we can apply different objective functions to it + for i in xrange(num_instances): + # Filter local hosts based on requirements ... + # + # The first pass through here will pass 'None' as the + # host_list.. which tells the filter to build the full + # list of hosts. + # On a 2nd pass, the filter can modify the host_list with + # any updates it needs to make based on resources that + # may have been consumed from a previous build.. + host_list = self.filter_hosts(topic, request_spec, host_list) + if not host_list: + break - # then weigh the selected hosts. - # weighted = [{weight=weight, name=hostname}, ...] - weighted = self.weigh_hosts(num_instances, request_spec, host_list) + # then weigh the selected hosts. + # weighted = [{weight=weight, hostname=hostname, + # capabilities=capabs}, ...] + weights = self.weigh_hosts(topic, request_spec, host_list) + weights.sort(key=operator.itemgetter('weight')) + best_weight = weights[0] + weighted.append(best_weight) + self.consume_resources(best_weight['capabilities'], + instance_type) # Next, tack on the best weights from the child zones ... json_spec = json.dumps(request_spec) @@ -254,18 +270,58 @@ class ZoneAwareScheduler(driver.Scheduler): weighted.sort(key=operator.itemgetter('weight')) return weighted - def filter_hosts(self, num, request_spec): - """Derived classes must override this method and return - a list of hosts in [(hostname, capability_dict)] format. + def compute_filter(self, hostname, capabilities, request_spec): + """Return whether or not we can schedule to this compute node. + Derived classes should override this and return True if the host + is acceptable for scheduling. """ - # NOTE(sirp): The default logic is the equivalent to AllHostsFilter - service_states = self.zone_manager.service_states - return [(host, services) - for host, services in service_states.iteritems()] + instance_type = request_spec['instance_type'] + reqested_mem = instance_type['memory_mb'] + return capabilities['host_memory_free'] >= requested_mem - def weigh_hosts(self, num, request_spec, hosts): + def filter_hosts(self, topic, request_spec, host_list=None): + """Return a list of hosts which are acceptable for scheduling. + Return value should be a list of (hostname, capability_dict)s. + Derived classes may override this, but may find the + '_filter' function more appropriate. + """ + + def _default_filter(self, hostname, capabilities, request_spec): + """Default filter function if there's no _filter""" + # NOTE(sirp): The default logic is the equivalent to + # AllHostsFilter + return True + + filter_func = getattr(self, '%s_filter' % topic, _default_filter) + + filtered_hosts = [] + if host_list is None: + host_list = self.zone_manager.service_states.iteritems() + for host, services in host_list: + if topic not in services: + continue + if filter_func(host, services['topic'], request_spec): + filtered_hosts.append((host, services['topic'])) + + def weigh_hosts(self, topic, request_spec, hosts): """Derived classes may override this to provide more sophisticated scheduling objectives """ # NOTE(sirp): The default logic is the same as the NoopCostFunction - return [dict(weight=1, hostname=host) for host, caps in hosts] + return [dict(weight=1, hostname=hostname, capabilities=capabilities) + for hostname, capabilities in hosts] + + def compute_consume(self, capabilities, instance_type): + """Consume compute resources for selected host""" + + requested_mem = max(instance_type['memory_mb'], 0) + capabilities['host_memory_free'] -= requested_mem + + def consume_resources(self, topic, capabilities, instance_type): + """Consume resources for a specific host. 'host' is a tuple + of the hostname and the services""" + + consume_func = getattr(self, '%s_consume' % topic, None) + if not consume_func: + return + consume_func(capabilities, instance_type) From bb4fa1ee1aaf2fb2edb6d51d6eae4a28f8fbc95a Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Thu, 23 Jun 2011 06:52:19 -0700 Subject: [PATCH 058/105] minor fixups --- nova/scheduler/host_filter.py | 4 +--- nova/scheduler/zone_aware_scheduler.py | 1 + 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/nova/scheduler/host_filter.py b/nova/scheduler/host_filter.py index 818ae4a3..b336665b 100644 --- a/nova/scheduler/host_filter.py +++ b/nova/scheduler/host_filter.py @@ -305,11 +305,9 @@ class HostFilterScheduler(zone_aware_scheduler.ZoneAwareScheduler): 'instance_type': } """ - def filter_hosts(self, topic, request_spec, hosts): + def filter_hosts(self, topic, request_spec, hosts=None): """Filter the full host list (from the ZoneManager)""" - if hosts: - return hosts filter_name = request_spec.get('filter', None) host_filter = choose_host_filter(filter_name) diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index d4d3d041..70cb83e8 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -302,6 +302,7 @@ class ZoneAwareScheduler(driver.Scheduler): continue if filter_func(host, services['topic'], request_spec): filtered_hosts.append((host, services['topic'])) + return filtered_hosts def weigh_hosts(self, topic, request_spec, hosts): """Derived classes may override this to provide more sophisticated From bc23101b7a33d98afe7b354cba9b4b88e10c6e68 Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Thu, 23 Jun 2011 09:43:27 -0700 Subject: [PATCH 059/105] an int() was missed being removed from UUID changes when zone rerouting kicks in --- nova/scheduler/api.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/scheduler/api.py b/nova/scheduler/api.py index 1bb047e2..0aed7568 100644 --- a/nova/scheduler/api.py +++ b/nova/scheduler/api.py @@ -169,7 +169,7 @@ def _issue_novaclient_command(nova, zone, collection, method_name, item_id): result = None try: try: - result = manager.get(int(item_id)) + result = manager.get(item_id) except ValueError, e: result = manager.find(name=item_id) except novaclient.NotFound: From 3df4e6df3e389dc9ea4e7a337070b91793f9410a Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Thu, 23 Jun 2011 13:54:45 -0400 Subject: [PATCH 060/105] Add admin api test case (like cloud test case) with a test for fw rules. --- nova/tests/test_adminapi.py | 90 +++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 nova/tests/test_adminapi.py diff --git a/nova/tests/test_adminapi.py b/nova/tests/test_adminapi.py new file mode 100644 index 00000000..70a00f99 --- /dev/null +++ b/nova/tests/test_adminapi.py @@ -0,0 +1,90 @@ +# 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. + +from eventlet import greenthread + +from nova import context +from nova import db +from nova import flags +from nova import log as logging +from nova import rpc +from nova import test +from nova import utils +from nova.auth import manager +from nova.api.ec2 import admin +from nova.image import fake + + +FLAGS = flags.FLAGS +LOG = logging.getLogger('nova.tests.adminapi') + + +class AdminApiTestCase(test.TestCase): + def setUp(self): + super(AdminApiTestCase, self).setUp() + self.flags(connection_type='fake') + + self.conn = rpc.Connection.instance() + + # set up our cloud + self.api = admin.AdminController() + + # set up services + self.compute = self.start_service('compute') + self.scheduter = self.start_service('scheduler') + self.network = self.start_service('network') + self.volume = self.start_service('volume') + self.image_service = utils.import_object(FLAGS.image_service) + + self.manager = manager.AuthManager() + self.user = self.manager.create_user('admin', 'admin', 'admin', True) + self.project = self.manager.create_project('proj', 'admin', 'proj') + self.context = context.RequestContext(user=self.user, + project=self.project) + 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, + 'type': 'machine', 'image_state': 'available'}} + + self.stubs.Set(fake._FakeImageService, 'show', fake_show) + self.stubs.Set(fake._FakeImageService, 'show_by_name', fake_show) + + # NOTE(vish): set up a manual wait so rpc.cast has a chance to finish + rpc_cast = rpc.cast + + def finish_cast(*args, **kwargs): + rpc_cast(*args, **kwargs) + greenthread.sleep(0.2) + + self.stubs.Set(rpc, 'cast', finish_cast) + + def tearDown(self): + network_ref = db.project_get_network(self.context, + self.project.id) + db.network_disassociate(self.context, network_ref['id']) + self.manager.delete_project(self.project) + self.manager.delete_user(self.user) + super(AdminApiTestCase, self).tearDown() + + def test_block_external_ips(self): + """Make sure provider firewall rules are created.""" + result = self.api.block_external_addresses(self.context, '1.1.1.1/32') + self.assertEqual('OK', result['status']) + self.assertEqual('Added 3 rules', result['message']) + From b188a904fbe0c626ad4cbe5347a396538f6c7068 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Thu, 23 Jun 2011 13:59:26 -0400 Subject: [PATCH 061/105] pep8: remove newline at end of file. --- nova/tests/test_adminapi.py | 1 - 1 file changed, 1 deletion(-) diff --git a/nova/tests/test_adminapi.py b/nova/tests/test_adminapi.py index 70a00f99..7ecaf1c0 100644 --- a/nova/tests/test_adminapi.py +++ b/nova/tests/test_adminapi.py @@ -87,4 +87,3 @@ class AdminApiTestCase(test.TestCase): result = self.api.block_external_addresses(self.context, '1.1.1.1/32') self.assertEqual('OK', result['status']) self.assertEqual('Added 3 rules', result['message']) - From ec73f6ed8be09967f277810ebd9c19e179b3c339 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Thu, 23 Jun 2011 14:13:27 -0400 Subject: [PATCH 062/105] Add test for listing provider firewall rules. --- nova/tests/test_adminapi.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/nova/tests/test_adminapi.py b/nova/tests/test_adminapi.py index 7ecaf1c0..2b90d49e 100644 --- a/nova/tests/test_adminapi.py +++ b/nova/tests/test_adminapi.py @@ -87,3 +87,10 @@ class AdminApiTestCase(test.TestCase): result = self.api.block_external_addresses(self.context, '1.1.1.1/32') self.assertEqual('OK', result['status']) self.assertEqual('Added 3 rules', result['message']) + + def test_list_blocked_ips(self): + """Make sure we can see the external blocks that exist.""" + result = self.api.describe_external_address_blocks(self.context) + num = len(db.provider_fw_rule_get_all(self.context)) + # we only list IP, not tcp/udp/icmp rules + self.assertEqual(num / 3, len(result['externalIpBlockInfo'])) From 466e91e00542bee2abb7a7583d96e0742c0d0efd Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Thu, 23 Jun 2011 14:16:11 -0400 Subject: [PATCH 063/105] Make sure there are actually rules to test against. --- nova/tests/test_adminapi.py | 1 + 1 file changed, 1 insertion(+) diff --git a/nova/tests/test_adminapi.py b/nova/tests/test_adminapi.py index 2b90d49e..4a96a3dd 100644 --- a/nova/tests/test_adminapi.py +++ b/nova/tests/test_adminapi.py @@ -90,6 +90,7 @@ class AdminApiTestCase(test.TestCase): def test_list_blocked_ips(self): """Make sure we can see the external blocks that exist.""" + self.api.block_external_addresses(self.context, '1.1.1.2/32') result = self.api.describe_external_address_blocks(self.context) num = len(db.provider_fw_rule_get_all(self.context)) # we only list IP, not tcp/udp/icmp rules From 173359fd344d36ba514d36863714c15c38e19bd1 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Thu, 23 Jun 2011 14:45:37 -0400 Subject: [PATCH 064/105] Make firewall rules tests idempotent, move IPy=>netaddr, add deltete test. --- nova/tests/test_adminapi.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/nova/tests/test_adminapi.py b/nova/tests/test_adminapi.py index 4a96a3dd..ce826fd5 100644 --- a/nova/tests/test_adminapi.py +++ b/nova/tests/test_adminapi.py @@ -85,6 +85,7 @@ class AdminApiTestCase(test.TestCase): def test_block_external_ips(self): """Make sure provider firewall rules are created.""" result = self.api.block_external_addresses(self.context, '1.1.1.1/32') + self.api.remove_external_address_block(self.context, '1.1.1.1/32') self.assertEqual('OK', result['status']) self.assertEqual('Added 3 rules', result['message']) @@ -93,5 +94,18 @@ class AdminApiTestCase(test.TestCase): self.api.block_external_addresses(self.context, '1.1.1.2/32') result = self.api.describe_external_address_blocks(self.context) num = len(db.provider_fw_rule_get_all(self.context)) + self.api.remove_external_address_block(self.context, '1.1.1.2/32') # we only list IP, not tcp/udp/icmp rules self.assertEqual(num / 3, len(result['externalIpBlockInfo'])) + + def test_remove_ip_block(self): + """Remove ip blocks.""" + result = self.api.block_external_addresses(self.context, '1.1.1.3/32') + self.assertEqual('OK', result['status']) + num0 = len(db.provider_fw_rule_get_all(self.context)) + result = self.api.remove_external_address_block(self.context, + '1.1.1.3/32') + self.assertEqual('OK', result['status']) + self.assertEqual('Deleted 3 rules', result['message']) + num1 = len(db.provider_fw_rule_get_all(self.context)) + self.assert_(num1 < num0) From 5a827e6e20b8a0c6d5f0e92fa53f41dc27a957d1 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Thu, 23 Jun 2011 14:52:58 -0400 Subject: [PATCH 065/105] libvirt test for deleting provider firewall rules. --- nova/tests/test_libvirt.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/nova/tests/test_libvirt.py b/nova/tests/test_libvirt.py index ee94d3c1..d12e2106 100644 --- a/nova/tests/test_libvirt.py +++ b/nova/tests/test_libvirt.py @@ -1115,6 +1115,13 @@ class IptablesFirewallTestCase(test.TestCase): provjump_rules.append(rule) self.assertEqual(1, len(provjump_rules)) + # remove a rule from the db, cast to compute to refresh rule + db.provider_fw_rule_destroy(admin_ctxt, provider_fw1['id']) + self.fw.refresh_provider_fw_rules() + rules = [rule for rule in self.fw.iptables.ipv4['filter'].rules + if rule.chain == 'provider'] + self.assertEqual(1, len(rules)) + class NWFilterTestCase(test.TestCase): def setUp(self): From d3648e45ea5b9576532f155b0bf09b9163d93f4c Mon Sep 17 00:00:00 2001 From: Brian Lamar Date: Thu, 23 Jun 2011 21:31:00 -0400 Subject: [PATCH 066/105] Created Bootstrapper to handle Nova bootstrapping logic. --- bin/nova-api | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/bin/nova-api b/bin/nova-api index 121f6f9a..ea99a1b4 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -25,17 +25,18 @@ Starts both the EC2 and OpenStack APIs in separate processes. import sys -import nova.log import nova.service +import nova.utils def main(): """Launch EC2 and OSAPI services.""" - launcher = nova.service.Launcher(sys.argv) + nova.utils.Bootstrapper.bootstrap_binary(sys.argv) ec2 = nova.service.WSGIService("ec2") osapi = nova.service.WSGIService("osapi") + launcher = nova.service.Launcher() launcher.launch_service(ec2) launcher.launch_service(osapi) From 63f22bfe684d00755c1d5589dd602981166a2e85 Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Thu, 23 Jun 2011 21:59:54 -0700 Subject: [PATCH 067/105] missed passing an argument to consume_resources --- nova/scheduler/zone_aware_scheduler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index 70cb83e8..073bdd3b 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -250,7 +250,7 @@ class ZoneAwareScheduler(driver.Scheduler): weights.sort(key=operator.itemgetter('weight')) best_weight = weights[0] weighted.append(best_weight) - self.consume_resources(best_weight['capabilities'], + self.consume_resources(topic, best_weight['capabilities'], instance_type) # Next, tack on the best weights from the child zones ... From 101c2b0a9cdf8e9c5ffeae51747449655cefe025 Mon Sep 17 00:00:00 2001 From: Lorin Hochstein Date: Fri, 24 Jun 2011 01:34:47 -0400 Subject: [PATCH 068/105] pep8 fixes --- nova/scheduler/host_filter.py | 24 ++++++++++++++++++++++-- nova/tests/scheduler/test_host_filter.py | 24 +++++++++++++++++++++++- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/nova/scheduler/host_filter.py b/nova/scheduler/host_filter.py index bd6b2660..7d4b9ad9 100644 --- a/nova/scheduler/host_filter.py +++ b/nova/scheduler/host_filter.py @@ -93,6 +93,22 @@ class InstanceTypeFilter(HostFilter): """Use instance_type to filter hosts.""" return (self._full_name(), instance_type) + def _satisfies_extra_specs(self, capabilities, instance_type): + """Check that the capabilities provided by the compute service + satisfy the extra specs associated with the instance type""" + + # Note(lorinh): For now, we are just checking exact matching on the + # values. Later on, we want to handle numerical + # values so we can represent things like number of GPU cards + try: + for key, value in instance_type['extra_specs'].iteritems(): + if capabilities[key] != value: + return False + except KeyError: + return False + + return True + def filter_hosts(self, zone_manager, query): """Return a list of hosts that can create instance_type.""" instance_type = query @@ -103,8 +119,12 @@ class InstanceTypeFilter(HostFilter): disk_bytes = capabilities['disk_available'] spec_ram = instance_type['memory_mb'] spec_disk = instance_type['local_gb'] - if host_ram_mb >= spec_ram and disk_bytes >= spec_disk: - selected_hosts.append((host, capabilities)) + extra_specs = instance_type['extra_specs'] + + if host_ram_mb >= spec_ram and \ + disk_bytes >= spec_disk and \ + self._satisfies_extra_specs(capabilities, instance_type): + selected_hosts.append((host, capabilities)) return selected_hosts #host entries (currently) are like: diff --git a/nova/tests/scheduler/test_host_filter.py b/nova/tests/scheduler/test_host_filter.py index 10eafde0..75a2cb21 100644 --- a/nova/tests/scheduler/test_host_filter.py +++ b/nova/tests/scheduler/test_host_filter.py @@ -67,13 +67,24 @@ class HostFilterTestCase(test.TestCase): flavorid=1, swap=500, rxtx_quota=30000, - rxtx_cap=200) + rxtx_cap=200, + extra_specs={}) + self.gpu_instance_type = dict(name='tiny.gpu', + memory_mb=50, + vcpus=10, + local_gb=500, + flavorid=2, + swap=500, + rxtx_quota=30000, + rxtx_cap=200, + extra_specs={'gpu': 'nvidia'}) self.zone_manager = FakeZoneManager() states = {} for x in xrange(10): states['host%02d' % (x + 1)] = {'compute': self._host_caps(x)} self.zone_manager.service_states = states + self.zone_manager.service_states['host07']['compute']['gpu'] = 'nvidia' def tearDown(self): FLAGS.default_host_filter = self.old_flag @@ -116,6 +127,17 @@ class HostFilterTestCase(test.TestCase): self.assertEquals('host05', just_hosts[0]) self.assertEquals('host10', just_hosts[5]) + def test_instance_type_filter_extra_specs(self): + hf = host_filter.InstanceTypeFilter() + # filter all hosts that can support 50 ram and 500 disk + name, cooked = hf.instance_type_to_filter(self.gpu_instance_type) + self.assertEquals('nova.scheduler.host_filter.InstanceTypeFilter', + name) + hosts = hf.filter_hosts(self.zone_manager, cooked) + self.assertEquals(1, len(hosts)) + just_hosts = [host for host, caps in hosts] + self.assertEquals('host07', just_hosts[0]) + def test_json_filter(self): hf = host_filter.JsonFilter() # filter all hosts that can support 50 ram and 500 disk From 2ee0bad326aa8f3150de573b52e4bb29a0a2ea82 Mon Sep 17 00:00:00 2001 From: Lorin Hochstein Date: Fri, 24 Jun 2011 01:44:22 -0400 Subject: [PATCH 069/105] Dealing with cases where extra_specs wasn't defined --- nova/scheduler/host_filter.py | 4 ++++ nova/tests/test_host_filter.py | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/nova/scheduler/host_filter.py b/nova/scheduler/host_filter.py index 7d4b9ad9..9c396cc0 100644 --- a/nova/scheduler/host_filter.py +++ b/nova/scheduler/host_filter.py @@ -97,9 +97,13 @@ class InstanceTypeFilter(HostFilter): """Check that the capabilities provided by the compute service satisfy the extra specs associated with the instance type""" + if 'extra_specs' not in instance_type: + return True + # Note(lorinh): For now, we are just checking exact matching on the # values. Later on, we want to handle numerical # values so we can represent things like number of GPU cards + try: for key, value in instance_type['extra_specs'].iteritems(): if capabilities[key] != value: diff --git a/nova/tests/test_host_filter.py b/nova/tests/test_host_filter.py index 3361c7b7..438f3e52 100644 --- a/nova/tests/test_host_filter.py +++ b/nova/tests/test_host_filter.py @@ -67,7 +67,8 @@ class HostFilterTestCase(test.TestCase): flavorid=1, swap=500, rxtx_quota=30000, - rxtx_cap=200) + rxtx_cap=200, + extra_specs={}) self.zone_manager = FakeZoneManager() states = {} From 47b4f75c43709f7cdd202e994a04f076b40fa889 Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Thu, 23 Jun 2011 22:48:44 -0700 Subject: [PATCH 070/105] debug logging of number of instances to build in scheduler --- nova/scheduler/zone_aware_scheduler.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index 073bdd3b..a747526d 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -180,18 +180,21 @@ class ZoneAwareScheduler(driver.Scheduler): request_spec, kwargs) return None + num_instances = request_spec['num_instances'] + LOG.debug(_("Attemping to build %d instance%s") % + (num_instances, "" if num_instances == 1 else "s")) + # Create build plan and provision ... build_plan = self.select(context, request_spec) if not build_plan: raise driver.NoValidHost(_('No hosts were available')) - for num in xrange(request_spec['num_instances']): + for num in xrange(num_instances): if not build_plan: break - item = build_plan.pop(0) - self._provision_resource(context, item, instance_id, request_spec, - kwargs) + self._provision_resource(context, item, instance_id, + request_spec, kwargs) # Returning None short-circuits the routing to Compute (since # we've already done it here) From feccd2a845c9b75837fd1c7e95475ecbbca5a852 Mon Sep 17 00:00:00 2001 From: Yuriy Taraday Date: Fri, 24 Jun 2011 09:54:38 +0400 Subject: [PATCH 071/105] Unwind last commit, force anyjson to use our serialization methods. --- bin/nova-manage | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/bin/nova-manage b/bin/nova-manage index 0147ae21..e09ea495 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -874,10 +874,10 @@ class InstanceTypeCommands(object): try: instance_types.create(name, memory, vcpus, local_gb, flavorid, swap, rxtx_quota, rxtx_cap) - except exception.InvalidInputException: - print "Must supply valid parameters to create instance_type" - print e - sys.exit(1) + #except exception.InvalidInputException: + # print "Must supply valid parameters to create instance_type" + # print e + # sys.exit(1) except exception.ApiError, e: print "\n\n" print "\n%s" % e From c24dcbc30b931cfea2ddf9e1968b16ef0c7df3a0 Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Thu, 23 Jun 2011 22:55:45 -0700 Subject: [PATCH 072/105] typo in least cost scheduler --- nova/scheduler/least_cost.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/scheduler/least_cost.py b/nova/scheduler/least_cost.py index 72db2fd1..9376631e 100644 --- a/nova/scheduler/least_cost.py +++ b/nova/scheduler/least_cost.py @@ -63,7 +63,7 @@ def compute_fill_first_cost_fn(host): class LeastCostScheduler(zone_aware_scheduler.ZoneAwareScheduler): def __init__(self, *args, **kwargs): self.cost_fns_cache = {} - super(LeastCoastScheduler, self).__init__(*args, **kwargs) + super(LeastCostScheduler, self).__init__(*args, **kwargs) def get_cost_fns(self, topic): """Returns a list of tuples containing weights and cost functions to From 8ea7a715d7fd8390c00e702b7cfdba72bdaf08eb Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Thu, 23 Jun 2011 23:00:15 -0700 Subject: [PATCH 073/105] more typos --- nova/scheduler/zone_aware_scheduler.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index a747526d..8f218c15 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -303,8 +303,8 @@ class ZoneAwareScheduler(driver.Scheduler): for host, services in host_list: if topic not in services: continue - if filter_func(host, services['topic'], request_spec): - filtered_hosts.append((host, services['topic'])) + if filter_func(host, services[topic], request_spec): + filtered_hosts.append((host, services[topic])) return filtered_hosts def weigh_hosts(self, topic, request_spec, hosts): From b07544045f06ef2ada44b3bbae5d84dea5b33ed9 Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Thu, 23 Jun 2011 23:05:12 -0700 Subject: [PATCH 074/105] requested_mem typo --- nova/scheduler/zone_aware_scheduler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index 8f218c15..769b2dd0 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -279,7 +279,7 @@ class ZoneAwareScheduler(driver.Scheduler): is acceptable for scheduling. """ instance_type = request_spec['instance_type'] - reqested_mem = instance_type['memory_mb'] + requested_mem = instance_type['memory_mb'] return capabilities['host_memory_free'] >= requested_mem def filter_hosts(self, topic, request_spec, host_list=None): From 25c3ae3534debf4be4455d49e8aeba1b582b0150 Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Thu, 23 Jun 2011 23:38:32 -0700 Subject: [PATCH 075/105] LeastCostScheduler wasn't checking for topic cost functions correctly. Added support so that --least_cost_scheduler_cost_functions only needs to have method names specified, instead of the full blown version with module and class name. Still works the old way, too. --- nova/scheduler/least_cost.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/nova/scheduler/least_cost.py b/nova/scheduler/least_cost.py index 9376631e..6f5eb66f 100644 --- a/nova/scheduler/least_cost.py +++ b/nova/scheduler/least_cost.py @@ -75,8 +75,15 @@ class LeastCostScheduler(zone_aware_scheduler.ZoneAwareScheduler): cost_fns = [] for cost_fn_str in FLAGS.least_cost_scheduler_cost_functions: - if not cost_fn_str.startswith('%s_' % topic) and \ - not cost_fn_str.startswith('noop'): + if '.' in cost_fn_str: + short_name = cost_fn_str.split('.')[-1] + else: + short_name = cost_fn_str + cost_fn_str = "%s.%s.%s" % ( + __name__, self.__class__.__name__, short_name) + + if not (short_name.startswith('%s_' % topic) or + short_name.startswith('noop')): continue try: From 26348f56fcd1ed3bb980c6b051636b12106f2197 Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Fri, 24 Jun 2011 00:26:55 -0700 Subject: [PATCH 076/105] on 2nd run through filter_hosts, we've already accounted for the topic memory needs converted to Bytes from MB --- nova/scheduler/zone_aware_scheduler.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index 769b2dd0..e6383b20 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -244,6 +244,8 @@ class ZoneAwareScheduler(driver.Scheduler): # may have been consumed from a previous build.. host_list = self.filter_hosts(topic, request_spec, host_list) if not host_list: + LOG.warn(_("Ran out of available hosts after weighing " + "%d of %d instances") % (i, num_instances)) break # then weigh the selected hosts. @@ -279,7 +281,7 @@ class ZoneAwareScheduler(driver.Scheduler): is acceptable for scheduling. """ instance_type = request_spec['instance_type'] - requested_mem = instance_type['memory_mb'] + requested_mem = instance_type['memory_mb'] * 1024 * 1024 return capabilities['host_memory_free'] >= requested_mem def filter_hosts(self, topic, request_spec, host_list=None): @@ -297,14 +299,20 @@ class ZoneAwareScheduler(driver.Scheduler): filter_func = getattr(self, '%s_filter' % topic, _default_filter) - filtered_hosts = [] if host_list is None: + first_run = True host_list = self.zone_manager.service_states.iteritems() + else: + first_run = False + + filtered_hosts = [] for host, services in host_list: - if topic not in services: - continue - if filter_func(host, services[topic], request_spec): - filtered_hosts.append((host, services[topic])) + if first_run: + if topic not in services: + continue + services = services['topic'] + if filter_func(host, services, request_spec): + filtered_hosts.append((host, services)) return filtered_hosts def weigh_hosts(self, topic, request_spec, hosts): @@ -318,7 +326,7 @@ class ZoneAwareScheduler(driver.Scheduler): def compute_consume(self, capabilities, instance_type): """Consume compute resources for selected host""" - requested_mem = max(instance_type['memory_mb'], 0) + requested_mem = max(instance_type['memory_mb'], 0) * 1024 * 1024 capabilities['host_memory_free'] -= requested_mem def consume_resources(self, topic, capabilities, instance_type): From 369d79dc66024b19287748838b92e168d85bebb5 Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Fri, 24 Jun 2011 00:30:58 -0700 Subject: [PATCH 077/105] same typo i made before! --- nova/scheduler/zone_aware_scheduler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index e6383b20..e24c2256 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -310,7 +310,7 @@ class ZoneAwareScheduler(driver.Scheduler): if first_run: if topic not in services: continue - services = services['topic'] + services = services[topic] if filter_func(host, services, request_spec): filtered_hosts.append((host, services)) return filtered_hosts From 5bdfaf95ff450ff97326e3c04e7f0b2eec11f931 Mon Sep 17 00:00:00 2001 From: Yuriy Taraday Date: Fri, 24 Jun 2011 15:20:24 +0400 Subject: [PATCH 078/105] Add reconnect on server fail to LDAP driver. --- nova/auth/ldapdriver.py | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/nova/auth/ldapdriver.py b/nova/auth/ldapdriver.py index e9532473..4af91b61 100644 --- a/nova/auth/ldapdriver.py +++ b/nova/auth/ldapdriver.py @@ -101,6 +101,41 @@ def sanitize(fn): return _wrapped +class LDAPWrapper(object): + def __init__(self, ldap, url, user, password): + self.ldap = ldap + self.url = url + self.user = user + self.password = password + self.conn = None + + def __wrap_reconnect(f): + def inner(self, *args, **kwargs): + if self.conn is None: + self.connect() + return f(self.conn)(*args, **kwargs) + else: + try: + return f(self.conn)(*args, **kwargs) + except self.ldap.SERVER_DOWN: + self.connect() + return f(self.conn)(*args, **kwargs) + return inner + + def connect(self): + try: + self.conn = self.ldap.initialize(self.url) + self.conn.bind_s(self.user, self.password) + except self.ldap.SERVER_DOWN: + self.conn = None + raise + + search_s = __wrap_reconnect(lambda conn: conn.search_s) + add_s = __wrap_reconnect(lambda conn: conn.add_s) + delete_s = __wrap_reconnect(lambda conn: conn.delete_s) + modify_s = __wrap_reconnect(lambda conn: conn.modify_s) + + class LdapDriver(object): """Ldap Auth driver @@ -124,8 +159,8 @@ class LdapDriver(object): LdapDriver.project_objectclass = 'novaProject' self.__cache = None if LdapDriver.conn is None: - LdapDriver.conn = self.ldap.initialize(FLAGS.ldap_url) - LdapDriver.conn.simple_bind_s(FLAGS.ldap_user_dn, + LdapDriver.conn = LDAPWrapper(self.ldap, FLAGS.ldap_url, + FLAGS.ldap_user_dn, FLAGS.ldap_password) if LdapDriver.mc is None: LdapDriver.mc = memcache.Client(FLAGS.memcached_servers, debug=0) From 4f6cdd7f52a581a500d045db401f7f621b939074 Mon Sep 17 00:00:00 2001 From: Yuriy Taraday Date: Fri, 24 Jun 2011 15:26:15 +0400 Subject: [PATCH 079/105] Use simple_bind_s instead of bind_s --- nova/auth/ldapdriver.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/auth/ldapdriver.py b/nova/auth/ldapdriver.py index 4af91b61..bc37d2d8 100644 --- a/nova/auth/ldapdriver.py +++ b/nova/auth/ldapdriver.py @@ -125,7 +125,7 @@ class LDAPWrapper(object): def connect(self): try: self.conn = self.ldap.initialize(self.url) - self.conn.bind_s(self.user, self.password) + self.conn.simple_bind_s(self.user, self.password) except self.ldap.SERVER_DOWN: self.conn = None raise From 3259bd06655132d68aff8f7830f3fc0d9ca1e7f4 Mon Sep 17 00:00:00 2001 From: Yuriy Taraday Date: Fri, 24 Jun 2011 15:55:06 +0400 Subject: [PATCH 080/105] Add reconnect test. --- nova/auth/fakeldap.py | 24 ++++++++++++++++++++++++ nova/tests/test_auth.py | 9 +++++++++ 2 files changed, 33 insertions(+) diff --git a/nova/auth/fakeldap.py b/nova/auth/fakeldap.py index 79afb910..f1e76927 100644 --- a/nova/auth/fakeldap.py +++ b/nova/auth/fakeldap.py @@ -100,6 +100,11 @@ class OBJECT_CLASS_VIOLATION(Exception): # pylint: disable=C0103 pass +class SERVER_DOWN(Exception): # pylint: disable=C0103 + """Duplicate exception class from real LDAP module.""" + pass + + def initialize(_uri): """Opens a fake connection with an LDAP server.""" return FakeLDAP() @@ -202,25 +207,38 @@ def _to_json(unencoded): return json.dumps(list(unencoded)) +server_fail = False + + class FakeLDAP(object): """Fake LDAP connection.""" def simple_bind_s(self, dn, password): """This method is ignored, but provided for compatibility.""" + if server_fail: + raise SERVER_DOWN pass def unbind_s(self): """This method is ignored, but provided for compatibility.""" + if server_fail: + raise SERVER_DOWN pass def add_s(self, dn, attr): """Add an object with the specified attributes at dn.""" + if server_fail: + raise SERVER_DOWN + key = "%s%s" % (self.__prefix, dn) value_dict = dict([(k, _to_json(v)) for k, v in attr]) Store.instance().hmset(key, value_dict) def delete_s(self, dn): """Remove the ldap object at specified dn.""" + if server_fail: + raise SERVER_DOWN + Store.instance().delete("%s%s" % (self.__prefix, dn)) def modify_s(self, dn, attrs): @@ -232,6 +250,9 @@ class FakeLDAP(object): ([MOD_ADD | MOD_DELETE | MOD_REPACE], attribute, value) """ + if server_fail: + raise SERVER_DOWN + store = Store.instance() key = "%s%s" % (self.__prefix, dn) @@ -255,6 +276,9 @@ class FakeLDAP(object): fields -- fields to return. Returns all fields if not specified """ + if server_fail: + raise SERVER_DOWN + if scope != SCOPE_BASE and scope != SCOPE_SUBTREE: raise NotImplementedError(str(scope)) store = Store.instance() diff --git a/nova/tests/test_auth.py b/nova/tests/test_auth.py index 7d00bddf..4aebbe94 100644 --- a/nova/tests/test_auth.py +++ b/nova/tests/test_auth.py @@ -25,6 +25,7 @@ from nova import log as logging from nova import test from nova.auth import manager from nova.api.ec2 import cloud +from nova.auth import fakeldap FLAGS = flags.FLAGS LOG = logging.getLogger('nova.tests.auth_unittest') @@ -369,6 +370,14 @@ class _AuthManagerBaseTestCase(test.TestCase): class AuthManagerLdapTestCase(_AuthManagerBaseTestCase): auth_driver = 'nova.auth.ldapdriver.FakeLdapDriver' + def test_reconnect_on_server_failure(self): + self.manager.get_users() + fakeldap.server_fail = True + with self.assertRaises(fakeldap.SERVER_DOWN): + self.manager.get_users() + fakeldap.server_fail = False + self.manager.get_users() + class AuthManagerDbTestCase(_AuthManagerBaseTestCase): auth_driver = 'nova.auth.dbdriver.DbDriver' From fa350ffee23822641baf5da58b8ec8e88ecb19a6 Mon Sep 17 00:00:00 2001 From: Lorin Hochstein Date: Fri, 24 Jun 2011 10:52:59 -0400 Subject: [PATCH 081/105] Edited the host filter test case for extra specs --- nova/scheduler/host_filter.py | 4 ++-- nova/tests/scheduler/test_host_filter.py | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/nova/scheduler/host_filter.py b/nova/scheduler/host_filter.py index 9c396cc0..5f61f945 100644 --- a/nova/scheduler/host_filter.py +++ b/nova/scheduler/host_filter.py @@ -103,7 +103,7 @@ class InstanceTypeFilter(HostFilter): # Note(lorinh): For now, we are just checking exact matching on the # values. Later on, we want to handle numerical # values so we can represent things like number of GPU cards - + try: for key, value in instance_type['extra_specs'].iteritems(): if capabilities[key] != value: @@ -128,7 +128,7 @@ class InstanceTypeFilter(HostFilter): if host_ram_mb >= spec_ram and \ disk_bytes >= spec_disk and \ self._satisfies_extra_specs(capabilities, instance_type): - selected_hosts.append((host, capabilities)) + selected_hosts.append((host, capabilities)) return selected_hosts #host entries (currently) are like: diff --git a/nova/tests/scheduler/test_host_filter.py b/nova/tests/scheduler/test_host_filter.py index 75a2cb21..b1892dab 100644 --- a/nova/tests/scheduler/test_host_filter.py +++ b/nova/tests/scheduler/test_host_filter.py @@ -77,14 +77,26 @@ class HostFilterTestCase(test.TestCase): swap=500, rxtx_quota=30000, rxtx_cap=200, - extra_specs={'gpu': 'nvidia'}) + extra_specs={'xpu_arch': 'fermi', + 'xpu_info': 'Tesla 2050'}) self.zone_manager = FakeZoneManager() states = {} for x in xrange(10): states['host%02d' % (x + 1)] = {'compute': self._host_caps(x)} self.zone_manager.service_states = states - self.zone_manager.service_states['host07']['compute']['gpu'] = 'nvidia' + + # Add some extra capabilities to some hosts + host07 = self.zone_manager.service_states['host07']['compute'] + host07['xpu_arch'] = 'fermi' + host07['xpu_info'] = 'Tesla 2050' + + host08 = self.zone_manager.service_states['host08']['compute'] + host08['xpu_arch'] = 'radeon' + + host09 = self.zone_manager.service_states['host09']['compute'] + host09['xpu_arch'] = 'fermi' + host09['xpu_info'] = 'Tesla 2150' def tearDown(self): FLAGS.default_host_filter = self.old_flag From 3ee2162cdd717a8facc9de35eafaae5a099dddf6 Mon Sep 17 00:00:00 2001 From: Ilya Alekseyev Date: Fri, 24 Jun 2011 23:55:18 +0400 Subject: [PATCH 083/105] stub tests --- Authors | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Authors b/Authors index 94fcf7f5..bf2ba81d 100644 --- a/Authors +++ b/Authors @@ -29,7 +29,7 @@ Ewan Mellor Gabe Westmaas Hisaharu Ishii Hisaki Ohara -Ilya Alekseyev +Ilya Alekseyev Isaku Yamahata Jason Cannavale Jason Koelker From 7c9545f919b8b751f3a490b702750434a3223354 Mon Sep 17 00:00:00 2001 From: Ilya Alekseyev Date: Sat, 25 Jun 2011 00:33:40 +0400 Subject: [PATCH 084/105] some tests --- Authors | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Authors b/Authors index bf2ba81d..09064051 100644 --- a/Authors +++ b/Authors @@ -29,7 +29,7 @@ Ewan Mellor Gabe Westmaas Hisaharu Ishii Hisaki Ohara -Ilya Alekseyev +Ilya Alekseyev Isaku Yamahata Jason Cannavale Jason Koelker From c00e3bcad01a740a0bf58536c65e1d5ff76e45f1 Mon Sep 17 00:00:00 2001 From: Ilya Alekseyev Date: Sat, 25 Jun 2011 03:03:17 +0400 Subject: [PATCH 085/105] fixes --- Authors | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Authors b/Authors index 09064051..c4281ca1 100644 --- a/Authors +++ b/Authors @@ -22,14 +22,14 @@ David Pravec Dean Troyer Devin Carlen Ed Leafe -Eldar Nugaev +Eldar Nugaev Eric Day Eric Windisch Ewan Mellor Gabe Westmaas Hisaharu Ishii Hisaki Ohara -Ilya Alekseyev +Ilya Alekseyev Isaku Yamahata Jason Cannavale Jason Koelker @@ -53,6 +53,7 @@ Kei Masumoto Ken Pepple Kevin Bringard Kevin L. Mitchell +Kirill Shileev Koji Iida Lorin Hochstein Lvov Maxim From d1efb8058ca1c747262cfc7fcef42bb316d3a50c Mon Sep 17 00:00:00 2001 From: Ilya Alekseyev Date: Sat, 25 Jun 2011 04:45:15 +0400 Subject: [PATCH 086/105] mailmap --- .mailmap | 2 ++ Authors | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.mailmap b/.mailmap index 3f0238ee..89094fbb 100644 --- a/.mailmap +++ b/.mailmap @@ -47,3 +47,5 @@ + + diff --git a/Authors b/Authors index c4281ca1..21a9bf94 100644 --- a/Authors +++ b/Authors @@ -29,7 +29,7 @@ Ewan Mellor Gabe Westmaas Hisaharu Ishii Hisaki Ohara -Ilya Alekseyev +Ilya Alekseyev Isaku Yamahata Jason Cannavale Jason Koelker From 8fce7d2f1696d936992c3bf7dfcbb28f75cf5039 Mon Sep 17 00:00:00 2001 From: Ilya Alekseyev Date: Sat, 25 Jun 2011 04:47:06 +0400 Subject: [PATCH 087/105] mailmap --- .mailmap | 2 ++ Authors | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.mailmap b/.mailmap index 89094fbb..6673d0a2 100644 --- a/.mailmap +++ b/.mailmap @@ -49,3 +49,5 @@ + + \ No newline at end of file diff --git a/Authors b/Authors index 21a9bf94..c3a65f1b 100644 --- a/Authors +++ b/Authors @@ -22,7 +22,7 @@ David Pravec Dean Troyer Devin Carlen Ed Leafe -Eldar Nugaev +Eldar Nugaev Eric Day Eric Windisch Ewan Mellor @@ -53,7 +53,7 @@ Kei Masumoto Ken Pepple Kevin Bringard Kevin L. Mitchell -Kirill Shileev +Kirill Shileev Koji Iida Lorin Hochstein Lvov Maxim From a17300baccb085b4e46dd24cf620f727a8d8008d Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Sat, 25 Jun 2011 17:26:38 -0700 Subject: [PATCH 088/105] only create the db if it doesn't exist, add an option -r to run_tests.py to delete it --- run_tests.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/run_tests.py b/run_tests.py index bb33f913..fd836967 100644 --- a/run_tests.py +++ b/run_tests.py @@ -69,7 +69,6 @@ from nose import core from nose import result from nova import log as logging -from nova.tests import fake_flags class _AnsiColorizer(object): @@ -211,11 +210,11 @@ class NovaTestResult(result.TextTestResult): break sys.stdout = stdout - # NOTE(lorinh): Initialize start_time in case a sqlalchemy-migrate - # error results in it failing to be initialized later. Otherwise, + # NOTE(lorinh): Initialize start_time in case a sqlalchemy-migrate + # error results in it failing to be initialized later. Otherwise, # _handleElapsedTime will fail, causing the wrong error message to # be outputted. - self.start_time = time.time() + self.start_time = time.time() def getDescription(self, test): return str(test) From 3520d508486305efe082b2831d23e559c69f7c90 Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Mon, 27 Jun 2011 15:05:37 -0700 Subject: [PATCH 089/105] Made _issue_novaclient_command() behave better. Fixed a bunch of tests. --- nova/scheduler/api.py | 49 +++++++++++++------ nova/scheduler/zone_aware_scheduler.py | 4 +- .../scheduler/test_least_cost_scheduler.py | 11 +++-- .../scheduler/test_zone_aware_scheduler.py | 35 ++++++------- 4 files changed, 58 insertions(+), 41 deletions(-) diff --git a/nova/scheduler/api.py b/nova/scheduler/api.py index 0aed7568..5d62beb8 100644 --- a/nova/scheduler/api.py +++ b/nova/scheduler/api.py @@ -162,32 +162,53 @@ def child_zone_helper(zone_list, func): _wrap_method(_process, func), zone_list)] -def _issue_novaclient_command(nova, zone, collection, method_name, item_id): +def _issue_novaclient_command(nova, zone, collection, + method_name, *args, **kwargs): """Use novaclient to issue command to a single child zone. - One of these will be run in parallel for each child zone.""" + One of these will be run in parallel for each child zone. + """ manager = getattr(nova, collection) - result = None - try: + + # NOTE(comstud): This is not ideal, but we have to do this based on + # how novaclient is implemented right now. + # 'find' is special cased as novaclient requires kwargs for it to + # filter on a 'get_all'. + # Every other method first needs to do a 'get' on the first argument + # passed, which should be a UUID. If it's 'get' itself that we want, + # we just return the result. Otherwise, we next call the real method + # that's wanted... passing other arguments that may or may not exist. + if method_name in ['find', 'findall']: try: - result = manager.get(item_id) - except ValueError, e: - result = manager.find(name=item_id) + return getattr(manager, method_name)(**kwargs) + except novaclient.NotFound: + url = zone.api_url + LOG.debug(_("%(collection)s.%(method_name)s didn't find " + "anything matching '%(kwargs)s' on '%(url)s'" % + locals())) + return None + + args = list(args) + # pop off the UUID to look up + item = args.pop(0) + try: + result = manager.get(item) except novaclient.NotFound: url = zone.api_url - LOG.debug(_("%(collection)s '%(item_id)s' not found on '%(url)s'" % + LOG.debug(_("%(collection)s '%(item)s' not found on '%(url)s'" % locals())) return None - if method_name.lower() not in ['get', 'find']: - result = getattr(result, method_name)() + if method_name.lower() != 'get': + # if we're doing something other than 'get', call it passing args. + result = getattr(result, method_name)(*args, **kwargs) return result -def wrap_novaclient_function(f, collection, method_name, item_id): - """Appends collection, method_name and item_id to the incoming +def wrap_novaclient_function(f, collection, method_name, *args, **kwargs): + """Appends collection, method_name and arguments to the incoming (nova, zone) call from child_zone_helper.""" def inner(nova, zone): - return f(nova, zone, collection, method_name, item_id) + return f(nova, zone, collection, method_name, *args, **kwargs) return inner @@ -220,7 +241,7 @@ class reroute_compute(object): the wrapped method. (This ensures that zone-local code can continue to use integer IDs). - 4. If the item was not found, we delgate the call to a child zone + 4. If the item was not found, we delegate the call to a child zone using the UUID. """ def __init__(self, method_name): diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index e24c2256..eb116fac 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -180,7 +180,7 @@ class ZoneAwareScheduler(driver.Scheduler): request_spec, kwargs) return None - num_instances = request_spec['num_instances'] + num_instances = request_spec.get('num_instances', 1) LOG.debug(_("Attemping to build %d instance%s") % (num_instances, "" if num_instances == 1 else "s")) @@ -227,7 +227,7 @@ class ZoneAwareScheduler(driver.Scheduler): raise NotImplemented(_("Zone Aware Scheduler only understands " "Compute nodes (for now)")) - num_instances = request_spec['num_instances'] + num_instances = request_spec.get('num_instances', 1) instance_type = request_spec['instance_type'] weighted = [] diff --git a/nova/tests/scheduler/test_least_cost_scheduler.py b/nova/tests/scheduler/test_least_cost_scheduler.py index 9a5318ae..49791053 100644 --- a/nova/tests/scheduler/test_least_cost_scheduler.py +++ b/nova/tests/scheduler/test_least_cost_scheduler.py @@ -122,15 +122,16 @@ class LeastCostSchedulerTestCase(test.TestCase): for hostname, caps in hosts] self.assertWeights(expected, num, request_spec, hosts) - def test_fill_first_cost_fn(self): + def test_compute_fill_first_cost_fn(self): FLAGS.least_cost_scheduler_cost_functions = [ - 'nova.scheduler.least_cost.fill_first_cost_fn', + 'nova.scheduler.least_cost.compute_fill_first_cost_fn', ] - FLAGS.fill_first_cost_fn_weight = 1 + FLAGS.compute_fill_first_cost_fn_weight = 1 num = 1 - request_spec = {} - hosts = self.sched.filter_hosts(num, request_spec) + instance_type = {'memory_mb': 1024} + request_spec = {'instance_type': instance_type} + hosts = self.sched.filter_hosts('compute', request_spec, None) expected = [] for idx, (hostname, caps) in enumerate(hosts): diff --git a/nova/tests/scheduler/test_zone_aware_scheduler.py b/nova/tests/scheduler/test_zone_aware_scheduler.py index 37c6488c..b2599f1b 100644 --- a/nova/tests/scheduler/test_zone_aware_scheduler.py +++ b/nova/tests/scheduler/test_zone_aware_scheduler.py @@ -55,29 +55,21 @@ def fake_zone_manager_service_states(num_hosts): class FakeZoneAwareScheduler(zone_aware_scheduler.ZoneAwareScheduler): - def filter_hosts(self, num, specs): - # NOTE(sirp): this is returning [(hostname, services)] - return self.zone_manager.service_states.items() - - def weigh_hosts(self, num, specs, hosts): - fake_weight = 99 - weighted = [] - for hostname, caps in hosts: - weighted.append(dict(weight=fake_weight, name=hostname)) - return weighted + # No need to stub anything at the moment + pass class FakeZoneManager(zone_manager.ZoneManager): def __init__(self): self.service_states = { 'host1': { - 'compute': {'ram': 1000}, + 'compute': {'host_memory_free': 1000*1024*1024}, }, 'host2': { - 'compute': {'ram': 2000}, + 'compute': {'host_memory_free': 2000*1024*1024}, }, 'host3': { - 'compute': {'ram': 3000}, + 'compute': {'host_memory_free': 3000*1024*1024}, }, } @@ -164,13 +156,17 @@ class ZoneAwareSchedulerTestCase(test.TestCase): sched.set_zone_manager(zm) fake_context = {} - build_plan = sched.select(fake_context, {}) + build_plan = sched.select(fake_context, + {'instance_type': {'memory_mb': 512}, + 'num_instances': 4 }) - self.assertEqual(15, len(build_plan)) + # 4 from local zones, 12 from remotes + self.assertEqual(16, len(build_plan)) - hostnames = [plan_item['name'] - for plan_item in build_plan if 'name' in plan_item] - self.assertEqual(3, len(hostnames)) + hostnames = [plan_item['hostname'] + for plan_item in build_plan if 'hostname' in plan_item] + # 4 local hosts + self.assertEqual(4, len(hostnames)) def test_empty_zone_aware_scheduler(self): """ @@ -185,8 +181,7 @@ class ZoneAwareSchedulerTestCase(test.TestCase): fake_context = {} self.assertRaises(driver.NoValidHost, sched.schedule_run_instance, fake_context, 1, - dict(host_filter=None, - request_spec={'instance_type': {}})) + dict(host_filter=None, instance_type={})) def test_schedule_do_not_schedule_with_hint(self): """ From 2602234e0fed374c2d619741931245e607c269cf Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Mon, 27 Jun 2011 15:17:19 -0700 Subject: [PATCH 090/105] logging fixes --- nova/scheduler/zone_aware_scheduler.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index eb116fac..638072ee 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -181,8 +181,7 @@ class ZoneAwareScheduler(driver.Scheduler): return None num_instances = request_spec.get('num_instances', 1) - LOG.debug(_("Attemping to build %d instance%s") % - (num_instances, "" if num_instances == 1 else "s")) + LOG.debug(_("Attemping to build %d instance(s)") % locals()) # Create build plan and provision ... build_plan = self.select(context, request_spec) @@ -245,7 +244,7 @@ class ZoneAwareScheduler(driver.Scheduler): host_list = self.filter_hosts(topic, request_spec, host_list) if not host_list: LOG.warn(_("Ran out of available hosts after weighing " - "%d of %d instances") % (i, num_instances)) + "%(i)d of %(num_instances)d instances") % locals()) break # then weigh the selected hosts. From 185ffdadb4b5aaab338f642e339ef8e05c94e2ca Mon Sep 17 00:00:00 2001 From: Monsyne Dragon Date: Tue, 28 Jun 2011 08:57:05 +0000 Subject: [PATCH 092/105] Re-merging code for generating system-usages to get around bzr merge braindeadness. --- bin/instance-usage-audit | 127 +++++++++++++++++++++++++++++++++ nova/notifier/test_notifier.py | 28 ++++++++ nova/tests/test_compute.py | 77 ++++++++++++++++++++ 3 files changed, 232 insertions(+) create mode 100755 bin/instance-usage-audit create mode 100644 nova/notifier/test_notifier.py diff --git a/bin/instance-usage-audit b/bin/instance-usage-audit new file mode 100755 index 00000000..1124cf55 --- /dev/null +++ b/bin/instance-usage-audit @@ -0,0 +1,127 @@ +#!/usr/bin/env python +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright (c) 2011 Openstack, LLC. +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +"""Cron script to generate usage notifications for instances neither created + nor destroyed in a given time period. + + Together with the notifications generated by compute on instance + create/delete/resize, over that ime period, this allows an external + system consuming usage notification feeds to calculate instance usage + for each tenant. + + Time periods are specified like so: + [mdy] + + 1m = previous month. If the script is run April 1, it will generate usages + for March 1 thry March 31. + 3m = 3 previous months. + 90d = previous 90 days. + 1y = previous year. If run on Jan 1, it generates usages for + Jan 1 thru Dec 31 of the previous year. +""" + +import datetime +import gettext +import os +import sys +import time + +# If ../nova/__init__.py exists, add ../ to Python search path, so that +# it will override what happens to be installed in /usr/(local/)lib/python... +POSSIBLE_TOPDIR = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), + os.pardir, + os.pardir)) +if os.path.exists(os.path.join(POSSIBLE_TOPDIR, 'nova', '__init__.py')): + sys.path.insert(0, POSSIBLE_TOPDIR) + +gettext.install('nova', unicode=1) + + +from nova import context +from nova import db +from nova import exception +from nova import flags +from nova import log as logging +from nova import utils + +from nova.notifier import api as notifier_api + +FLAGS = flags.FLAGS +flags.DEFINE_string('instance_usage_audit_period', '1m', + 'time period to generate instance usages for.') + +def time_period(period): + today = datetime.date.today() + unit = period[-1] + if unit not in 'mdy': + raise ValueError('Time period must be m, d, or y') + n = int(period[:-1]) + if unit == 'm': + year = today.year - (n//12) + n = n % 12 + if n >= today.month: + year -= 1 + month = 12 + (today.month - n) + else: + month = today.month - n + begin = datetime.datetime(day=1, month=month, year=year) + end = datetime.datetime(day=1, month=today.month, year=today.year) + + elif unit == 'y': + begin = datetime.datetime(day=1, month=1, year=today.year - n) + end = datetime.datetime(day=1, month=1, year=today.year) + + elif unit == 'd': + b = today - datetime.timedelta(days=n) + begin = datetime.datetime(day=b.day, month=b.month, year=b.year) + end = datetime.datetime(day=today.day, + month=today.month, + year=today.year) + + return (begin, end) + +if __name__ == '__main__': + utils.default_flagfile() + flags.FLAGS(sys.argv) + logging.setup() + begin, end = time_period(FLAGS.instance_usage_audit_period) + print "Creating usages for %s until %s" % (str(begin), str(end)) + instances = db.instance_get_active_by_window(context.get_admin_context(), + begin, + end) + print "%s instances" % len(instances) + for instance_ref in instances: + usage_info = dict( + tenant_id=instance_ref['project_id'], + user_id=instance_ref['user_id'], + instance_id=instance_ref['id'], + instance_type=instance_ref['instance_type']['name'], + instance_type_id=instance_ref['instance_type_id'], + display_name=instance_ref['display_name'], + created_at=str(instance_ref['created_at']), + launched_at=str(instance_ref['launched_at']) \ + if instance_ref['launched_at'] else '', + image_id=instance_ref['image_id'], + audit_period_begining=str(begin), + audit_period_ending=str(end)) + notifier_api.notify('compute.%s' % FLAGS.host, + 'compute.instance.exists', + notifier_api.INFO, + usage_info) + + diff --git a/nova/notifier/test_notifier.py b/nova/notifier/test_notifier.py new file mode 100644 index 00000000..d43f43e4 --- /dev/null +++ b/nova/notifier/test_notifier.py @@ -0,0 +1,28 @@ +# Copyright 2011 OpenStack LLC. +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import json + +from nova import flags +from nova import log as logging + +FLAGS = flags.FLAGS + +NOTIFICATIONS = [] + + +def notify(message): + """Test notifier, stores notifications in memory for unittests.""" + NOTIFICATIONS.append(message) diff --git a/nova/tests/test_compute.py b/nova/tests/test_compute.py index 55e7ae0c..30a65a4b 100644 --- a/nova/tests/test_compute.py +++ b/nova/tests/test_compute.py @@ -38,6 +38,7 @@ from nova.compute import manager as compute_manager from nova.compute import power_state from nova.db.sqlalchemy import models from nova.image import local +from nova.notifier import test_notifier LOG = logging.getLogger('nova.tests.compute') FLAGS = flags.FLAGS @@ -63,6 +64,7 @@ class ComputeTestCase(test.TestCase): super(ComputeTestCase, self).setUp() self.flags(connection_type='fake', stub_network=True, + notification_driver='nova.notifier.test_notifier', network_manager='nova.network.manager.FlatManager') self.compute = utils.import_object(FLAGS.compute_manager) self.compute_api = compute.API() @@ -70,6 +72,7 @@ class ComputeTestCase(test.TestCase): self.user = self.manager.create_user('fake', 'fake', 'fake') self.project = self.manager.create_project('fake', 'fake', 'fake') self.context = context.RequestContext('fake', 'fake', False) + test_notifier.NOTIFICATIONS = [] def fake_show(meh, context, id): return {'id': 1, 'properties': {'kernel_id': 1, 'ramdisk_id': 1}} @@ -305,6 +308,50 @@ class ComputeTestCase(test.TestCase): self.assert_(console) self.compute.terminate_instance(self.context, instance_id) + def test_run_instance_usage_notification(self): + """Ensure run instance generates apropriate usage notification""" + instance_id = self._create_instance() + self.compute.run_instance(self.context, instance_id) + self.assertEquals(len(test_notifier.NOTIFICATIONS), 1) + msg = test_notifier.NOTIFICATIONS[0] + self.assertEquals(msg['priority'], 'INFO') + self.assertEquals(msg['event_type'], 'compute.instance.create') + payload = msg['payload'] + self.assertEquals(payload['tenant_id'], self.project.id) + self.assertEquals(payload['user_id'], self.user.id) + self.assertEquals(payload['instance_id'], instance_id) + self.assertEquals(payload['instance_type'], 'm1.tiny') + type_id = instance_types.get_instance_type_by_name('m1.tiny')['id'] + self.assertEquals(str(payload['instance_type_id']), str(type_id)) + self.assertTrue('display_name' in payload) + self.assertTrue('created_at' in payload) + self.assertTrue('launched_at' in payload) + self.assertEquals(payload['image_id'], '1') + self.compute.terminate_instance(self.context, instance_id) + + def test_terminate_usage_notification(self): + """Ensure terminate_instance generates apropriate usage notification""" + instance_id = self._create_instance() + self.compute.run_instance(self.context, instance_id) + test_notifier.NOTIFICATIONS = [] + self.compute.terminate_instance(self.context, instance_id) + + self.assertEquals(len(test_notifier.NOTIFICATIONS), 1) + msg = test_notifier.NOTIFICATIONS[0] + self.assertEquals(msg['priority'], 'INFO') + self.assertEquals(msg['event_type'], 'compute.instance.delete') + payload = msg['payload'] + self.assertEquals(payload['tenant_id'], self.project.id) + self.assertEquals(payload['user_id'], self.user.id) + self.assertEquals(payload['instance_id'], instance_id) + self.assertEquals(payload['instance_type'], 'm1.tiny') + type_id = instance_types.get_instance_type_by_name('m1.tiny')['id'] + self.assertEquals(str(payload['instance_type_id']), str(type_id)) + self.assertTrue('display_name' in payload) + self.assertTrue('created_at' in payload) + self.assertTrue('launched_at' in payload) + self.assertEquals(payload['image_id'], '1') + def test_run_instance_existing(self): """Ensure failure when running an instance that already exists""" instance_id = self._create_instance() @@ -334,6 +381,36 @@ class ComputeTestCase(test.TestCase): self.compute.terminate_instance(self.context, instance_id) + def test_resize_instance_notification(self): + """Ensure instance can be migrated/resized""" + instance_id = self._create_instance() + context = self.context.elevated() + + self.compute.run_instance(self.context, instance_id) + test_notifier.NOTIFICATIONS = [] + + db.instance_update(self.context, instance_id, {'host': 'foo'}) + self.compute.prep_resize(context, instance_id, 1) + migration_ref = db.migration_get_by_instance_and_status(context, + instance_id, 'pre-migrating') + + self.assertEquals(len(test_notifier.NOTIFICATIONS), 1) + msg = test_notifier.NOTIFICATIONS[0] + self.assertEquals(msg['priority'], 'INFO') + self.assertEquals(msg['event_type'], 'compute.instance.resize.prep') + payload = msg['payload'] + self.assertEquals(payload['tenant_id'], self.project.id) + self.assertEquals(payload['user_id'], self.user.id) + self.assertEquals(payload['instance_id'], instance_id) + self.assertEquals(payload['instance_type'], 'm1.tiny') + type_id = instance_types.get_instance_type_by_name('m1.tiny')['id'] + self.assertEquals(str(payload['instance_type_id']), str(type_id)) + self.assertTrue('display_name' in payload) + self.assertTrue('created_at' in payload) + self.assertTrue('launched_at' in payload) + self.assertEquals(payload['image_id'], '1') + self.compute.terminate_instance(context, instance_id) + def test_resize_instance(self): """Ensure instance can be migrated/resized""" instance_id = self._create_instance() From 4528041cef5914409f9832ba5732e3bfb491fb03 Mon Sep 17 00:00:00 2001 From: Monsyne Dragon Date: Tue, 28 Jun 2011 09:08:35 +0000 Subject: [PATCH 093/105] Fix pep8 nits in audit script --- bin/instance-usage-audit | 53 ++++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 27 deletions(-) diff --git a/bin/instance-usage-audit b/bin/instance-usage-audit index 1124cf55..cef9b464 100755 --- a/bin/instance-usage-audit +++ b/bin/instance-usage-audit @@ -17,22 +17,22 @@ # under the License. """Cron script to generate usage notifications for instances neither created - nor destroyed in a given time period. - + nor destroyed in a given time period. + Together with the notifications generated by compute on instance - create/delete/resize, over that ime period, this allows an external - system consuming usage notification feeds to calculate instance usage + create/delete/resize, over that ime period, this allows an external + system consuming usage notification feeds to calculate instance usage for each tenant. Time periods are specified like so: - [mdy] + [mdy] 1m = previous month. If the script is run April 1, it will generate usages for March 1 thry March 31. 3m = 3 previous months. - 90d = previous 90 days. - 1y = previous year. If run on Jan 1, it generates usages for - Jan 1 thru Dec 31 of the previous year. + 90d = previous 90 days. + 1y = previous year. If run on Jan 1, it generates usages for + Jan 1 thru Dec 31 of the previous year. """ import datetime @@ -65,6 +65,7 @@ FLAGS = flags.FLAGS flags.DEFINE_string('instance_usage_audit_period', '1m', 'time period to generate instance usages for.') + def time_period(period): today = datetime.date.today() unit = period[-1] @@ -72,27 +73,27 @@ def time_period(period): raise ValueError('Time period must be m, d, or y') n = int(period[:-1]) if unit == 'm': - year = today.year - (n//12) - n = n % 12 - if n >= today.month: - year -= 1 - month = 12 + (today.month - n) - else: - month = today.month - n - begin = datetime.datetime(day=1, month=month, year=year) - end = datetime.datetime(day=1, month=today.month, year=today.year) + year = today.year - (n // 12) + n = n % 12 + if n >= today.month: + year -= 1 + month = 12 + (today.month - n) + else: + month = today.month - n + begin = datetime.datetime(day=1, month=month, year=year) + end = datetime.datetime(day=1, month=today.month, year=today.year) elif unit == 'y': - begin = datetime.datetime(day=1, month=1, year=today.year - n) - end = datetime.datetime(day=1, month=1, year=today.year) - + begin = datetime.datetime(day=1, month=1, year=today.year - n) + end = datetime.datetime(day=1, month=1, year=today.year) + elif unit == 'd': - b = today - datetime.timedelta(days=n) - begin = datetime.datetime(day=b.day, month=b.month, year=b.year) - end = datetime.datetime(day=today.day, - month=today.month, + b = today - datetime.timedelta(days=n) + begin = datetime.datetime(day=b.day, month=b.month, year=b.year) + end = datetime.datetime(day=today.day, + month=today.month, year=today.year) - + return (begin, end) if __name__ == '__main__': @@ -123,5 +124,3 @@ if __name__ == '__main__': 'compute.instance.exists', notifier_api.INFO, usage_info) - - From a2f08bf148f00dab5939c7682df33eb654787ffb Mon Sep 17 00:00:00 2001 From: Yuriy Taraday Date: Tue, 28 Jun 2011 18:52:22 +0400 Subject: [PATCH 094/105] Prevent test case from ruining other tests. Make it work in earlier python versions. --- nova/tests/test_auth.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/nova/tests/test_auth.py b/nova/tests/test_auth.py index 4aebbe94..71e0d17c 100644 --- a/nova/tests/test_auth.py +++ b/nova/tests/test_auth.py @@ -373,9 +373,10 @@ class AuthManagerLdapTestCase(_AuthManagerBaseTestCase): def test_reconnect_on_server_failure(self): self.manager.get_users() fakeldap.server_fail = True - with self.assertRaises(fakeldap.SERVER_DOWN): - self.manager.get_users() - fakeldap.server_fail = False + try: + self.assertRaises(fakeldap.SERVER_DOWN, self.manager.get_users) + finally: + fakeldap.server_fail = False self.manager.get_users() From 6fae4b4e551d612408854e52338fb788d50f0a1b Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Tue, 28 Jun 2011 08:08:13 -0700 Subject: [PATCH 095/105] log formatting typo pep8 fixes --- nova/scheduler/zone_aware_scheduler.py | 3 ++- nova/tests/scheduler/test_zone_aware_scheduler.py | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index 638072ee..2efad7bf 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -181,7 +181,8 @@ class ZoneAwareScheduler(driver.Scheduler): return None num_instances = request_spec.get('num_instances', 1) - LOG.debug(_("Attemping to build %d instance(s)") % locals()) + LOG.debug(_("Attempting to build %(num_instances)d instance(s)") % + locals()) # Create build plan and provision ... build_plan = self.select(context, request_spec) diff --git a/nova/tests/scheduler/test_zone_aware_scheduler.py b/nova/tests/scheduler/test_zone_aware_scheduler.py index b2599f1b..1e23e3ee 100644 --- a/nova/tests/scheduler/test_zone_aware_scheduler.py +++ b/nova/tests/scheduler/test_zone_aware_scheduler.py @@ -63,13 +63,13 @@ class FakeZoneManager(zone_manager.ZoneManager): def __init__(self): self.service_states = { 'host1': { - 'compute': {'host_memory_free': 1000*1024*1024}, + 'compute': {'host_memory_free': 1073741824}, }, 'host2': { - 'compute': {'host_memory_free': 2000*1024*1024}, + 'compute': {'host_memory_free': 2147483648}, }, 'host3': { - 'compute': {'host_memory_free': 3000*1024*1024}, + 'compute': {'host_memory_free': 3221225472}, }, } @@ -158,7 +158,7 @@ class ZoneAwareSchedulerTestCase(test.TestCase): fake_context = {} build_plan = sched.select(fake_context, {'instance_type': {'memory_mb': 512}, - 'num_instances': 4 }) + 'num_instances': 4}) # 4 from local zones, 12 from remotes self.assertEqual(16, len(build_plan)) From 8ae8892fc9d07dba91d47915700b086b9a7b97ca Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Tue, 28 Jun 2011 08:12:08 -0700 Subject: [PATCH 096/105] update a test docstring to make it clear we're testing multiple instance builds --- nova/tests/scheduler/test_zone_aware_scheduler.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nova/tests/scheduler/test_zone_aware_scheduler.py b/nova/tests/scheduler/test_zone_aware_scheduler.py index 1e23e3ee..32f5150a 100644 --- a/nova/tests/scheduler/test_zone_aware_scheduler.py +++ b/nova/tests/scheduler/test_zone_aware_scheduler.py @@ -146,8 +146,8 @@ class ZoneAwareSchedulerTestCase(test.TestCase): def test_zone_aware_scheduler(self): """ - Create a nested set of FakeZones, ensure that a select call returns the - appropriate build plan. + Create a nested set of FakeZones, try to build multiple instances + and ensure that a select call returns the appropriate build plan. """ sched = FakeZoneAwareScheduler() self.stubs.Set(sched, '_call_zone_method', fake_call_zone_method) From 169f4d5d71da700f1f8e21db28996a8dadd40a66 Mon Sep 17 00:00:00 2001 From: Monsyne Dragon Date: Tue, 28 Jun 2011 15:21:08 +0000 Subject: [PATCH 097/105] Fix issues due to renming of imange_id attrib. --- bin/instance-usage-audit | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/instance-usage-audit b/bin/instance-usage-audit index cef9b464..1fa2c218 100755 --- a/bin/instance-usage-audit +++ b/bin/instance-usage-audit @@ -117,7 +117,7 @@ if __name__ == '__main__': created_at=str(instance_ref['created_at']), launched_at=str(instance_ref['launched_at']) \ if instance_ref['launched_at'] else '', - image_id=instance_ref['image_id'], + image_ref=instance_ref['image_ref'], audit_period_begining=str(begin), audit_period_ending=str(end)) notifier_api.notify('compute.%s' % FLAGS.host, From 393f03377a61167441462334ae603949aaabc2d5 Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Tue, 28 Jun 2011 08:53:13 -0700 Subject: [PATCH 098/105] change variable names to remove future conflict with sandy's zone-offsets branch --- nova/scheduler/zone_aware_scheduler.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index 2efad7bf..2e6662a7 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -192,9 +192,10 @@ class ZoneAwareScheduler(driver.Scheduler): for num in xrange(num_instances): if not build_plan: break - item = build_plan.pop(0) - self._provision_resource(context, item, instance_id, - request_spec, kwargs) + + build_plan_item = build_plan.pop(0) + self._provision_resource(context, build_plan_item, instance_id, + request_spec, kwargs) # Returning None short-circuits the routing to Compute (since # we've already done it here) From 324aa54c15d7b3624a2eb6b89f1165f44a8238c6 Mon Sep 17 00:00:00 2001 From: Monsyne Dragon Date: Tue, 28 Jun 2011 16:08:27 +0000 Subject: [PATCH 099/105] Fix merge issue in compute unittest. --- nova/tests/test_compute.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nova/tests/test_compute.py b/nova/tests/test_compute.py index e94a6267..4d42b1fd 100644 --- a/nova/tests/test_compute.py +++ b/nova/tests/test_compute.py @@ -348,7 +348,7 @@ class ComputeTestCase(test.TestCase): self.assertTrue('display_name' in payload) self.assertTrue('created_at' in payload) self.assertTrue('launched_at' in payload) - self.assertEquals(payload['image_id'], '1') + self.assertEquals(payload['image_ref'], '1') self.compute.terminate_instance(self.context, instance_id) def test_terminate_usage_notification(self): @@ -372,7 +372,7 @@ class ComputeTestCase(test.TestCase): self.assertTrue('display_name' in payload) self.assertTrue('created_at' in payload) self.assertTrue('launched_at' in payload) - self.assertEquals(payload['image_id'], '1') + self.assertEquals(payload['image_ref'], '1') def test_run_instance_existing(self): """Ensure failure when running an instance that already exists""" @@ -452,7 +452,7 @@ class ComputeTestCase(test.TestCase): self.assertTrue('display_name' in payload) self.assertTrue('created_at' in payload) self.assertTrue('launched_at' in payload) - self.assertEquals(payload['image_id'], '1') + self.assertEquals(payload['image_ref'], '1') self.compute.terminate_instance(context, instance_id) def test_resize_instance(self): From 7abc0fdbf781040af78fb40751b12617f88312be Mon Sep 17 00:00:00 2001 From: Monsyne Dragon Date: Tue, 28 Jun 2011 20:37:05 +0000 Subject: [PATCH 100/105] Refactored usage generation --- bin/instance-usage-audit | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/bin/instance-usage-audit b/bin/instance-usage-audit index 1fa2c218..a06c6b1b 100755 --- a/bin/instance-usage-audit +++ b/bin/instance-usage-audit @@ -107,19 +107,9 @@ if __name__ == '__main__': end) print "%s instances" % len(instances) for instance_ref in instances: - usage_info = dict( - tenant_id=instance_ref['project_id'], - user_id=instance_ref['user_id'], - instance_id=instance_ref['id'], - instance_type=instance_ref['instance_type']['name'], - instance_type_id=instance_ref['instance_type_id'], - display_name=instance_ref['display_name'], - created_at=str(instance_ref['created_at']), - launched_at=str(instance_ref['launched_at']) \ - if instance_ref['launched_at'] else '', - image_ref=instance_ref['image_ref'], - audit_period_begining=str(begin), - audit_period_ending=str(end)) + usage_info = utils.usage_from_instance(instance_ref, + audit_period_begining=str(begin), + audit_period_ending=str(end)) notifier_api.notify('compute.%s' % FLAGS.host, 'compute.instance.exists', notifier_api.INFO, From a4a376f2ca0df94108723ce79d65bebf52a82170 Mon Sep 17 00:00:00 2001 From: Josh Kearney Date: Tue, 28 Jun 2011 17:26:08 -0500 Subject: [PATCH 101/105] Use milestone cut. --- bin/nova-api | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/bin/nova-api b/bin/nova-api index ea99a1b4..fff67251 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -23,8 +23,14 @@ Starts both the EC2 and OpenStack APIs in separate processes. """ +import os import sys +possible_topdir = os.path.normpath(os.path.join(os.path.abspath( + sys.argv[0]), os.pardir, os.pardir)) +if os.path.exists(os.path.join(possible_topdir, "nova", "__init__.py")): + sys.path.insert(0, possible_topdir) + import nova.service import nova.utils From 37b14b979b1b76755314d83bfddd8b4e1e628663 Mon Sep 17 00:00:00 2001 From: Thierry Carrez Date: Wed, 29 Jun 2011 16:45:46 +0200 Subject: [PATCH 102/105] Fix nova-manage vm list --- bin/nova-manage | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/bin/nova-manage b/bin/nova-manage index 02f20347..d5390b63 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -617,7 +617,7 @@ class VmCommands(object): :param host: show all instance on specified host. :param instance: show specificed instance. """ - print "%-10s %-15s %-10s %-10s %-19s %-12s %-12s %-12s" \ + print "%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s" \ " %-10s %-10s %-10s %-5s" % ( _('instance'), _('node'), @@ -639,14 +639,14 @@ class VmCommands(object): context.get_admin_context(), host) for instance in instances: - print "%-10s %-15s %-10s %-10s %-19s %-12s %-12s %-12s" \ + print "%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s" \ " %-10s %-10s %-10s %-5d" % ( instance['hostname'], instance['host'], - instance['instance_type'], + instance['instance_type'].name, instance['state_description'], instance['launched_at'], - instance['image_id'], + instance['image_ref'], instance['kernel_id'], instance['ramdisk_id'], instance['project_id'], From 0277e60aaa470148dda969743788865efb730286 Mon Sep 17 00:00:00 2001 From: Thierry Carrez Date: Wed, 29 Jun 2011 16:52:55 +0200 Subject: [PATCH 103/105] Fix 'undefined name 'e'' pylint error --- bin/nova-manage | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/nova-manage b/bin/nova-manage index d5390b63..51e0c32c 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -878,7 +878,7 @@ class InstanceTypeCommands(object): try: instance_types.create(name, memory, vcpus, local_gb, flavorid, swap, rxtx_quota, rxtx_cap) - except exception.InvalidInput: + except exception.InvalidInput, e: print "Must supply valid parameters to create instance_type" print e sys.exit(1) From d308bab3d8ba170cb6a1f8eb62ace4daf73a915b Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Wed, 29 Jun 2011 09:49:19 -0700 Subject: [PATCH 104/105] Fanout queues use unique queue names, so the consumer should have exclusive access. This means that they also get auto deleted when we're done with them, so they're not left around on a service restart. Fixes lp:803165 --- nova/rpc.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/nova/rpc.py b/nova/rpc.py index 2e78a31e..9f0b507f 100644 --- a/nova/rpc.py +++ b/nova/rpc.py @@ -275,6 +275,11 @@ class FanoutAdapterConsumer(AdapterConsumer): unique = uuid.uuid4().hex self.queue = '%s_fanout_%s' % (topic, unique) self.durable = False + # Fanout creates unique queue names, so we should auto-remove + # them when done, so they're not left around on restart. + # Also, we're the only one that should be consuming. exclusive + # implies auto_delete, so we'll just set that.. + self.exclusive = True LOG.info(_('Created "%(exchange)s" fanout exchange ' 'with "%(key)s" routing key'), dict(exchange=self.exchange, key=self.routing_key)) From 23f51be9b69a36f080f5c5463e66c6dda3182296 Mon Sep 17 00:00:00 2001 From: Chris Behrens Date: Wed, 29 Jun 2011 12:23:26 -0700 Subject: [PATCH 105/105] Fixed indentation issues Fixed min/max_count checking issues Fixed a wrongly log message when zone aware scheduler finds no suitable hosts --- nova/scheduler/zone_aware_scheduler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/scheduler/zone_aware_scheduler.py b/nova/scheduler/zone_aware_scheduler.py index 2e6662a7..9e4fc47d 100644 --- a/nova/scheduler/zone_aware_scheduler.py +++ b/nova/scheduler/zone_aware_scheduler.py @@ -245,7 +245,7 @@ class ZoneAwareScheduler(driver.Scheduler): # may have been consumed from a previous build.. host_list = self.filter_hosts(topic, request_spec, host_list) if not host_list: - LOG.warn(_("Ran out of available hosts after weighing " + LOG.warn(_("Filter returned no hosts after processing " "%(i)d of %(num_instances)d instances") % locals()) break