diff options
52 files changed, 3901 insertions, 3693 deletions
diff --git a/bin/nova-compute b/bin/nova-compute index 631d2c85c..1724e9659 100755 --- a/bin/nova-compute +++ b/bin/nova-compute @@ -32,12 +32,12 @@ possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), if os.path.exists(os.path.join(possible_topdir, 'nova', '__init__.py')): sys.path.insert(0, possible_topdir) +from nova import service from nova import twistd -from nova.compute import service if __name__ == '__main__': twistd.serve(__file__) if __name__ == '__builtin__': - application = service.ComputeService.create() # pylint: disable-msg=C0103 + application = service.Service.create() # pylint: disable=C0103 diff --git a/bin/nova-dhcpbridge b/bin/nova-dhcpbridge index 0c3d987a7..a127ed03c 100755 --- a/bin/nova-dhcpbridge +++ b/bin/nova-dhcpbridge @@ -33,24 +33,32 @@ possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), if os.path.exists(os.path.join(possible_topdir, 'nova', '__init__.py')): sys.path.insert(0, possible_topdir) +from nova import db from nova import flags from nova import rpc from nova import utils from nova.network import linux_net -from nova.network import model -from nova.network import service FLAGS = flags.FLAGS +flags.DECLARE('auth_driver', 'nova.auth.manager') +flags.DECLARE('redis_db', 'nova.datastore') +flags.DECLARE('network_size', 'nova.network.manager') +flags.DECLARE('num_networks', 'nova.network.manager') +flags.DECLARE('update_dhcp_on_disassociate', 'nova.network.manager') -def add_lease(_mac, ip_address, _hostname, _interface): +def add_lease(mac, ip_address, _hostname, _interface): """Set the IP that was assigned by the DHCP server.""" if FLAGS.fake_rabbit: - service.VlanNetworkService().lease_ip(ip_address) + logging.debug("leasing ip") + network_manager = utils.import_object(FLAGS.network_manager) + network_manager.lease_fixed_ip(None, mac, ip_address) else: - rpc.cast("%s.%s" % (FLAGS.network_topic, FLAGS.node_name), - {"method": "lease_ip", - "args": {"fixed_ip": ip_address}}) + rpc.cast("%s.%s" % (FLAGS.network_topic, FLAGS.host), + {"method": "lease_fixed_ip", + "args": {"context": None, + "mac": mac, + "address": ip_address}}) def old_lease(_mac, _ip_address, _hostname, _interface): @@ -58,23 +66,24 @@ def old_lease(_mac, _ip_address, _hostname, _interface): logging.debug("Adopted old lease or got a change of mac/hostname") -def del_lease(_mac, ip_address, _hostname, _interface): +def del_lease(mac, ip_address, _hostname, _interface): """Called when a lease expires.""" if FLAGS.fake_rabbit: - service.VlanNetworkService().release_ip(ip_address) + logging.debug("releasing ip") + network_manager = utils.import_object(FLAGS.network_manager) + network_manager.release_fixed_ip(None, mac, ip_address) else: - rpc.cast("%s.%s" % (FLAGS.network_topic, FLAGS.node_name), - {"method": "release_ip", - "args": {"fixed_ip": ip_address}}) + rpc.cast("%s.%s" % (FLAGS.network_topic, FLAGS.host), + {"method": "release_fixed_ip", + "args": {"context": None, + "mac": mac, + "address": ip_address}}) def init_leases(interface): """Get the list of hosts for an interface.""" - net = model.get_network_by_interface(interface) - res = "" - for address in net.assigned_objs: - res += "%s\n" % linux_net.host_dhcp(address) - return res + network_ref = db.network_get_by_bridge(None, interface) + return linux_net.get_dhcp_hosts(None, network_ref['id']) def main(): @@ -86,10 +95,16 @@ def main(): if int(os.environ.get('TESTING', '0')): FLAGS.fake_rabbit = True FLAGS.redis_db = 8 - FLAGS.network_size = 32 + FLAGS.network_size = 16 FLAGS.connection_type = 'fake' FLAGS.fake_network = True FLAGS.auth_driver = 'nova.auth.ldapdriver.FakeLdapDriver' + FLAGS.num_networks = 5 + path = os.path.abspath(os.path.join(os.path.dirname(__file__), + '..', + '_trial_temp', + 'nova.sqlite')) + FLAGS.sql_connection = 'sqlite:///%s' % path action = argv[1] if action in ['add', 'del', 'old']: mac = argv[2] diff --git a/bin/nova-manage b/bin/nova-manage index 6e5266767..325245ac4 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -57,6 +57,8 @@ 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... possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), @@ -65,10 +67,10 @@ possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), if os.path.exists(os.path.join(possible_topdir, 'nova', '__init__.py')): sys.path.insert(0, possible_topdir) +from nova import db from nova import flags from nova import utils from nova.auth import manager -from nova.compute import model from nova.cloudpipe import pipelib from nova.endpoint import cloud @@ -81,7 +83,6 @@ class VpnCommands(object): def __init__(self): self.manager = manager.AuthManager() - self.instdir = model.InstanceDirectory() self.pipe = pipelib.CloudPipe(cloud.CloudController()) def list(self): @@ -96,8 +97,8 @@ class VpnCommands(object): vpn = self._vpn_for(project.id) if vpn: command = "ping -c1 -w1 %s > /dev/null; echo $?" - out, _err = utils.execute( command % vpn['private_dns_name'], - check_exit_code=False) + out, _err = utils.execute(command % vpn['private_dns_name'], + check_exit_code=False) if out.strip() == '0': net = 'up' else: @@ -113,9 +114,8 @@ class VpnCommands(object): def _vpn_for(self, project_id): """Get the VPN instance for a project ID.""" - for instance in self.instdir.all: - if ('image_id' in instance.state - and instance['image_id'] == FLAGS.vpn_image_id + for instance in db.instance_get_all(): + if (instance['image_id'] == FLAGS.vpn_image_id and not instance['state_description'] in ['shutting_down', 'shutdown'] and instance['project_id'] == project_id): @@ -274,6 +274,37 @@ class ProjectCommands(object): with open(filename, 'w') as f: f.write(zip_file) +class FloatingIpCommands(object): + """Class for managing floating ip.""" + + def create(self, host, range): + """Creates floating ips for host by range + arguments: host ip_range""" + for address in IPy.IP(range): + db.floating_ip_create(None, {'address': str(address), + 'host': host}) + + def delete(self, ip_range): + """Deletes floating ips by range + arguments: range""" + for address in IPy.IP(ip_range): + db.floating_ip_destroy(None, str(address)) + + + def list(self, host=None): + """Lists all floating ips (optionally by host) + arguments: [host]""" + if host == None: + floating_ips = db.floating_ip_get_all(None) + else: + floating_ips = db.floating_ip_get_all_by_host(None, host) + for floating_ip in floating_ips: + instance = None + if floating_ip['fixed_ip']: + instance = floating_ip['fixed_ip']['instance']['str_id'] + print "%s\t%s\t%s" % (floating_ip['host'], + floating_ip['address'], + instance) CATEGORIES = [ ('user', UserCommands), @@ -281,6 +312,7 @@ CATEGORIES = [ ('role', RoleCommands), ('shell', ShellCommands), ('vpn', VpnCommands), + ('floating', FloatingIpCommands) ] diff --git a/bin/nova-network b/bin/nova-network index 307795d7b..fa88aeb47 100755 --- a/bin/nova-network +++ b/bin/nova-network @@ -32,17 +32,12 @@ possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), if os.path.exists(os.path.join(possible_topdir, 'nova', '__init__.py')): sys.path.insert(0, possible_topdir) -from nova import flags +from nova import service from nova import twistd -from nova.network import service - -FLAGS = flags.FLAGS - if __name__ == '__main__': twistd.serve(__file__) if __name__ == '__builtin__': - # pylint: disable-msg=C0103 - application = service.type_to_class(FLAGS.network_type).create() + application = service.Service.create() # pylint: disable-msg=C0103 diff --git a/bin/nova-objectstore b/bin/nova-objectstore index 447ef9055..728f2ee5b 100755 --- a/bin/nova-objectstore +++ b/bin/nova-objectstore @@ -46,4 +46,4 @@ if __name__ == '__main__': if __name__ == '__builtin__': utils.default_flagfile() - application = handler.get_application() # pylint: disable-msg=C0103 + application = handler.get_application() # pylint: disable-msg=C0103 diff --git a/bin/nova-volume b/bin/nova-volume index f8e2e1744..b9e235717 100755 --- a/bin/nova-volume +++ b/bin/nova-volume @@ -32,12 +32,12 @@ possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), if os.path.exists(os.path.join(possible_topdir, 'nova', '__init__.py')): sys.path.insert(0, possible_topdir) +from nova import service from nova import twistd -from nova.volume import service if __name__ == '__main__': twistd.serve(__file__) if __name__ == '__builtin__': - application = service.VolumeService.create() # pylint: disable-msg=C0103 + application = service.Service.create() # pylint: disable-msg=C0103 diff --git a/nova/api/rackspace/servers.py b/nova/api/rackspace/servers.py index 25d1fe9c8..1815f7523 100644 --- a/nova/api/rackspace/servers.py +++ b/nova/api/rackspace/servers.py @@ -14,27 +14,31 @@ # 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 time +from nova import db +from nova import flags from nova import rpc -from nova.compute import model as compute +from nova import utils from nova.api.rackspace import base +FLAGS = flags.FLAGS class Controller(base.Controller): entity_name = 'servers' def index(self, **kwargs): instances = [] - for inst in compute.InstanceDirectory().all: + for inst in db.instance_get_all(None): instances.append(instance_details(inst)) def show(self, **kwargs): instance_id = kwargs['id'] - return compute.InstanceDirectory().get(instance_id) + return db.instance_get(None, instance_id) def delete(self, **kwargs): instance_id = kwargs['id'] - instance = compute.InstanceDirectory().get(instance_id) + instance = db.instance_get(None, instance_id) if not instance: raise ServerNotFound("The requested server was not found") instance.destroy() @@ -45,11 +49,11 @@ class Controller(base.Controller): rpc.cast( FLAGS.compute_topic, { "method": "run_instance", - "args": {"instance_id": inst.instance_id}}) + "args": {"instance_id": inst['id']}}) def update(self, **kwargs): instance_id = kwargs['id'] - instance = compute.InstanceDirectory().get(instance_id) + instance = db.instance_get(None, instance_id) if not instance: raise ServerNotFound("The requested server was not found") instance.update(kwargs['server']) @@ -59,7 +63,7 @@ class Controller(base.Controller): """Build instance data structure and save it to the data store.""" reservation = utils.generate_uid('r') ltime = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) - inst = self.instdir.new() + inst = {} inst['name'] = env['server']['name'] inst['image_id'] = env['server']['imageId'] inst['instance_type'] = env['server']['flavorId'] @@ -68,15 +72,8 @@ class Controller(base.Controller): inst['reservation_id'] = reservation inst['launch_time'] = ltime inst['mac_address'] = utils.generate_mac() - address = self.network.allocate_ip( - inst['user_id'], - inst['project_id'], - mac=inst['mac_address']) - inst['private_dns_name'] = str(address) - inst['bridge_name'] = network.BridgedNetwork.get_network_for_project( - inst['user_id'], - inst['project_id'], - 'default')['bridge_name'] + inst_id = db.instance_create(None, inst)['id'] + address = self.network_manager.allocate_fixed_ip(None, inst_id) # key_data, key_name, ami_launch_index # TODO(todd): key data or root password inst.save() diff --git a/nova/auth/manager.py b/nova/auth/manager.py index 284b29502..d5fbec7c5 100644 --- a/nova/auth/manager.py +++ b/nova/auth/manager.py @@ -29,11 +29,11 @@ import uuid import zipfile from nova import crypto +from nova import db from nova import exception from nova import flags from nova import utils from nova.auth import signer -from nova.network import vpn FLAGS = flags.FLAGS @@ -252,6 +252,7 @@ class AuthManager(object): __init__ is run every time AuthManager() is called, so we only reset the driver if it is not set or a new driver is specified. """ + self.network_manager = utils.import_object(FLAGS.network_manager) if driver or not getattr(self, 'driver', None): self.driver = utils.import_class(driver or FLAGS.auth_driver) @@ -493,8 +494,8 @@ class AuthManager(object): return [] return [Project(**project_dict) for project_dict in project_list] - def create_project(self, name, manager_user, - description=None, member_users=None): + def create_project(self, name, manager_user, description=None, + member_users=None, context=None): """Create a project @type name: str @@ -523,7 +524,14 @@ class AuthManager(object): description, member_users) if project_dict: - return Project(**project_dict) + project = Project(**project_dict) + try: + self.network_manager.allocate_network(context, + project.id) + except: + drv.delete_project(project.id) + raise + return project def add_to_project(self, user, project): """Add user to project""" @@ -550,7 +558,7 @@ class AuthManager(object): Project.safe_id(project)) @staticmethod - def get_project_vpn_data(project): + def get_project_vpn_data(project, context=None): """Gets vpn ip and port for project @type project: Project or project_id @@ -560,15 +568,26 @@ class AuthManager(object): @return: A tuple containing (ip, port) or None, None if vpn has not been allocated for user. """ - network_data = vpn.NetworkData.lookup(Project.safe_id(project)) - if not network_data: + + network_ref = db.project_get_network(context, + Project.safe_id(project)) + + if not network_ref['vpn_public_port']: raise exception.NotFound('project network data has not been set') - return (network_data.ip, network_data.port) + return (network_ref['vpn_public_address'], + network_ref['vpn_public_port']) - def delete_project(self, project): + def delete_project(self, project, context=None): """Deletes a project""" + try: + network_ref = db.project_get_network(context, + Project.safe_id(project)) + db.network_destroy(context, network_ref['id']) + except: + logging.exception('Could not destroy network for %s', + project) with self.driver() as drv: - return drv.delete_project(Project.safe_id(project)) + drv.delete_project(Project.safe_id(project)) def get_user(self, uid): """Retrieves a user by id""" @@ -703,15 +722,15 @@ class AuthManager(object): zippy.writestr(FLAGS.credential_key_file, private_key) zippy.writestr(FLAGS.credential_cert_file, signed_cert) - network_data = vpn.NetworkData.lookup(pid) - if network_data: + (vpn_ip, vpn_port) = self.get_project_vpn_data(project) + if vpn_ip: configfile = open(FLAGS.vpn_client_template, "r") s = string.Template(configfile.read()) configfile.close() config = s.substitute(keyfile=FLAGS.credential_key_file, certfile=FLAGS.credential_cert_file, - ip=network_data.ip, - port=network_data.port) + ip=vpn_ip, + port=vpn_port) zippy.writestr(FLAGS.credential_vpn_file, config) else: logging.warn("No vpn data for project %s" % diff --git a/nova/compute/manager.py b/nova/compute/manager.py new file mode 100644 index 000000000..ae7099812 --- /dev/null +++ b/nova/compute/manager.py @@ -0,0 +1,195 @@ +# 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. + +""" +Handles all code relating to instances (guest vms) +""" + +import base64 +import datetime +import logging +import os + +from twisted.internet import defer + +from nova import exception +from nova import flags +from nova import manager +from nova import utils +from nova.compute import power_state + + +FLAGS = flags.FLAGS +flags.DEFINE_string('instances_path', utils.abspath('../instances'), + 'where instances are stored on disk') +flags.DEFINE_string('compute_driver', 'nova.virt.connection.get_connection', + 'Driver to use for volume creation') + + +class ComputeManager(manager.Manager): + """ + Manages the running instances. + """ + def __init__(self, compute_driver=None, *args, **kwargs): + """Load configuration options and connect to the hypervisor.""" + # TODO(vish): sync driver creation logic with the rest of the system + if not compute_driver: + compute_driver = FLAGS.compute_driver + self.driver = utils.import_object(compute_driver) + self.network_manager = utils.import_object(FLAGS.network_manager) + self.volume_manager = utils.import_object(FLAGS.volume_manager) + super(ComputeManager, self).__init__(*args, **kwargs) + + def _update_state(self, context, instance_id): + """Update the state of an instance from the driver info""" + # FIXME(ja): include other fields from state? + instance_ref = self.db.instance_get(context, instance_id) + state = self.driver.get_info(instance_ref.name)['state'] + self.db.instance_set_state(context, instance_id, state) + + @defer.inlineCallbacks + @exception.wrap_exception + def run_instance(self, context, instance_id, **_kwargs): + """Launch a new instance with specified options.""" + instance_ref = self.db.instance_get(context, instance_id) + if instance_ref['str_id'] in self.driver.list_instances(): + raise exception.Error("Instance has already been created") + logging.debug("instance %s: starting...", instance_id) + project_id = instance_ref['project_id'] + self.network_manager.setup_compute_network(context, project_id) + self.db.instance_update(context, + instance_id, + {'host': self.host}) + + # TODO(vish) check to make sure the availability zone matches + self.db.instance_set_state(context, + instance_id, + power_state.NOSTATE, + 'spawning') + + try: + yield self.driver.spawn(instance_ref) + now = datetime.datetime.utcnow() + self.db.instance_update(None, instance_id, {'launched_at': now}) + except Exception: # pylint: disable-msg=W0702 + logging.exception("instance %s: Failed to spawn", + instance_ref['name']) + self.db.instance_set_state(context, + instance_id, + power_state.SHUTDOWN) + + self._update_state(context, instance_id) + + @defer.inlineCallbacks + @exception.wrap_exception + def terminate_instance(self, context, instance_id): + """Terminate an instance on this machine.""" + logging.debug("instance %s: terminating", instance_id) + instance_ref = self.db.instance_get(context, instance_id) + + if instance_ref['state'] == power_state.SHUTOFF: + self.db.instance_destroy(context, instance_id) + raise exception.Error('trying to destroy already destroyed' + ' instance: %s' % instance_id) + + self.db.instance_set_state(context, + instance_id, + power_state.NOSTATE, + 'shutting_down') + yield self.driver.destroy(instance_ref) + now = datetime.datetime.utcnow() + self.db.instance_update(None, instance_id, {'terminated_at': now}) + + # TODO(ja): should we keep it in a terminated state for a bit? + self.db.instance_destroy(context, instance_id) + + @defer.inlineCallbacks + @exception.wrap_exception + def reboot_instance(self, context, instance_id): + """Reboot an instance on this server.""" + self._update_state(context, instance_id) + instance_ref = self.db.instance_get(context, instance_id) + + if instance_ref['state'] != power_state.RUNNING: + raise exception.Error( + 'trying to reboot a non-running' + 'instance: %s (state: %s excepted: %s)' % + (instance_ref['str_id'], + instance_ref['state'], + power_state.RUNNING)) + + logging.debug('instance %s: rebooting', instance_ref['name']) + self.db.instance_set_state(context, + instance_id, + power_state.NOSTATE, + 'rebooting') + yield self.driver.reboot(instance_ref) + self._update_state(context, instance_id) + + @exception.wrap_exception + def get_console_output(self, context, instance_id): + """Send the console output for an instance.""" + # TODO(vish): Move this into the driver layer + + logging.debug("instance %s: getting console output", instance_id) + instance_ref = self.db.instance_get(context, instance_id) + + if FLAGS.connection_type == 'libvirt': + fname = os.path.abspath(os.path.join(FLAGS.instances_path, + instance_ref['str_id'], + 'console.log')) + with open(fname, 'r') as f: + output = f.read() + else: + output = 'FAKE CONSOLE OUTPUT' + + # TODO(termie): this stuff belongs in the API layer, no need to + # munge the data we send to ourselves + output = {"InstanceId": instance_id, + "Timestamp": "2", + "output": base64.b64encode(output)} + return output + + @defer.inlineCallbacks + @exception.wrap_exception + def attach_volume(self, context, instance_id, volume_id, mountpoint): + """Attach a volume to an instance.""" + logging.debug("instance %s: attaching volume %s to %s", instance_id, + volume_id, mountpoint) + instance_ref = self.db.instance_get(context, instance_id) + dev_path = yield self.volume_manager.setup_compute_volume(context, + volume_id) + yield self.driver.attach_volume(instance_ref['str_id'], + dev_path, + mountpoint) + self.db.volume_attached(context, volume_id, instance_id, mountpoint) + defer.returnValue(True) + + @defer.inlineCallbacks + @exception.wrap_exception + def detach_volume(self, context, instance_id, volume_id): + """Detach a volume from an instance.""" + logging.debug("instance %s: detaching volume %s", + instance_id, + volume_id) + instance_ref = self.db.instance_get(context, instance_id) + volume_ref = self.db.volume_get(context, volume_id) + self.driver.detach_volume(instance_ref['str_id'], + volume_ref['mountpoint']) + self.db.volume_detached(context, volume_id) + defer.returnValue(True) diff --git a/nova/compute/model.py b/nova/compute/model.py deleted file mode 100644 index 84432b55f..000000000 --- a/nova/compute/model.py +++ /dev/null @@ -1,314 +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. - -""" -Datastore Model objects for Compute Instances, with -InstanceDirectory manager. - -# Create a new instance? ->>> InstDir = InstanceDirectory() ->>> inst = InstDir.new() ->>> inst.destroy() -True ->>> inst = InstDir['i-123'] ->>> inst['ip'] = "192.168.0.3" ->>> inst['project_id'] = "projectA" ->>> inst.save() -True - ->>> InstDir['i-123'] -<Instance:i-123> ->>> InstDir.all.next() -<Instance:i-123> - ->>> inst.destroy() -True -""" - -import datetime -import uuid - -from nova import datastore -from nova import exception -from nova import flags -from nova import utils - - -FLAGS = flags.FLAGS - - -# TODO(todd): Implement this at the class level for Instance -class InstanceDirectory(object): - """an api for interacting with the global state of instances""" - - def get(self, instance_id): - """returns an instance object for a given id""" - return Instance(instance_id) - - def __getitem__(self, item): - return self.get(item) - - @datastore.absorb_connection_error - def by_project(self, project): - """returns a list of instance objects for a project""" - for instance_id in datastore.Redis.instance().smembers('project:%s:instances' % project): - yield Instance(instance_id) - - @datastore.absorb_connection_error - def by_node(self, node): - """returns a list of instances for a node""" - for instance_id in datastore.Redis.instance().smembers('node:%s:instances' % node): - yield Instance(instance_id) - - def by_ip(self, ip): - """returns an instance object that is using the IP""" - # NOTE(vish): The ip association should be just a single value, but - # to maintain consistency it is using the standard - # association and the ugly method for retrieving - # the first item in the set below. - result = datastore.Redis.instance().smembers('ip:%s:instances' % ip) - if not result: - return None - return Instance(list(result)[0]) - - def by_volume(self, volume_id): - """returns the instance a volume is attached to""" - pass - - @datastore.absorb_connection_error - def exists(self, instance_id): - return datastore.Redis.instance().sismember('instances', instance_id) - - @property - @datastore.absorb_connection_error - def all(self): - """returns a list of all instances""" - for instance_id in datastore.Redis.instance().smembers('instances'): - yield Instance(instance_id) - - def new(self): - """returns an empty Instance object, with ID""" - instance_id = utils.generate_uid('i') - return self.get(instance_id) - - -class Instance(datastore.BasicModel): - """Wrapper around stored properties of an instance""" - - def __init__(self, instance_id): - """loads an instance from the datastore if exists""" - # set instance data before super call since it uses default_state - self.instance_id = instance_id - super(Instance, self).__init__() - - def default_state(self): - return {'state': 0, - 'state_description': 'pending', - 'instance_id': self.instance_id, - 'node_name': 'unassigned', - 'project_id': 'unassigned', - 'user_id': 'unassigned', - 'private_dns_name': 'unassigned'} - - @property - def identifier(self): - return self.instance_id - - @property - def project(self): - if self.state.get('project_id', None): - return self.state['project_id'] - return self.state.get('owner_id', 'unassigned') - - @property - def volumes(self): - """returns a list of attached volumes""" - pass - - @property - def reservation(self): - """Returns a reservation object""" - pass - - def save(self): - """Call into superclass to save object, then save associations""" - # NOTE(todd): doesn't track migration between projects/nodes, - # it just adds the first one - is_new = self.is_new_record() - node_set = (self.state['node_name'] != 'unassigned' and - self.initial_state.get('node_name', 'unassigned') - == 'unassigned') - success = super(Instance, self).save() - if success and is_new: - self.associate_with("project", self.project) - self.associate_with("ip", self.state['private_dns_name']) - if success and node_set: - self.associate_with("node", self.state['node_name']) - return True - - def destroy(self): - """Destroy associations, then destroy the object""" - self.unassociate_with("project", self.project) - self.unassociate_with("node", self.state['node_name']) - self.unassociate_with("ip", self.state['private_dns_name']) - return super(Instance, self).destroy() - - -class Host(datastore.BasicModel): - """A Host is the machine where a Daemon is running.""" - - def __init__(self, hostname): - """loads an instance from the datastore if exists""" - # set instance data before super call since it uses default_state - self.hostname = hostname - super(Host, self).__init__() - - def default_state(self): - return {"hostname": self.hostname} - - @property - def identifier(self): - return self.hostname - - -class Daemon(datastore.BasicModel): - """A Daemon is a job (compute, api, network, ...) that runs on a host.""" - - def __init__(self, host_or_combined, binpath=None): - """loads an instance from the datastore if exists""" - # set instance data before super call since it uses default_state - # since loading from datastore expects a combined key that - # is equivilent to identifier, we need to expect that, while - # maintaining meaningful semantics (2 arguments) when creating - # from within other code like the bin/nova-* scripts - if binpath: - self.hostname = host_or_combined - self.binary = binpath - else: - self.hostname, self.binary = host_or_combined.split(":") - super(Daemon, self).__init__() - - def default_state(self): - return {"hostname": self.hostname, - "binary": self.binary, - "updated_at": utils.isotime() - } - - @property - def identifier(self): - return "%s:%s" % (self.hostname, self.binary) - - def save(self): - """Call into superclass to save object, then save associations""" - # NOTE(todd): this makes no attempt to destroy itsself, - # so after termination a record w/ old timestmap remains - success = super(Daemon, self).save() - if success: - self.associate_with("host", self.hostname) - return True - - def destroy(self): - """Destroy associations, then destroy the object""" - self.unassociate_with("host", self.hostname) - return super(Daemon, self).destroy() - - def heartbeat(self): - self['updated_at'] = utils.isotime() - return self.save() - - @classmethod - def by_host(cls, hostname): - for x in cls.associated_to("host", hostname): - yield x - - -class SessionToken(datastore.BasicModel): - """This is a short-lived auth token that is passed through web requests""" - - def __init__(self, session_token): - self.token = session_token - self.default_ttl = FLAGS.auth_token_ttl - super(SessionToken, self).__init__() - - @property - def identifier(self): - return self.token - - def default_state(self): - now = datetime.datetime.utcnow() - diff = datetime.timedelta(seconds=self.default_ttl) - expires = now + diff - return {'user': None, 'session_type': None, 'token': self.token, - 'expiry': expires.strftime(utils.TIME_FORMAT)} - - def save(self): - """Call into superclass to save object, then save associations""" - if not self['user']: - raise exception.Invalid("SessionToken requires a User association") - success = super(SessionToken, self).save() - if success: - self.associate_with("user", self['user']) - return True - - @classmethod - def lookup(cls, key): - token = super(SessionToken, cls).lookup(key) - if token: - expires_at = utils.parse_isotime(token['expiry']) - if datetime.datetime.utcnow() >= expires_at: - token.destroy() - return None - return token - - @classmethod - def generate(cls, userid, session_type=None): - """make a new token for the given user""" - token = str(uuid.uuid4()) - while cls.lookup(token): - token = str(uuid.uuid4()) - instance = cls(token) - instance['user'] = userid - instance['session_type'] = session_type - instance.save() - return instance - - def update_expiry(self, **kwargs): - """updates the expirty attribute, but doesn't save""" - if not kwargs: - kwargs['seconds'] = self.default_ttl - time = datetime.datetime.utcnow() - diff = datetime.timedelta(**kwargs) - expires = time + diff - self['expiry'] = expires.strftime(utils.TIME_FORMAT) - - def is_expired(self): - now = datetime.datetime.utcnow() - expires = utils.parse_isotime(self['expiry']) - return expires <= now - - def ttl(self): - """number of seconds remaining before expiration""" - now = datetime.datetime.utcnow() - expires = utils.parse_isotime(self['expiry']) - delta = expires - now - return (delta.seconds + (delta.days * 24 * 3600)) - - -if __name__ == "__main__": - import doctest - doctest.testmod() diff --git a/nova/compute/service.py b/nova/compute/service.py deleted file mode 100644 index 3321c2c00..000000000 --- a/nova/compute/service.py +++ /dev/null @@ -1,359 +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. - -""" -Compute Service: - - Runs on each compute host, managing the - hypervisor using the virt module. - -""" - -import base64 -import json -import logging -import os -import sys - -from twisted.internet import defer -from twisted.internet import task - -from nova import exception -from nova import flags -from nova import process -from nova import service -from nova import utils -from nova.compute import disk -from nova.compute import model -from nova.compute import power_state -from nova.compute.instance_types import INSTANCE_TYPES -from nova.network import service as network_service -from nova.objectstore import image # for image_path flag -from nova.virt import connection as virt_connection -from nova.volume import service as volume_service - - -FLAGS = flags.FLAGS -flags.DEFINE_string('instances_path', utils.abspath('../instances'), - 'where instances are stored on disk') - - -class ComputeService(service.Service): - """ - Manages the running instances. - """ - def __init__(self): - """ load configuration options for this node and connect to the hypervisor""" - super(ComputeService, self).__init__() - self._instances = {} - self._conn = virt_connection.get_connection() - self.instdir = model.InstanceDirectory() - # TODO(joshua): This needs to ensure system state, specifically: modprobe aoe - - def noop(self): - """ simple test of an AMQP message call """ - return defer.succeed('PONG') - - def get_instance(self, instance_id): - # inst = self.instdir.get(instance_id) - # return inst - if self.instdir.exists(instance_id): - return Instance.fromName(self._conn, instance_id) - return None - - @exception.wrap_exception - def adopt_instances(self): - """ if there are instances already running, adopt them """ - return defer.succeed(0) - instance_names = self._conn.list_instances() - for name in instance_names: - try: - new_inst = Instance.fromName(self._conn, name) - new_inst.update_state() - except: - pass - return defer.succeed(len(self._instances)) - - @exception.wrap_exception - def describe_instances(self): - retval = {} - for inst in self.instdir.by_node(FLAGS.node_name): - retval[inst['instance_id']] = ( - Instance.fromName(self._conn, inst['instance_id'])) - return retval - - @defer.inlineCallbacks - def report_state(self, nodename, daemon): - # TODO(termie): make this pattern be more elegant. -todd - try: - record = model.Daemon(nodename, daemon) - record.heartbeat() - if getattr(self, "model_disconnected", False): - self.model_disconnected = False - logging.error("Recovered model server connection!") - - except model.ConnectionError, ex: - if not getattr(self, "model_disconnected", False): - self.model_disconnected = True - logging.exception("model server went away") - yield - - @exception.wrap_exception - def run_instance(self, instance_id, **_kwargs): - """ launch a new instance with specified options """ - logging.debug("Starting instance %s..." % (instance_id)) - inst = self.instdir.get(instance_id) - # TODO: Get the real security group of launch in here - security_group = "default" - # NOTE(vish): passing network type allows us to express the - # network without making a call to network to find - # out which type of network to setup - network_service.setup_compute_network( - inst.get('network_type', 'vlan'), - inst['user_id'], - inst['project_id'], - security_group) - - inst['node_name'] = FLAGS.node_name - inst.save() - # TODO(vish) check to make sure the availability zone matches - new_inst = Instance(self._conn, name=instance_id, data=inst) - logging.info("Instances current state is %s", new_inst.state) - if new_inst.is_running(): - raise exception.Error("Instance is already running") - new_inst.spawn() - - @exception.wrap_exception - def terminate_instance(self, instance_id): - """ terminate an instance on this machine """ - logging.debug("Got told to terminate instance %s" % instance_id) - instance = self.get_instance(instance_id) - # inst = self.instdir.get(instance_id) - if not instance: - raise exception.Error( - 'trying to terminate unknown instance: %s' % instance_id) - d = instance.destroy() - # d.addCallback(lambda x: inst.destroy()) - return d - - @exception.wrap_exception - def reboot_instance(self, instance_id): - """ reboot an instance on this server - KVM doesn't support reboot, so we terminate and restart """ - instance = self.get_instance(instance_id) - if not instance: - raise exception.Error( - 'trying to reboot unknown instance: %s' % instance_id) - return instance.reboot() - - @defer.inlineCallbacks - @exception.wrap_exception - def get_console_output(self, instance_id): - """ send the console output for an instance """ - logging.debug("Getting console output for %s" % (instance_id)) - inst = self.instdir.get(instance_id) - instance = self.get_instance(instance_id) - if not instance: - raise exception.Error( - 'trying to get console log for unknown: %s' % instance_id) - rv = yield instance.console_output() - # TODO(termie): this stuff belongs in the API layer, no need to - # munge the data we send to ourselves - output = {"InstanceId" : instance_id, - "Timestamp" : "2", - "output" : base64.b64encode(rv)} - defer.returnValue(output) - - @defer.inlineCallbacks - @exception.wrap_exception - def attach_volume(self, instance_id = None, - volume_id = None, mountpoint = None): - volume = volume_service.get_volume(volume_id) - yield self._init_aoe() - yield process.simple_execute( - "sudo virsh attach-disk %s /dev/etherd/%s %s" % - (instance_id, - volume['aoe_device'], - mountpoint.rpartition('/dev/')[2])) - volume.finish_attach() - defer.returnValue(True) - - @defer.inlineCallbacks - def _init_aoe(self): - yield process.simple_execute("sudo aoe-discover") - yield process.simple_execute("sudo aoe-stat") - - @defer.inlineCallbacks - @exception.wrap_exception - def detach_volume(self, instance_id, volume_id): - """ detach a volume from an instance """ - # despite the documentation, virsh detach-disk just wants the device - # name without the leading /dev/ - volume = volume_service.get_volume(volume_id) - target = volume['mountpoint'].rpartition('/dev/')[2] - yield process.simple_execute( - "sudo virsh detach-disk %s %s " % (instance_id, target)) - volume.finish_detach() - defer.returnValue(True) - - -class Group(object): - def __init__(self, group_id): - self.group_id = group_id - - -class ProductCode(object): - def __init__(self, product_code): - self.product_code = product_code - - -class Instance(object): - - def __init__(self, conn, name, data): - """ spawn an instance with a given name """ - self._conn = conn - # TODO(vish): this can be removed after data has been updated - # data doesn't seem to have a working iterator so in doesn't work - if data.get('owner_id', None) is not None: - data['user_id'] = data['owner_id'] - data['project_id'] = data['owner_id'] - self.datamodel = data - - size = data.get('instance_type', FLAGS.default_instance_type) - if size not in INSTANCE_TYPES: - raise exception.Error('invalid instance type: %s' % size) - - self.datamodel.update(INSTANCE_TYPES[size]) - - self.datamodel['name'] = name - self.datamodel['instance_id'] = name - self.datamodel['basepath'] = data.get( - 'basepath', os.path.abspath( - os.path.join(FLAGS.instances_path, self.name))) - self.datamodel['memory_kb'] = int(self.datamodel['memory_mb']) * 1024 - self.datamodel.setdefault('image_id', FLAGS.default_image) - self.datamodel.setdefault('kernel_id', FLAGS.default_kernel) - self.datamodel.setdefault('ramdisk_id', FLAGS.default_ramdisk) - self.datamodel.setdefault('project_id', self.datamodel['user_id']) - self.datamodel.setdefault('bridge_name', None) - #self.datamodel.setdefault('key_data', None) - #self.datamodel.setdefault('key_name', None) - #self.datamodel.setdefault('addressing_type', None) - - # TODO(joshua) - The ugly non-flat ones - self.datamodel['groups'] = data.get('security_group', 'default') - # TODO(joshua): Support product codes somehow - self.datamodel.setdefault('product_codes', None) - - self.datamodel.save() - logging.debug("Finished init of Instance with id of %s" % name) - - @classmethod - def fromName(cls, conn, name): - """ use the saved data for reloading the instance """ - instdir = model.InstanceDirectory() - instance = instdir.get(name) - return cls(conn=conn, name=name, data=instance) - - def set_state(self, state_code, state_description=None): - self.datamodel['state'] = state_code - if not state_description: - state_description = power_state.name(state_code) - self.datamodel['state_description'] = state_description - self.datamodel.save() - - @property - def state(self): - # it is a string in datamodel - return int(self.datamodel['state']) - - @property - def name(self): - return self.datamodel['name'] - - def is_pending(self): - return (self.state == power_state.NOSTATE or self.state == 'pending') - - def is_destroyed(self): - return self.state == power_state.SHUTOFF - - def is_running(self): - logging.debug("Instance state is: %s" % self.state) - return (self.state == power_state.RUNNING or self.state == 'running') - - def describe(self): - return self.datamodel - - def info(self): - result = self._conn.get_info(self.name) - result['node_name'] = FLAGS.node_name - return result - - def update_state(self): - self.datamodel.update(self.info()) - self.set_state(self.state) - self.datamodel.save() # Extra, but harmless - - @defer.inlineCallbacks - @exception.wrap_exception - def destroy(self): - if self.is_destroyed(): - self.datamodel.destroy() - raise exception.Error('trying to destroy already destroyed' - ' instance: %s' % self.name) - - self.set_state(power_state.NOSTATE, 'shutting_down') - yield self._conn.destroy(self) - self.datamodel.destroy() - - @defer.inlineCallbacks - @exception.wrap_exception - def reboot(self): - if not self.is_running(): - raise exception.Error( - 'trying to reboot a non-running' - 'instance: %s (state: %s)' % (self.name, self.state)) - - logging.debug('rebooting instance %s' % self.name) - self.set_state(power_state.NOSTATE, 'rebooting') - yield self._conn.reboot(self) - self.update_state() - - @defer.inlineCallbacks - @exception.wrap_exception - def spawn(self): - self.set_state(power_state.NOSTATE, 'spawning') - logging.debug("Starting spawn in Instance") - try: - yield self._conn.spawn(self) - except Exception, ex: - logging.debug(ex) - self.set_state(power_state.SHUTDOWN) - self.update_state() - - @exception.wrap_exception - def console_output(self): - # FIXME: Abstract this for Xen - if FLAGS.connection_type == 'libvirt': - fname = os.path.abspath( - os.path.join(self.datamodel['basepath'], 'console.log')) - with open(fname, 'r') as f: - console = f.read() - else: - console = 'FAKE CONSOLE OUTPUT' - return defer.succeed(console) diff --git a/nova/datastore.py b/nova/datastore.py index 5dc6ed107..8e2519429 100644 --- a/nova/datastore.py +++ b/nova/datastore.py @@ -26,10 +26,7 @@ before trying to run this. import logging import redis -from nova import exception from nova import flags -from nova import utils - FLAGS = flags.FLAGS flags.DEFINE_string('redis_host', '127.0.0.1', @@ -54,209 +51,3 @@ class Redis(object): return cls._instance -class ConnectionError(exception.Error): - pass - - -def absorb_connection_error(fn): - def _wrapper(*args, **kwargs): - try: - return fn(*args, **kwargs) - except redis.exceptions.ConnectionError, ce: - raise ConnectionError(str(ce)) - return _wrapper - - -class BasicModel(object): - """ - All Redis-backed data derives from this class. - - You MUST specify an identifier() property that returns a unique string - per instance. - - You MUST have an initializer that takes a single argument that is a value - returned by identifier() to load a new class with. - - You may want to specify a dictionary for default_state(). - - You may also specify override_type at the class left to use a key other - than __class__.__name__. - - You override save and destroy calls to automatically build and destroy - associations. - """ - - override_type = None - - @absorb_connection_error - def __init__(self): - state = Redis.instance().hgetall(self.__redis_key) - if state: - self.initial_state = state - self.state = dict(self.initial_state) - else: - self.initial_state = {} - self.state = self.default_state() - - - def default_state(self): - """You probably want to define this in your subclass""" - return {} - - @classmethod - def _redis_name(cls): - return cls.override_type or cls.__name__.lower() - - @classmethod - def lookup(cls, identifier): - rv = cls(identifier) - if rv.is_new_record(): - return None - else: - return rv - - @classmethod - @absorb_connection_error - def all(cls): - """yields all objects in the store""" - redis_set = cls._redis_set_name(cls.__name__) - for identifier in Redis.instance().smembers(redis_set): - yield cls(identifier) - - @classmethod - def associated_to(cls, foreign_type, foreign_id): - for identifier in cls.associated_keys(foreign_type, foreign_id): - yield cls(identifier) - - @classmethod - @absorb_connection_error - def associated_keys(cls, foreign_type, foreign_id): - redis_set = cls._redis_association_name(foreign_type, foreign_id) - return Redis.instance().smembers(redis_set) or [] - - @classmethod - def _redis_set_name(cls, kls_name): - # stupidly pluralize (for compatiblity with previous codebase) - return kls_name.lower() + "s" - - @classmethod - def _redis_association_name(cls, foreign_type, foreign_id): - return cls._redis_set_name("%s:%s:%s" % - (foreign_type, foreign_id, cls._redis_name())) - - @property - def identifier(self): - """You DEFINITELY want to define this in your subclass""" - raise NotImplementedError("Your subclass should define identifier") - - @property - def __redis_key(self): - return '%s:%s' % (self._redis_name(), self.identifier) - - def __repr__(self): - return "<%s:%s>" % (self.__class__.__name__, self.identifier) - - def keys(self): - return self.state.keys() - - def copy(self): - copyDict = {} - for item in self.keys(): - copyDict[item] = self[item] - return copyDict - - def get(self, item, default): - return self.state.get(item, default) - - def update(self, update_dict): - return self.state.update(update_dict) - - def setdefault(self, item, default): - return self.state.setdefault(item, default) - - def __contains__(self, item): - return item in self.state - - def __getitem__(self, item): - return self.state[item] - - def __setitem__(self, item, val): - self.state[item] = val - return self.state[item] - - def __delitem__(self, item): - """We don't support this""" - raise Exception("Silly monkey, models NEED all their properties.") - - def is_new_record(self): - return self.initial_state == {} - - @absorb_connection_error - def add_to_index(self): - """Each insance of Foo has its id tracked int the set named Foos""" - set_name = self.__class__._redis_set_name(self.__class__.__name__) - Redis.instance().sadd(set_name, self.identifier) - - @absorb_connection_error - def remove_from_index(self): - """Remove id of this instance from the set tracking ids of this type""" - set_name = self.__class__._redis_set_name(self.__class__.__name__) - Redis.instance().srem(set_name, self.identifier) - - @absorb_connection_error - def associate_with(self, foreign_type, foreign_id): - """Add this class id into the set foreign_type:foreign_id:this_types""" - # note the extra 's' on the end is for plurality - # to match the old data without requiring a migration of any sort - self.add_associated_model_to_its_set(foreign_type, foreign_id) - redis_set = self.__class__._redis_association_name(foreign_type, - foreign_id) - Redis.instance().sadd(redis_set, self.identifier) - - @absorb_connection_error - def unassociate_with(self, foreign_type, foreign_id): - """Delete from foreign_type:foreign_id:this_types set""" - redis_set = self.__class__._redis_association_name(foreign_type, - foreign_id) - Redis.instance().srem(redis_set, self.identifier) - - def add_associated_model_to_its_set(self, model_type, model_id): - """ - When associating an X to a Y, save Y for newer timestamp, etc, and to - make sure to save it if Y is a new record. - If the model_type isn't found as a usable class, ignore it, this can - happen when associating to things stored in LDAP (user, project, ...). - """ - table = globals() - klsname = model_type.capitalize() - if table.has_key(klsname): - model_class = table[klsname] - model_inst = model_class(model_id) - model_inst.save() - - @absorb_connection_error - def save(self): - """ - update the directory with the state from this model - also add it to the index of items of the same type - then set the initial_state = state so new changes are tracked - """ - # TODO(ja): implement hmset in redis-py and use it - # instead of multiple calls to hset - if self.is_new_record(): - self["create_time"] = utils.isotime() - for key, val in self.state.iteritems(): - Redis.instance().hset(self.__redis_key, key, val) - self.add_to_index() - self.initial_state = dict(self.state) - return True - - @absorb_connection_error - def destroy(self): - """deletes all related records from datastore.""" - logging.info("Destroying datamodel for %s %s", - self.__class__.__name__, self.identifier) - Redis.instance().delete(self.__redis_key) - self.remove_from_index() - return True - diff --git a/nova/db/__init__.py b/nova/db/__init__.py new file mode 100644 index 000000000..054b7ac94 --- /dev/null +++ b/nova/db/__init__.py @@ -0,0 +1,23 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 +# 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. +""" +DB abstraction for Nova +""" + +from nova.db.api import * diff --git a/nova/db/api.py b/nova/db/api.py new file mode 100644 index 000000000..d749ae50a --- /dev/null +++ b/nova/db/api.py @@ -0,0 +1,441 @@ +# 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. +""" +Defines interface for DB access +""" + +from nova import exception +from nova import flags +from nova import utils + + +FLAGS = flags.FLAGS +flags.DEFINE_string('db_backend', 'sqlalchemy', + 'The backend to use for db') + + +IMPL = utils.LazyPluggable(FLAGS['db_backend'], + sqlalchemy='nova.db.sqlalchemy.api') + + +class NoMoreAddresses(exception.Error): + """No more available addresses""" + pass + + +class NoMoreBlades(exception.Error): + """No more available blades""" + pass + + +class NoMoreNetworks(exception.Error): + """No more available networks""" + pass + + +################### + + +def service_get(context, service_id): + """Get an service or raise if it does not exist.""" + return IMPL.service_get(context, service_id) + + +def service_get_by_args(context, host, binary): + """Get the state of an service by node name and binary.""" + return IMPL.service_get_by_args(context, host, binary) + + +def service_create(context, values): + """Create a service from the values dictionary.""" + return IMPL.service_create(context, values) + + +def service_update(context, service_id, values): + """Set the given properties on an service and update it. + + Raises NotFound if service does not exist. + + """ + return IMPL.service_update(context, service_id, values) + + +################### + + +def floating_ip_allocate_address(context, host, project_id): + """Allocate free floating ip and return the address. + + Raises if one is not available. + """ + return IMPL.floating_ip_allocate_address(context, host, project_id) + + +def floating_ip_create(context, values): + """Create a floating ip from the values dictionary.""" + return IMPL.floating_ip_create(context, values) + + +def floating_ip_deallocate(context, address): + """Deallocate an floating ip by address""" + return IMPL.floating_ip_deallocate(context, address) + + +def floating_ip_destroy(context, address): + """Destroy the floating_ip or raise if it does not exist.""" + return IMPL.floating_ip_destroy(context, address) + + +def floating_ip_disassociate(context, address): + """Disassociate an floating ip from a fixed ip by address. + + Returns the address of the existing fixed ip. + """ + return IMPL.floating_ip_disassociate(context, address) + + +def floating_ip_fixed_ip_associate(context, floating_address, fixed_address): + """Associate an floating ip to a fixed_ip by address.""" + return IMPL.floating_ip_fixed_ip_associate(context, + floating_address, + fixed_address) + + +def floating_ip_get_all(context): + """Get all floating ips.""" + return IMPL.floating_ip_get_all(context) + + +def floating_ip_get_all_by_host(context, host): + """Get all floating ips.""" + return IMPL.floating_ip_get_all_by_host(context, host) + + +def floating_ip_get_by_address(context, address): + """Get a floating ip by address or raise if it doesn't exist.""" + return IMPL.floating_ip_get_by_address(context, address) + + +def floating_ip_get_instance(context, address): + """Get an instance for a floating ip by address.""" + return IMPL.floating_ip_get_instance(context, address) + + +#################### + + +def fixed_ip_associate(context, address, instance_id): + """Associate fixed ip to instance. + + Raises if fixed ip is not available. + """ + return IMPL.fixed_ip_associate(context, address, instance_id) + + +def fixed_ip_associate_pool(context, network_id, instance_id): + """Find free ip in network and associate it to instance. + + Raises if one is not available. + """ + return IMPL.fixed_ip_associate_pool(context, network_id, instance_id) + + +def fixed_ip_create(context, values): + """Create a fixed ip from the values dictionary.""" + return IMPL.fixed_ip_create(context, values) + + +def fixed_ip_disassociate(context, address): + """Disassociate a fixed ip from an instance by address.""" + return IMPL.fixed_ip_disassociate(context, address) + + +def fixed_ip_get_by_address(context, address): + """Get a fixed ip by address or raise if it does not exist.""" + return IMPL.fixed_ip_get_by_address(context, address) + + +def fixed_ip_get_instance(context, address): + """Get an instance for a fixed ip by address.""" + return IMPL.fixed_ip_get_instance(context, address) + + +def fixed_ip_get_network(context, address): + """Get a network for a fixed ip by address.""" + return IMPL.fixed_ip_get_network(context, address) + + +def fixed_ip_update(context, address, values): + """Create a fixed ip from the values dictionary.""" + return IMPL.fixed_ip_update(context, address, values) + + +#################### + + +def instance_create(context, values): + """Create an instance from the values dictionary.""" + return IMPL.instance_create(context, values) + + +def instance_destroy(context, instance_id): + """Destroy the instance or raise if it does not exist.""" + return IMPL.instance_destroy(context, instance_id) + + +def instance_get(context, instance_id): + """Get an instance or raise if it does not exist.""" + return IMPL.instance_get(context, instance_id) + + +def instance_get_all(context): + """Get all instances.""" + return IMPL.instance_get_all(context) + + +def instance_get_by_project(context, project_id): + """Get all instance belonging to a project.""" + return IMPL.instance_get_by_project(context, project_id) + + +def instance_get_by_reservation(context, reservation_id): + """Get all instance belonging to a reservation.""" + return IMPL.instance_get_by_reservation(context, reservation_id) + + +def instance_get_fixed_address(context, instance_id): + """Get the fixed ip address of an instance.""" + return IMPL.instance_get_fixed_address(context, instance_id) + + +def instance_get_floating_address(context, instance_id): + """Get the first floating ip address of an instance.""" + return IMPL.instance_get_floating_address(context, instance_id) + + +def instance_get_by_str(context, str_id): + """Get an instance by string id.""" + return IMPL.instance_get_by_str(context, str_id) + + +def instance_is_vpn(context, instance_id): + """True if instance is a vpn.""" + return IMPL.instance_is_vpn(context, instance_id) + + +def instance_set_state(context, instance_id, state, description=None): + """Set the state of an instance.""" + return IMPL.instance_set_state(context, instance_id, state, description) + + +def instance_update(context, instance_id, values): + """Set the given properties on an instance and update it. + + Raises NotFound if instance does not exist. + + """ + return IMPL.instance_update(context, instance_id, values) + + +#################### + + +def network_count(context): + """Return the number of networks.""" + return IMPL.network_count(context) + + +def network_count_allocated_ips(context, network_id): + """Return the number of allocated non-reserved ips in the network.""" + return IMPL.network_count_allocated_ips(context, network_id) + + +def network_count_available_ips(context, network_id): + """Return the number of available ips in the network.""" + return IMPL.network_count_available_ips(context, network_id) + + +def network_count_reserved_ips(context, network_id): + """Return the number of reserved ips in the network.""" + return IMPL.network_count_reserved_ips(context, network_id) + + +def network_create(context, values): + """Create a network from the values dictionary.""" + return IMPL.network_create(context, values) + + +def network_create_fixed_ips(context, network_id, num_vpn_clients): + """Create the ips for the network, reserving sepecified ips.""" + return IMPL.network_create_fixed_ips(context, network_id, num_vpn_clients) + + +def network_destroy(context, network_id): + """Destroy the network or raise if it does not exist.""" + return IMPL.network_destroy(context, network_id) + + +def network_get(context, network_id): + """Get an network or raise if it does not exist.""" + return IMPL.network_get(context, network_id) + + +# pylint: disable-msg=C0103 +def network_get_associated_fixed_ips(context, network_id): + """Get all network's ips that have been associated.""" + return IMPL.network_get_associated_fixed_ips(context, network_id) + + +def network_get_by_bridge(context, bridge): + """Get an network or raise if it does not exist.""" + return IMPL.network_get_by_bridge(context, bridge) + + +def network_get_index(context, network_id): + """Get non-conflicting index for network""" + return IMPL.network_get_index(context, network_id) + + +def network_get_vpn_ip(context, network_id): + """Get non-conflicting index for network""" + return IMPL.network_get_vpn_ip(context, network_id) + + +def network_index_count(context): + """Return count of network indexes""" + return IMPL.network_index_count(context) + + +def network_index_create(context, values): + """Create a network index from the values dict""" + return IMPL.network_index_create(context, values) + + +def network_set_cidr(context, network_id, cidr): + """Set the Classless Inner Domain Routing for the network""" + return IMPL.network_set_cidr(context, network_id, cidr) + + +def network_set_host(context, network_id, host_id): + """Safely set the host for network""" + return IMPL.network_set_host(context, network_id, host_id) + + +def network_update(context, network_id, values): + """Set the given properties on an network and update it. + + Raises NotFound if network does not exist. + + """ + return IMPL.network_update(context, network_id, values) + + +################### + + +def project_get_network(context, project_id): + """Return the network associated with the project.""" + return IMPL.project_get_network(context, project_id) + + +################### + + +def queue_get_for(context, topic, physical_node_id): + """Return a channel to send a message to a node with a topic.""" + return IMPL.queue_get_for(context, topic, physical_node_id) + + +################### + + +def export_device_count(context): + """Return count of export devices.""" + return IMPL.export_device_count(context) + + +def export_device_create(context, values): + """Create an export_device from the values dictionary.""" + return IMPL.export_device_create(context, values) + + +################### + + +def volume_allocate_shelf_and_blade(context, volume_id): + """Atomically allocate a free shelf and blade from the pool.""" + return IMPL.volume_allocate_shelf_and_blade(context, volume_id) + + +def volume_attached(context, volume_id, instance_id, mountpoint): + """Ensure that a volume is set as attached.""" + return IMPL.volume_attached(context, volume_id, instance_id, mountpoint) + + +def volume_create(context, values): + """Create a volume from the values dictionary.""" + return IMPL.volume_create(context, values) + + +def volume_destroy(context, volume_id): + """Destroy the volume or raise if it does not exist.""" + return IMPL.volume_destroy(context, volume_id) + + +def volume_detached(context, volume_id): + """Ensure that a volume is set as detached.""" + return IMPL.volume_detached(context, volume_id) + + +def volume_get(context, volume_id): + """Get a volume or raise if it does not exist.""" + return IMPL.volume_get(context, volume_id) + + +def volume_get_all(context): + """Get all volumes.""" + return IMPL.volume_get_all(context) + + +def volume_get_instance(context, volume_id): + """Get the instance that a volume is attached to.""" + return IMPL.volume_get_instance(context, volume_id) + + +def volume_get_by_project(context, project_id): + """Get all volumes belonging to a project.""" + return IMPL.volume_get_by_project(context, project_id) + + +def volume_get_by_str(context, str_id): + """Get a volume by string id.""" + return IMPL.volume_get_by_str(context, str_id) + + +def volume_get_shelf_and_blade(context, volume_id): + """Get the shelf and blade allocated to the volume.""" + return IMPL.volume_get_shelf_and_blade(context, volume_id) + + +def volume_update(context, volume_id, values): + """Set the given properties on an volume and update it. + + Raises NotFound if volume does not exist. + + """ + return IMPL.volume_update(context, volume_id, values) diff --git a/nova/db/sqlalchemy/__init__.py b/nova/db/sqlalchemy/__init__.py new file mode 100644 index 000000000..3288ebd20 --- /dev/null +++ b/nova/db/sqlalchemy/__init__.py @@ -0,0 +1,24 @@ +# 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. + +""" +SQLAlchemy database backend +""" +from nova.db.sqlalchemy import models + +models.register_models() diff --git a/nova/db/sqlalchemy/api.py b/nova/db/sqlalchemy/api.py new file mode 100644 index 000000000..485dca2b0 --- /dev/null +++ b/nova/db/sqlalchemy/api.py @@ -0,0 +1,643 @@ +# 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. +""" +Implementation of SQLAlchemy backend +""" + +from nova import db +from nova import exception +from nova import flags +from nova.db.sqlalchemy import models +from nova.db.sqlalchemy.session import get_session +from sqlalchemy import or_ +from sqlalchemy.orm import joinedload_all + +FLAGS = flags.FLAGS + + +# NOTE(vish): disabling docstring pylint because the docstrings are +# in the interface definition +# pylint: disable-msg=C0111 +def _deleted(context): + """Calculates whether to include deleted objects based on context. + + Currently just looks for a flag called deleted in the context dict. + """ + if not hasattr(context, 'get'): + return False + return context.get('deleted', False) + + +################### + + +def service_get(_context, service_id): + return models.Service.find(service_id) + + +def service_get_by_args(_context, host, binary): + return models.Service.find_by_args(host, binary) + + +def service_create(_context, values): + service_ref = models.Service() + for (key, value) in values.iteritems(): + service_ref[key] = value + service_ref.save() + return service_ref + + +def service_update(_context, service_id, values): + session = get_session() + with session.begin(): + service_ref = models.Service.find(service_id, session=session) + for (key, value) in values.iteritems(): + service_ref[key] = value + service_ref.save(session=session) + + +################### + + +def floating_ip_allocate_address(_context, host, project_id): + session = get_session() + with session.begin(): + floating_ip_ref = session.query(models.FloatingIp + ).filter_by(host=host + ).filter_by(fixed_ip_id=None + ).filter_by(deleted=False + ).with_lockmode('update' + ).first() + # NOTE(vish): if with_lockmode isn't supported, as in sqlite, + # then this has concurrency issues + if not floating_ip_ref: + raise db.NoMoreAddresses() + floating_ip_ref['project_id'] = project_id + session.add(floating_ip_ref) + return floating_ip_ref['address'] + + +def floating_ip_create(_context, values): + floating_ip_ref = models.FloatingIp() + for (key, value) in values.iteritems(): + floating_ip_ref[key] = value + floating_ip_ref.save() + return floating_ip_ref['address'] + + +def floating_ip_fixed_ip_associate(_context, floating_address, fixed_address): + session = get_session() + with session.begin(): + floating_ip_ref = models.FloatingIp.find_by_str(floating_address, + session=session) + fixed_ip_ref = models.FixedIp.find_by_str(fixed_address, + session=session) + floating_ip_ref.fixed_ip = fixed_ip_ref + floating_ip_ref.save(session=session) + + +def floating_ip_deallocate(_context, address): + session = get_session() + with session.begin(): + floating_ip_ref = models.FloatingIp.find_by_str(address, + session=session) + floating_ip_ref['project_id'] = None + floating_ip_ref.save(session=session) + + +def floating_ip_destroy(_context, address): + session = get_session() + with session.begin(): + floating_ip_ref = models.FloatingIp.find_by_str(address, + session=session) + floating_ip_ref.delete(session=session) + + +def floating_ip_disassociate(_context, address): + session = get_session() + with session.begin(): + floating_ip_ref = models.FloatingIp.find_by_str(address, + session=session) + fixed_ip_ref = floating_ip_ref.fixed_ip + if fixed_ip_ref: + fixed_ip_address = fixed_ip_ref['address'] + else: + fixed_ip_address = None + floating_ip_ref.fixed_ip = None + floating_ip_ref.save(session=session) + return fixed_ip_address + + +def floating_ip_get_all(_context): + session = get_session() + return session.query(models.FloatingIp + ).options(joinedload_all('fixed_ip.instance') + ).filter_by(deleted=False + ).all() + + +def floating_ip_get_all_by_host(_context, host): + session = get_session() + return session.query(models.FloatingIp + ).options(joinedload_all('fixed_ip.instance') + ).filter_by(host=host + ).filter_by(deleted=False + ).all() + +def floating_ip_get_by_address(_context, address): + return models.FloatingIp.find_by_str(address) + + +def floating_ip_get_instance(_context, address): + session = get_session() + with session.begin(): + floating_ip_ref = models.FloatingIp.find_by_str(address, + session=session) + return floating_ip_ref.fixed_ip.instance + + +################### + + +def fixed_ip_associate(_context, address, instance_id): + session = get_session() + with session.begin(): + fixed_ip_ref = session.query(models.FixedIp + ).filter_by(address=address + ).filter_by(deleted=False + ).filter_by(instance=None + ).with_lockmode('update' + ).first() + # NOTE(vish): if with_lockmode isn't supported, as in sqlite, + # then this has concurrency issues + if not fixed_ip_ref: + raise db.NoMoreAddresses() + fixed_ip_ref.instance = models.Instance.find(instance_id, + session=session) + session.add(fixed_ip_ref) + + +def fixed_ip_associate_pool(_context, network_id, instance_id): + session = get_session() + with session.begin(): + network_or_none = or_(models.FixedIp.network_id == network_id, + models.FixedIp.network_id == None) + fixed_ip_ref = session.query(models.FixedIp + ).filter(network_or_none + ).filter_by(reserved=False + ).filter_by(deleted=False + ).filter_by(instance=None + ).with_lockmode('update' + ).first() + # NOTE(vish): if with_lockmode isn't supported, as in sqlite, + # then this has concurrency issues + if not fixed_ip_ref: + raise db.NoMoreAddresses() + if not fixed_ip_ref.network: + fixed_ip_ref.network = models.Network.find(network_id, + session=session) + fixed_ip_ref.instance = models.Instance.find(instance_id, + session=session) + session.add(fixed_ip_ref) + return fixed_ip_ref['address'] + + +def fixed_ip_create(_context, values): + fixed_ip_ref = models.FixedIp() + for (key, value) in values.iteritems(): + fixed_ip_ref[key] = value + fixed_ip_ref.save() + return fixed_ip_ref['address'] + + +def fixed_ip_disassociate(_context, address): + session = get_session() + with session.begin(): + fixed_ip_ref = models.FixedIp.find_by_str(address, session=session) + fixed_ip_ref.instance = None + fixed_ip_ref.save(session=session) + + +def fixed_ip_get_by_address(_context, address): + return models.FixedIp.find_by_str(address) + + +def fixed_ip_get_instance(_context, address): + session = get_session() + with session.begin(): + return models.FixedIp.find_by_str(address, session=session).instance + + +def fixed_ip_get_network(_context, address): + session = get_session() + with session.begin(): + return models.FixedIp.find_by_str(address, session=session).network + + +def fixed_ip_update(_context, address, values): + session = get_session() + with session.begin(): + fixed_ip_ref = models.FixedIp.find_by_str(address, session=session) + for (key, value) in values.iteritems(): + fixed_ip_ref[key] = value + fixed_ip_ref.save(session=session) + + +################### + + +def instance_create(_context, values): + instance_ref = models.Instance() + for (key, value) in values.iteritems(): + instance_ref[key] = value + instance_ref.save() + return instance_ref + + +def instance_destroy(_context, instance_id): + session = get_session() + with session.begin(): + instance_ref = models.Instance.find(instance_id, session=session) + instance_ref.delete(session=session) + + +def instance_get(context, instance_id): + return models.Instance.find(instance_id, deleted=_deleted(context)) + + +def instance_get_all(context): + session = get_session() + return session.query(models.Instance + ).options(joinedload_all('fixed_ip.floating_ips') + ).filter_by(deleted=_deleted(context) + ).all() + + +def instance_get_by_project(context, project_id): + session = get_session() + return session.query(models.Instance + ).options(joinedload_all('fixed_ip.floating_ips') + ).filter_by(project_id=project_id + ).filter_by(deleted=_deleted(context) + ).all() + + +def instance_get_by_reservation(_context, reservation_id): + session = get_session() + return session.query(models.Instance + ).options(joinedload_all('fixed_ip.floating_ips') + ).filter_by(reservation_id=reservation_id + ).filter_by(deleted=False + ).all() + + +def instance_get_by_str(context, str_id): + return models.Instance.find_by_str(str_id, deleted=_deleted(context)) + + +def instance_get_fixed_address(_context, instance_id): + session = get_session() + with session.begin(): + instance_ref = models.Instance.find(instance_id, session=session) + if not instance_ref.fixed_ip: + return None + return instance_ref.fixed_ip['address'] + + +def instance_get_floating_address(_context, instance_id): + session = get_session() + with session.begin(): + instance_ref = models.Instance.find(instance_id, session=session) + if not instance_ref.fixed_ip: + return None + if not instance_ref.fixed_ip.floating_ips: + return None + # NOTE(vish): this just returns the first floating ip + return instance_ref.fixed_ip.floating_ips[0]['address'] + + +def instance_is_vpn(context, instance_id): + # TODO(vish): Move this into image code somewhere + instance_ref = instance_get(context, instance_id) + return instance_ref['image_id'] == FLAGS.vpn_image_id + + +def instance_set_state(context, instance_id, state, description=None): + # TODO(devcamcar): Move this out of models and into driver + from nova.compute import power_state + if not description: + description = power_state.name(state) + db.instance_update(context, + instance_id, + {'state': state, + 'state_description': description}) + + +def instance_update(_context, instance_id, values): + session = get_session() + with session.begin(): + instance_ref = models.Instance.find(instance_id, session=session) + for (key, value) in values.iteritems(): + instance_ref[key] = value + instance_ref.save(session=session) + + +################### + + +def network_count(_context): + return models.Network.count() + + +def network_count_allocated_ips(_context, network_id): + session = get_session() + return session.query(models.FixedIp + ).filter_by(network_id=network_id + ).filter_by(allocated=True + ).filter_by(deleted=False + ).count() + + +def network_count_available_ips(_context, network_id): + session = get_session() + return session.query(models.FixedIp + ).filter_by(network_id=network_id + ).filter_by(allocated=False + ).filter_by(reserved=False + ).filter_by(deleted=False + ).count() + + +def network_count_reserved_ips(_context, network_id): + session = get_session() + return session.query(models.FixedIp + ).filter_by(network_id=network_id + ).filter_by(reserved=True + ).filter_by(deleted=False + ).count() + + +def network_create(_context, values): + network_ref = models.Network() + for (key, value) in values.iteritems(): + network_ref[key] = value + network_ref.save() + return network_ref + + +def network_destroy(_context, network_id): + session = get_session() + with session.begin(): + # TODO(vish): do we have to use sql here? + session.execute('update networks set deleted=1 where id=:id', + {'id': network_id}) + session.execute('update fixed_ips set deleted=1 where network_id=:id', + {'id': network_id}) + session.execute('update floating_ips set deleted=1 ' + 'where fixed_ip_id in ' + '(select id from fixed_ips ' + 'where network_id=:id)', + {'id': network_id}) + session.execute('update network_indexes set network_id=NULL ' + 'where network_id=:id', + {'id': network_id}) + + +def network_get(_context, network_id): + return models.Network.find(network_id) + + +# NOTE(vish): pylint complains because of the long method name, but +# it fits with the names of the rest of the methods +# pylint: disable-msg=C0103 +def network_get_associated_fixed_ips(_context, network_id): + session = get_session() + return session.query(models.FixedIp + ).filter_by(network_id=network_id + ).filter(models.FixedIp.instance_id != None + ).filter_by(deleted=False + ).all() + + +def network_get_by_bridge(_context, bridge): + session = get_session() + rv = session.query(models.Network + ).filter_by(bridge=bridge + ).filter_by(deleted=False + ).first() + if not rv: + raise exception.NotFound('No network for bridge %s' % bridge) + return rv + + +def network_get_index(_context, network_id): + session = get_session() + with session.begin(): + network_index = session.query(models.NetworkIndex + ).filter_by(network_id=None + ).filter_by(deleted=False + ).with_lockmode('update' + ).first() + if not network_index: + raise db.NoMoreNetworks() + network_index['network'] = models.Network.find(network_id, + session=session) + session.add(network_index) + return network_index['index'] + + +def network_index_count(_context): + return models.NetworkIndex.count() + + +def network_index_create(_context, values): + network_index_ref = models.NetworkIndex() + for (key, value) in values.iteritems(): + network_index_ref[key] = value + network_index_ref.save() + + +def network_set_host(_context, network_id, host_id): + session = get_session() + with session.begin(): + network = session.query(models.Network + ).filter_by(id=network_id + ).filter_by(deleted=False + ).with_lockmode('update' + ).first() + if not network: + raise exception.NotFound("Couldn't find network with %s" % + network_id) + # NOTE(vish): if with_lockmode isn't supported, as in sqlite, + # then this has concurrency issues + if not network['host']: + network['host'] = host_id + session.add(network) + return network['host'] + + +def network_update(_context, network_id, values): + session = get_session() + with session.begin(): + network_ref = models.Network.find(network_id, session=session) + for (key, value) in values.iteritems(): + network_ref[key] = value + network_ref.save(session=session) + + +################### + + +def project_get_network(_context, project_id): + session = get_session() + rv = session.query(models.Network + ).filter_by(project_id=project_id + ).filter_by(deleted=False + ).first() + if not rv: + raise exception.NotFound('No network for project: %s' % project_id) + return rv + + +################### + + +def queue_get_for(_context, topic, physical_node_id): + # FIXME(ja): this should be servername? + return "%s.%s" % (topic, physical_node_id) + +################### + + +def export_device_count(_context): + return models.ExportDevice.count() + + +def export_device_create(_context, values): + export_device_ref = models.ExportDevice() + for (key, value) in values.iteritems(): + export_device_ref[key] = value + export_device_ref.save() + return export_device_ref + + +################### + + +def volume_allocate_shelf_and_blade(_context, volume_id): + session = get_session() + with session.begin(): + export_device = session.query(models.ExportDevice + ).filter_by(volume=None + ).filter_by(deleted=False + ).with_lockmode('update' + ).first() + # NOTE(vish): if with_lockmode isn't supported, as in sqlite, + # then this has concurrency issues + if not export_device: + raise db.NoMoreBlades() + export_device.volume_id = volume_id + session.add(export_device) + return (export_device.shelf_id, export_device.blade_id) + + +def volume_attached(_context, volume_id, instance_id, mountpoint): + session = get_session() + with session.begin(): + volume_ref = models.Volume.find(volume_id, session=session) + volume_ref['status'] = 'in-use' + volume_ref['mountpoint'] = mountpoint + volume_ref['attach_status'] = 'attached' + volume_ref.instance = models.Instance.find(instance_id, + session=session) + volume_ref.save(session=session) + + +def volume_create(_context, values): + volume_ref = models.Volume() + for (key, value) in values.iteritems(): + volume_ref[key] = value + volume_ref.save() + return volume_ref + + +def volume_destroy(_context, volume_id): + session = get_session() + with session.begin(): + # TODO(vish): do we have to use sql here? + session.execute('update volumes set deleted=1 where id=:id', + {'id': volume_id}) + session.execute('update export_devices set volume_id=NULL ' + 'where volume_id=:id', + {'id': volume_id}) + + +def volume_detached(_context, volume_id): + session = get_session() + with session.begin(): + volume_ref = models.Volume.find(volume_id, session=session) + volume_ref['status'] = 'available' + volume_ref['mountpoint'] = None + volume_ref['attach_status'] = 'detached' + volume_ref.instance = None + volume_ref.save(session=session) + + +def volume_get(context, volume_id): + return models.Volume.find(volume_id, deleted=_deleted(context)) + + +def volume_get_all(context): + return models.Volume.all(deleted=_deleted(context)) + + +def volume_get_by_project(context, project_id): + session = get_session() + return session.query(models.Volume + ).filter_by(project_id=project_id + ).filter_by(deleted=_deleted(context) + ).all() + + +def volume_get_by_str(context, str_id): + return models.Volume.find_by_str(str_id, deleted=_deleted(context)) + + +def volume_get_instance(_context, volume_id): + session = get_session() + with session.begin(): + return models.Volume.find(volume_id, session=session).instance + + +def volume_get_shelf_and_blade(_context, volume_id): + session = get_session() + export_device = session.query(models.ExportDevice + ).filter_by(volume_id=volume_id + ).first() + if not export_device: + raise exception.NotFound() + return (export_device.shelf_id, export_device.blade_id) + + +def volume_update(_context, volume_id, values): + session = get_session() + with session.begin(): + volume_ref = models.Volume.find(volume_id, session=session) + for (key, value) in values.iteritems(): + volume_ref[key] = value + volume_ref.save(session=session) diff --git a/nova/db/sqlalchemy/models.py b/nova/db/sqlalchemy/models.py new file mode 100644 index 000000000..6818f838c --- /dev/null +++ b/nova/db/sqlalchemy/models.py @@ -0,0 +1,394 @@ +# 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. + +""" +SQLAlchemy models for nova data +""" + +import sys +import datetime + +# TODO(vish): clean up these imports +from sqlalchemy.orm import relationship, backref, exc, object_mapper +from sqlalchemy import Column, Integer, String +from sqlalchemy import ForeignKey, DateTime, Boolean, Text +from sqlalchemy.ext.declarative import declarative_base + +from nova.db.sqlalchemy.session import get_session + +from nova import auth +from nova import exception +from nova import flags + +FLAGS = flags.FLAGS + +BASE = declarative_base() + + +class NovaBase(object): + """Base class for Nova Models""" + __table_args__ = {'mysql_engine': 'InnoDB'} + __table_initialized__ = False + __prefix__ = 'none' + created_at = Column(DateTime, default=datetime.datetime.utcnow) + updated_at = Column(DateTime, onupdate=datetime.datetime.utcnow) + deleted_at = Column(DateTime) + deleted = Column(Boolean, default=False) + + @classmethod + def all(cls, session=None, deleted=False): + """Get all objects of this type""" + if not session: + session = get_session() + return session.query(cls + ).filter_by(deleted=deleted + ).all() + + @classmethod + def count(cls, session=None, deleted=False): + """Count objects of this type""" + if not session: + session = get_session() + return session.query(cls + ).filter_by(deleted=deleted + ).count() + + @classmethod + def find(cls, obj_id, session=None, deleted=False): + """Find object by id""" + if not session: + session = get_session() + try: + return session.query(cls + ).filter_by(id=obj_id + ).filter_by(deleted=deleted + ).one() + except exc.NoResultFound: + new_exc = exception.NotFound("No model for id %s" % obj_id) + raise new_exc.__class__, new_exc, sys.exc_info()[2] + + @classmethod + def find_by_str(cls, str_id, session=None, deleted=False): + """Find object by str_id""" + int_id = int(str_id.rpartition('-')[2]) + return cls.find(int_id, session=session, deleted=deleted) + + @property + def str_id(self): + """Get string id of object (generally prefix + '-' + id)""" + return "%s-%s" % (self.__prefix__, self.id) + + def save(self, session=None): + """Save this object""" + if not session: + session = get_session() + session.add(self) + session.flush() + + def delete(self, session=None): + """Delete this object""" + self.deleted = True + self.deleted_at = datetime.datetime.now() + self.save(session=session) + + def __setitem__(self, key, value): + setattr(self, key, value) + + def __getitem__(self, key): + return getattr(self, key) + + def __iter__(self): + self._i = iter(object_mapper(self).columns) + return self + + def next(self): + n = self._i.next().name + return n, getattr(self, n) + +# TODO(vish): Store images in the database instead of file system +#class Image(BASE, NovaBase): +# """Represents an image in the datastore""" +# __tablename__ = 'images' +# __prefix__ = 'ami' +# id = Column(Integer, primary_key=True) +# user_id = Column(String(255)) +# project_id = Column(String(255)) +# image_type = Column(String(255)) +# public = Column(Boolean, default=False) +# state = Column(String(255)) +# location = Column(String(255)) +# arch = Column(String(255)) +# default_kernel_id = Column(String(255)) +# default_ramdisk_id = Column(String(255)) +# +# @validates('image_type') +# def validate_image_type(self, key, image_type): +# assert(image_type in ['machine', 'kernel', 'ramdisk', 'raw']) +# +# @validates('state') +# def validate_state(self, key, state): +# assert(state in ['available', 'pending', 'disabled']) +# +# @validates('default_kernel_id') +# def validate_kernel_id(self, key, val): +# if val != 'machine': +# assert(val is None) +# +# @validates('default_ramdisk_id') +# def validate_ramdisk_id(self, key, val): +# if val != 'machine': +# assert(val is None) +# +# +# TODO(vish): To make this into its own table, we need a good place to +# create the host entries. In config somwhere? Or the first +# time any object sets host? This only becomes particularly +# important if we need to store per-host data. +#class Host(BASE, NovaBase): +# """Represents a host where services are running""" +# __tablename__ = 'hosts' +# id = Column(String(255), primary_key=True) +# +# +class Service(BASE, NovaBase): + """Represents a running service on a host""" + __tablename__ = 'services' + id = Column(Integer, primary_key=True) + host = Column(String(255)) # , ForeignKey('hosts.id')) + binary = Column(String(255)) + topic = Column(String(255)) + report_count = Column(Integer, nullable=False, default=0) + + @classmethod + def find_by_args(cls, host, binary, session=None, deleted=False): + if not session: + session = get_session() + try: + return session.query(cls + ).filter_by(host=host + ).filter_by(binary=binary + ).filter_by(deleted=deleted + ).one() + except exc.NoResultFound: + new_exc = exception.NotFound("No model for %s, %s" % (host, + binary)) + raise new_exc.__class__, new_exc, sys.exc_info()[2] + + +class Instance(BASE, NovaBase): + """Represents a guest vm""" + __tablename__ = 'instances' + __prefix__ = 'i' + id = Column(Integer, primary_key=True) + + user_id = Column(String(255)) + project_id = Column(String(255)) + + @property + def user(self): + return auth.manager.AuthManager().get_user(self.user_id) + + @property + def project(self): + return auth.manager.AuthManager().get_project(self.project_id) + + @property + def name(self): + return self.str_id + + image_id = Column(String(255)) + kernel_id = Column(String(255)) + ramdisk_id = Column(String(255)) +# image_id = Column(Integer, ForeignKey('images.id'), nullable=True) +# kernel_id = Column(Integer, ForeignKey('images.id'), nullable=True) +# ramdisk_id = Column(Integer, ForeignKey('images.id'), nullable=True) +# ramdisk = relationship(Ramdisk, backref=backref('instances', order_by=id)) +# kernel = relationship(Kernel, backref=backref('instances', order_by=id)) +# project = relationship(Project, backref=backref('instances', order_by=id)) + + launch_index = Column(Integer) + key_name = Column(String(255)) + key_data = Column(Text) + security_group = Column(String(255)) + + state = Column(Integer) + state_description = Column(String(255)) + + hostname = Column(String(255)) + host = Column(String(255)) # , ForeignKey('hosts.id')) + + instance_type = Column(String(255)) + + user_data = Column(Text) + + reservation_id = Column(String(255)) + mac_address = Column(String(255)) + + launched_at = Column(DateTime) + terminated_at = Column(DateTime) + # TODO(vish): see Ewan's email about state improvements, probably + # should be in a driver base class or some such + # vmstate_state = running, halted, suspended, paused + # power_state = what we have + # task_state = transitory and may trigger power state transition + + #@validates('state') + #def validate_state(self, key, state): + # assert(state in ['nostate', 'running', 'blocked', 'paused', + # 'shutdown', 'shutoff', 'crashed']) + + +class Volume(BASE, NovaBase): + """Represents a block storage device that can be attached to a vm""" + __tablename__ = 'volumes' + __prefix__ = 'vol' + id = Column(Integer, primary_key=True) + + user_id = Column(String(255)) + project_id = Column(String(255)) + + host = Column(String(255)) # , ForeignKey('hosts.id')) + size = Column(Integer) + availability_zone = Column(String(255)) # TODO(vish): foreign key? + instance_id = Column(Integer, ForeignKey('instances.id'), nullable=True) + instance = relationship(Instance, backref=backref('volumes')) + mountpoint = Column(String(255)) + attach_time = Column(String(255)) # TODO(vish): datetime + status = Column(String(255)) # TODO(vish): enum? + attach_status = Column(String(255)) # TODO(vish): enum + + +class ExportDevice(BASE, NovaBase): + """Represates a shelf and blade that a volume can be exported on""" + __tablename__ = 'export_devices' + id = Column(Integer, primary_key=True) + shelf_id = Column(Integer) + blade_id = Column(Integer) + volume_id = Column(Integer, ForeignKey('volumes.id'), nullable=True) + volume = relationship(Volume, backref=backref('export_device', + uselist=False)) + + +class Network(BASE, NovaBase): + """Represents a network""" + __tablename__ = 'networks' + id = Column(Integer, primary_key=True) + + injected = Column(Boolean, default=False) + cidr = Column(String(255)) + netmask = Column(String(255)) + bridge = Column(String(255)) + gateway = Column(String(255)) + broadcast = Column(String(255)) + dns = Column(String(255)) + + vlan = Column(Integer) + vpn_public_address = Column(String(255)) + vpn_public_port = Column(Integer) + vpn_private_address = Column(String(255)) + dhcp_start = Column(String(255)) + + project_id = Column(String(255)) + host = Column(String(255)) # , ForeignKey('hosts.id')) + + +class NetworkIndex(BASE, NovaBase): + """Represents a unique offset for a network + + Currently vlan number, vpn port, and fixed ip ranges are keyed off of + this index. These may ultimately need to be converted to separate + pools. + """ + __tablename__ = 'network_indexes' + id = Column(Integer, primary_key=True) + index = Column(Integer) + network_id = Column(Integer, ForeignKey('networks.id'), nullable=True) + network = relationship(Network, backref=backref('network_index', + uselist=False)) + + +# TODO(vish): can these both come from the same baseclass? +class FixedIp(BASE, NovaBase): + """Represents a fixed ip for an instance""" + __tablename__ = 'fixed_ips' + id = Column(Integer, primary_key=True) + address = Column(String(255)) + network_id = Column(Integer, ForeignKey('networks.id'), nullable=True) + network = relationship(Network, backref=backref('fixed_ips')) + instance_id = Column(Integer, ForeignKey('instances.id'), nullable=True) + instance = relationship(Instance, backref=backref('fixed_ip', + uselist=False)) + allocated = Column(Boolean, default=False) + leased = Column(Boolean, default=False) + reserved = Column(Boolean, default=False) + + @property + def str_id(self): + return self.address + + @classmethod + def find_by_str(cls, str_id, session=None, deleted=False): + if not session: + session = get_session() + try: + return session.query(cls + ).filter_by(address=str_id + ).filter_by(deleted=deleted + ).one() + except exc.NoResultFound: + new_exc = exception.NotFound("No model for address %s" % str_id) + raise new_exc.__class__, new_exc, sys.exc_info()[2] + + +class FloatingIp(BASE, NovaBase): + """Represents a floating ip that dynamically forwards to a fixed ip""" + __tablename__ = 'floating_ips' + id = Column(Integer, primary_key=True) + address = Column(String(255)) + fixed_ip_id = Column(Integer, ForeignKey('fixed_ips.id'), nullable=True) + fixed_ip = relationship(FixedIp, backref=backref('floating_ips')) + + project_id = Column(String(255)) + host = Column(String(255)) # , ForeignKey('hosts.id')) + + @property + def str_id(self): + return self.address + + @classmethod + def find_by_str(cls, str_id, session=None, deleted=False): + if not session: + session = get_session() + try: + return session.query(cls + ).filter_by(address=str_id + ).filter_by(deleted=deleted + ).one() + except exc.NoResultFound: + new_exc = exception.NotFound("No model for address %s" % str_id) + raise new_exc.__class__, new_exc, sys.exc_info()[2] + + +def register_models(): + """Register Models and create metadata""" + from sqlalchemy import create_engine + models = (Service, Instance, Volume, ExportDevice, + FixedIp, FloatingIp, Network, NetworkIndex) # , Image, Host) + engine = create_engine(FLAGS.sql_connection, echo=False) + for model in models: + model.metadata.create_all(engine) diff --git a/nova/db/sqlalchemy/session.py b/nova/db/sqlalchemy/session.py new file mode 100644 index 000000000..69a205378 --- /dev/null +++ b/nova/db/sqlalchemy/session.py @@ -0,0 +1,42 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2010 United States Government as represented by the +# Administrator of the National Aeronautics and Space Administration. +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +""" +Session Handling for SQLAlchemy backend +""" + +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from nova import flags + +FLAGS = flags.FLAGS + +_ENGINE = None +_MAKER = None + +def get_session(autocommit=True, expire_on_commit=False): + """Helper method to grab session""" + global _ENGINE + global _MAKER + if not _MAKER: + if not _ENGINE: + _ENGINE = create_engine(FLAGS.sql_connection, echo=False) + _MAKER = sessionmaker(bind=_ENGINE, + autocommit=autocommit, + expire_on_commit=expire_on_commit) + return _MAKER() diff --git a/nova/endpoint/admin.py b/nova/endpoint/admin.py index d6f622755..c6dcb5320 100644 --- a/nova/endpoint/admin.py +++ b/nova/endpoint/admin.py @@ -22,8 +22,9 @@ Admin API controller, exposed through http via the api worker. import base64 +from nova import db +from nova import exception from nova.auth import manager -from nova.compute import model def user_dict(user, base64_file=None): @@ -181,7 +182,7 @@ class AdminController(object): result = { 'members': [{'member': m} for m in project.member_ids]} return result - + @admin_only def modify_project_member(self, context, user, project, operation, **kwargs): """Add or remove a user from a project.""" @@ -193,6 +194,8 @@ class AdminController(object): raise exception.ApiError('operation must be add or remove') return True + # FIXME(vish): these host commands don't work yet, perhaps some of the + # required data can be retrieved from service objects? @admin_only def describe_hosts(self, _context, **_kwargs): """Returns status info for all nodes. Includes: @@ -203,9 +206,9 @@ class AdminController(object): * DHCP servers running * Iptables / bridges """ - return {'hostSet': [host_dict(h) for h in model.Host.all()]} + return {'hostSet': [host_dict(h) for h in db.host_get_all()]} @admin_only def describe_host(self, _context, name, **_kwargs): """Returns status info for single node.""" - return host_dict(model.Host.lookup(name)) + return host_dict(db.host_get(name)) diff --git a/nova/endpoint/cloud.py b/nova/endpoint/cloud.py index 8e2beb1e3..622b4e2a4 100644 --- a/nova/endpoint/cloud.py +++ b/nova/endpoint/cloud.py @@ -29,22 +29,19 @@ import time from twisted.internet import defer -from nova import datastore +from nova import db from nova import exception from nova import flags from nova import rpc from nova import utils from nova.auth import rbac from nova.auth import manager -from nova.compute import model from nova.compute.instance_types import INSTANCE_TYPES from nova.endpoint import images -from nova.network import service as network_service -from nova.network import model as network_model -from nova.volume import service FLAGS = flags.FLAGS +flags.DECLARE('storage_availability_zone', 'nova.volume.manager') def _gen_key(user_id, key_name): @@ -63,26 +60,16 @@ class CloudController(object): sent to the other nodes. """ def __init__(self): - self.instdir = model.InstanceDirectory() + self.network_manager = utils.import_object(FLAGS.network_manager) self.setup() - @property - def instances(self): - """ All instances in the system, as dicts """ - return self.instdir.all - - @property - def volumes(self): - """ returns a list of all volumes """ - for volume_id in datastore.Redis.instance().smembers("volumes"): - volume = service.get_volume(volume_id) - yield volume - def __str__(self): return 'CloudController' def setup(self): """ Ensure the keychains and folders exist. """ + # FIXME(ja): this should be moved to a nova-manage command, + # if not setup throw exceptions instead of running # Create keys folder, if it doesn't exist if not os.path.exists(FLAGS.keys_path): os.makedirs(FLAGS.keys_path) @@ -91,18 +78,15 @@ class CloudController(object): if not os.path.exists(root_ca_path): start = os.getcwd() os.chdir(FLAGS.ca_path) + # TODO(vish): Do this with M2Crypto instead utils.runthis("Generating root CA: %s", "sh genrootca.sh") os.chdir(start) - # TODO: Do this with M2Crypto instead - - def get_instance_by_ip(self, ip): - return self.instdir.by_ip(ip) def _get_mpi_data(self, project_id): result = {} - for instance in self.instdir.all: - if instance['project_id'] == project_id: - line = '%s slots=%d' % (instance['private_dns_name'], + for instance in db.instance_get_by_project(None, project_id): + if instance['fixed_ip']: + line = '%s slots=%d' % (instance['fixed_ip']['str_id'], INSTANCE_TYPES[instance['instance_type']]['vcpus']) if instance['key_name'] in result: result[instance['key_name']].append(line) @@ -110,33 +94,30 @@ class CloudController(object): result[instance['key_name']] = [line] return result - def get_metadata(self, ipaddress): - i = self.get_instance_by_ip(ipaddress) - if i is None: + def get_metadata(self, address): + instance_ref = db.fixed_ip_get_instance(None, address) + if instance_ref is None: return None - mpi = self._get_mpi_data(i['project_id']) - if i['key_name']: + mpi = self._get_mpi_data(instance_ref['project_id']) + if instance_ref['key_name']: keys = { '0': { - '_name': i['key_name'], - 'openssh-key': i['key_data'] + '_name': instance_ref['key_name'], + 'openssh-key': instance_ref['key_data'] } } else: keys = '' - - address_record = network_model.FixedIp(i['private_dns_name']) - if address_record: - hostname = address_record['hostname'] - else: - hostname = 'ip-%s' % i['private_dns_name'].replace('.', '-') + hostname = instance_ref['hostname'] + floating_ip = db.instance_get_floating_address(None, + instance_ref['id']) data = { - 'user-data': base64.b64decode(i['user_data']), + 'user-data': base64.b64decode(instance_ref['user_data']), 'meta-data': { - 'ami-id': i['image_id'], - 'ami-launch-index': i['ami_launch_index'], - 'ami-manifest-path': 'FIXME', # image property - 'block-device-mapping': { # TODO: replace with real data + 'ami-id': instance_ref['image_id'], + 'ami-launch-index': instance_ref['launch_index'], + 'ami-manifest-path': 'FIXME', + 'block-device-mapping': { # TODO(vish): replace with real data 'ami': 'sda1', 'ephemeral0': 'sda2', 'root': '/dev/sda1', @@ -144,27 +125,27 @@ class CloudController(object): }, 'hostname': hostname, 'instance-action': 'none', - 'instance-id': i['instance_id'], - 'instance-type': i.get('instance_type', ''), + 'instance-id': instance_ref['str_id'], + 'instance-type': instance_ref['instance_type'], 'local-hostname': hostname, - 'local-ipv4': i['private_dns_name'], # TODO: switch to IP - 'kernel-id': i.get('kernel_id', ''), + 'local-ipv4': address, + 'kernel-id': instance_ref['kernel_id'], 'placement': { - 'availaibility-zone': i.get('availability_zone', 'nova'), + 'availability-zone': 'nova' # TODO(vish): real zone }, 'public-hostname': hostname, - 'public-ipv4': i.get('dns_name', ''), # TODO: switch to IP + 'public-ipv4': floating_ip or '', 'public-keys': keys, - 'ramdisk-id': i.get('ramdisk_id', ''), - 'reservation-id': i['reservation_id'], - 'security-groups': i.get('groups', ''), + 'ramdisk-id': instance_ref['ramdisk_id'], + 'reservation-id': instance_ref['reservation_id'], + 'security-groups': '', 'mpi': mpi } } - if False: # TODO: store ancestor ids + if False: # TODO(vish): store ancestor ids data['ancestor-ami-ids'] = [] - if i.get('product_codes', None): - data['product-codes'] = i['product_codes'] + if False: # TODO(vish): store product codes + data['product-codes'] = [] return data @rbac.allow('all') @@ -251,141 +232,114 @@ class CloudController(object): @rbac.allow('projectmanager', 'sysadmin') def get_console_output(self, context, instance_id, **kwargs): # instance_id is passed in as a list of instances - instance = self._get_instance(context, instance_id[0]) - return rpc.call('%s.%s' % (FLAGS.compute_topic, instance['node_name']), - {"method": "get_console_output", - "args": {"instance_id": instance_id[0]}}) - - def _get_user_id(self, context): - if context and context.user: - return context.user.id - else: - return None + instance_ref = db.instance_get_by_str(context, instance_id[0]) + return rpc.call('%s.%s' % (FLAGS.compute_topic, + instance_ref['host']), + {"method": "get_console_output", + "args": {"context": None, + "instance_id": instance_ref['id']}}) @rbac.allow('projectmanager', 'sysadmin') def describe_volumes(self, context, **kwargs): - volumes = [] - for volume in self.volumes: - if context.user.is_admin() or volume['project_id'] == context.project.id: - v = self.format_volume(context, volume) - volumes.append(v) - return defer.succeed({'volumeSet': volumes}) - - def format_volume(self, context, volume): + if context.user.is_admin(): + volumes = db.volume_get_all(context) + else: + volumes = db.volume_get_by_project(context, context.project.id) + + volumes = [self._format_volume(context, v) for v in volumes] + + return {'volumeSet': volumes} + + def _format_volume(self, context, volume): v = {} - v['volumeId'] = volume['volume_id'] + v['volumeId'] = volume['str_id'] v['status'] = volume['status'] v['size'] = volume['size'] v['availabilityZone'] = volume['availability_zone'] - v['createTime'] = volume['create_time'] + v['createTime'] = volume['created_at'] if context.user.is_admin(): v['status'] = '%s (%s, %s, %s, %s)' % ( - volume.get('status', None), - volume.get('user_id', None), - volume.get('node_name', None), - volume.get('instance_id', ''), - volume.get('mountpoint', '')) + volume['status'], + volume['user_id'], + volume['host'], + volume['instance_id'], + volume['mountpoint']) if volume['attach_status'] == 'attached': v['attachmentSet'] = [{'attachTime': volume['attach_time'], - 'deleteOnTermination': volume['delete_on_termination'], + 'deleteOnTermination': False, 'device': volume['mountpoint'], 'instanceId': volume['instance_id'], 'status': 'attached', - 'volume_id': volume['volume_id']}] + 'volume_id': volume['str_id']}] else: v['attachmentSet'] = [{}] return v @rbac.allow('projectmanager', 'sysadmin') - @defer.inlineCallbacks def create_volume(self, context, size, **kwargs): - # TODO(vish): refactor this to create the volume object here and tell service to create it - result = yield rpc.call(FLAGS.volume_topic, {"method": "create_volume", - "args": {"size": size, - "user_id": context.user.id, - "project_id": context.project.id}}) - # NOTE(vish): rpc returned value is in the result key in the dictionary - volume = self._get_volume(context, result) - defer.returnValue({'volumeSet': [self.format_volume(context, volume)]}) - - def _get_address(self, context, public_ip): - # FIXME(vish) this should move into network.py - address = network_model.ElasticIp.lookup(public_ip) - if address and (context.user.is_admin() or address['project_id'] == context.project.id): - return address - raise exception.NotFound("Address at ip %s not found" % public_ip) - - def _get_image(self, context, image_id): - """passes in context because - objectstore does its own authorization""" - result = images.list(context, [image_id]) - if not result: - raise exception.NotFound('Image %s could not be found' % image_id) - image = result[0] - return image - - def _get_instance(self, context, instance_id): - for instance in self.instdir.all: - if instance['instance_id'] == instance_id: - if context.user.is_admin() or instance['project_id'] == context.project.id: - return instance - raise exception.NotFound('Instance %s could not be found' % instance_id) - - def _get_volume(self, context, volume_id): - volume = service.get_volume(volume_id) - if context.user.is_admin() or volume['project_id'] == context.project.id: - return volume - raise exception.NotFound('Volume %s could not be found' % volume_id) + vol = {} + vol['size'] = size + vol['user_id'] = context.user.id + vol['project_id'] = context.project.id + vol['availability_zone'] = FLAGS.storage_availability_zone + vol['status'] = "creating" + vol['attach_status'] = "detached" + volume_ref = db.volume_create(context, vol) + + rpc.cast(FLAGS.volume_topic, {"method": "create_volume", + "args": {"context": None, + "volume_id": volume_ref['id']}}) + + return {'volumeSet': [self._format_volume(context, volume_ref)]} + @rbac.allow('projectmanager', 'sysadmin') def attach_volume(self, context, volume_id, instance_id, device, **kwargs): - volume = self._get_volume(context, volume_id) - if volume['status'] == "attached": + volume_ref = db.volume_get_by_str(context, volume_id) + # TODO(vish): abstract status checking? + if volume_ref['attach_status'] == "attached": raise exception.ApiError("Volume is already attached") - # TODO(vish): looping through all volumes is slow. We should probably maintain an index - for vol in self.volumes: - if vol['instance_id'] == instance_id and vol['mountpoint'] == device: - raise exception.ApiError("Volume %s is already attached to %s" % (vol['volume_id'], vol['mountpoint'])) - volume.start_attach(instance_id, device) - instance = self._get_instance(context, instance_id) - compute_node = instance['node_name'] - rpc.cast('%s.%s' % (FLAGS.compute_topic, compute_node), + instance_ref = db.instance_get_by_str(context, instance_id) + host = instance_ref['host'] + rpc.cast(db.queue_get_for(context, FLAGS.compute_topic, host), {"method": "attach_volume", - "args": {"volume_id": volume_id, - "instance_id": instance_id, - "mountpoint": device}}) - return defer.succeed({'attachTime': volume['attach_time'], - 'device': volume['mountpoint'], - 'instanceId': instance_id, + "args": {"context": None, + "volume_id": volume_ref['id'], + "instance_id": instance_ref['id'], + "mountpoint": device}}) + return defer.succeed({'attachTime': volume_ref['attach_time'], + 'device': volume_ref['mountpoint'], + 'instanceId': instance_ref['id'], 'requestId': context.request_id, - 'status': volume['attach_status'], - 'volumeId': volume_id}) + 'status': volume_ref['attach_status'], + 'volumeId': volume_ref['id']}) @rbac.allow('projectmanager', 'sysadmin') def detach_volume(self, context, volume_id, **kwargs): - volume = self._get_volume(context, volume_id) - instance_id = volume.get('instance_id', None) - if not instance_id: + volume_ref = db.volume_get_by_str(context, volume_id) + instance_ref = db.volume_get_instance(context, volume_ref['id']) + if not instance_ref: raise exception.Error("Volume isn't attached to anything!") - if volume['status'] == "available": + # TODO(vish): abstract status checking? + if volume_ref['status'] == "available": raise exception.Error("Volume is already detached") try: - volume.start_detach() - instance = self._get_instance(context, instance_id) - rpc.cast('%s.%s' % (FLAGS.compute_topic, instance['node_name']), + host = instance_ref['host'] + rpc.cast(db.queue_get_for(context, FLAGS.compute_topic, host), {"method": "detach_volume", - "args": {"instance_id": instance_id, - "volume_id": volume_id}}) + "args": {"context": None, + "instance_id": instance_ref['id'], + "volume_id": volume_ref['id']}}) except exception.NotFound: # If the instance doesn't exist anymore, # then we need to call detach blind - volume.finish_detach() - return defer.succeed({'attachTime': volume['attach_time'], - 'device': volume['mountpoint'], - 'instanceId': instance_id, + db.volume_detached(context) + return defer.succeed({'attachTime': volume_ref['attach_time'], + 'device': volume_ref['mountpoint'], + 'instanceId': instance_ref['str_id'], 'requestId': context.request_id, - 'status': volume['attach_status'], - 'volumeId': volume_id}) + 'status': volume_ref['attach_status'], + 'volumeId': volume_ref['id']}) def _convert_to_set(self, lst, label): if lst == None or lst == []: @@ -406,52 +360,55 @@ class CloudController(object): assert len(i) == 1 return i[0] - def _format_instances(self, context, reservation_id = None): + def _format_instances(self, context, reservation_id=None): reservations = {} - if context.user.is_admin(): - instgenerator = self.instdir.all + if reservation_id: + instances = db.instance_get_by_reservation(context, + reservation_id) else: - instgenerator = self.instdir.by_project(context.project.id) - for instance in instgenerator: - res_id = instance.get('reservation_id', 'Unknown') - if reservation_id != None and reservation_id != res_id: - continue + if not context.user.is_admin(): + instances = db.instance_get_all(context) + else: + instances = db.instance_get_by_project(context, + context.project.id) + for instance in instances: if not context.user.is_admin(): if instance['image_id'] == FLAGS.vpn_image_id: continue i = {} - i['instance_id'] = instance.get('instance_id', None) - i['image_id'] = instance.get('image_id', None) - i['instance_state'] = { - 'code': instance.get('state', 0), - 'name': instance.get('state_description', 'pending') + i['instanceId'] = instance['str_id'] + i['imageId'] = instance['image_id'] + i['instanceState'] = { + 'code': instance['state'], + 'name': instance['state_description'] } - i['public_dns_name'] = network_model.get_public_ip_for_instance( - i['instance_id']) - i['private_dns_name'] = instance.get('private_dns_name', None) - if not i['public_dns_name']: - i['public_dns_name'] = i['private_dns_name'] - i['dns_name'] = instance.get('dns_name', None) - i['key_name'] = instance.get('key_name', None) + fixed_addr = None + floating_addr = None + if instance['fixed_ip']: + fixed_addr = instance['fixed_ip']['str_id'] + if instance['fixed_ip']['floating_ips']: + fixed = instance['fixed_ip'] + floating_addr = fixed['floating_ips'][0]['str_id'] + i['privateDnsName'] = fixed_addr + i['publicDnsName'] = floating_addr + i['dnsName'] = i['publicDnsName'] or i['privateDnsName'] + i['keyName'] = instance['key_name'] if context.user.is_admin(): - i['key_name'] = '%s (%s, %s)' % (i['key_name'], - instance.get('project_id', None), - instance.get('node_name', '')) - i['product_codes_set'] = self._convert_to_set( - instance.get('product_codes', None), 'product_code') - i['instance_type'] = instance.get('instance_type', None) - i['launch_time'] = instance.get('launch_time', None) - i['ami_launch_index'] = instance.get('ami_launch_index', - None) - if not reservations.has_key(res_id): + i['keyName'] = '%s (%s, %s)' % (i['keyName'], + instance['project_id'], + instance['host']) + i['productCodesSet'] = self._convert_to_set([], 'product_codes') + i['instanceType'] = instance['instance_type'] + i['launchTime'] = instance['created_at'] + i['amiLaunchIndex'] = instance['launch_index'] + if not reservations.has_key(instance['reservation_id']): r = {} - r['reservation_id'] = res_id - r['owner_id'] = instance.get('project_id', None) - r['group_set'] = self._convert_to_set( - instance.get('groups', None), 'group_id') - r['instances_set'] = [] - reservations[res_id] = r - reservations[res_id]['instances_set'].append(i) + r['reservationId'] = instance['reservation_id'] + r['ownerId'] = instance['project_id'] + r['groupSet'] = self._convert_to_set([], 'groups') + r['instancesSet'] = [] + reservations[instance['reservation_id']] = r + reservations[instance['reservation_id']]['instancesSet'].append(i) return list(reservations.values()) @@ -461,20 +418,23 @@ class CloudController(object): def format_addresses(self, context): addresses = [] - for address in network_model.ElasticIp.all(): - # TODO(vish): implement a by_project iterator for addresses - if (context.user.is_admin() or - address['project_id'] == context.project.id): - address_rv = { - 'public_ip': address['address'], - 'instance_id': address.get('instance_id', 'free') - } - if context.user.is_admin(): - address_rv['instance_id'] = "%s (%s, %s)" % ( - address['instance_id'], - address['user_id'], - address['project_id'], - ) + if context.user.is_admin(): + iterator = db.floating_ip_get_all(context) + else: + iterator = db.floating_ip_get_by_project(context, + context.project.id) + for floating_ip_ref in iterator: + address = floating_ip_ref['str_id'] + instance_id = None + if (floating_ip_ref['fixed_ip'] + and floating_ip_ref['fixed_ip']['instance']): + instance_id = floating_ip_ref['fixed_ip']['instance']['str_id'] + address_rv = {'public_ip': address, + 'instance_id': instance_id} + if context.user.is_admin(): + details = "%s (%s)" % (address_rv['instance_id'], + floating_ip_ref['project_id']) + address_rv['instance_id'] = details addresses.append(address_rv) return {'addressesSet': addresses} @@ -483,8 +443,8 @@ class CloudController(object): def allocate_address(self, context, **kwargs): network_topic = yield self._get_network_topic(context) public_ip = yield rpc.call(network_topic, - {"method": "allocate_elastic_ip", - "args": {"user_id": context.user.id, + {"method": "allocate_floating_ip", + "args": {"context": None, "project_id": context.project.id}}) defer.returnValue({'addressSet': [{'publicIp': public_ip}]}) @@ -492,56 +452,62 @@ class CloudController(object): @defer.inlineCallbacks def release_address(self, context, public_ip, **kwargs): # NOTE(vish): Should we make sure this works? + floating_ip_ref = db.floating_ip_get_by_address(context, public_ip) network_topic = yield self._get_network_topic(context) rpc.cast(network_topic, - {"method": "deallocate_elastic_ip", - "args": {"elastic_ip": public_ip}}) + {"method": "deallocate_floating_ip", + "args": {"context": None, + "floating_address": floating_ip_ref['str_id']}}) defer.returnValue({'releaseResponse': ["Address released."]}) @rbac.allow('netadmin') @defer.inlineCallbacks def associate_address(self, context, instance_id, public_ip, **kwargs): - instance = self._get_instance(context, instance_id) - address = self._get_address(context, public_ip) + instance_ref = db.instance_get_by_str(context, instance_id) + fixed_ip_ref = db.fixed_ip_get_by_instance(context, instance_ref['id']) + floating_ip_ref = db.floating_ip_get_by_address(context, public_ip) network_topic = yield self._get_network_topic(context) rpc.cast(network_topic, - {"method": "associate_elastic_ip", - "args": {"elastic_ip": address['address'], - "fixed_ip": instance['private_dns_name'], - "instance_id": instance['instance_id']}}) + {"method": "associate_floating_ip", + "args": {"context": None, + "floating_address": floating_ip_ref['str_id'], + "fixed_address": fixed_ip_ref['str_id']}}) defer.returnValue({'associateResponse': ["Address associated."]}) @rbac.allow('netadmin') @defer.inlineCallbacks def disassociate_address(self, context, public_ip, **kwargs): - address = self._get_address(context, public_ip) + floating_ip_ref = db.floating_ip_get_by_address(context, public_ip) network_topic = yield self._get_network_topic(context) rpc.cast(network_topic, - {"method": "disassociate_elastic_ip", - "args": {"elastic_ip": address['address']}}) + {"method": "disassociate_floating_ip", + "args": {"context": None, + "floating_address": floating_ip_ref['str_id']}}) defer.returnValue({'disassociateResponse': ["Address disassociated."]}) @defer.inlineCallbacks def _get_network_topic(self, context): """Retrieves the network host for a project""" - host = network_service.get_host_for_project(context.project.id) + network_ref = db.project_get_network(context, context.project.id) + host = network_ref['host'] if not host: host = yield rpc.call(FLAGS.network_topic, - {"method": "set_network_host", - "args": {"user_id": context.user.id, - "project_id": context.project.id}}) - defer.returnValue('%s.%s' %(FLAGS.network_topic, host)) + {"method": "set_network_host", + "args": {"context": None, + "project_id": context.project.id}}) + defer.returnValue(db.queue_get_for(context, FLAGS.network_topic, host)) @rbac.allow('projectmanager', 'sysadmin') @defer.inlineCallbacks def run_instances(self, context, **kwargs): # make sure user can access the image # vpn image is private so it doesn't show up on lists - if kwargs['image_id'] != FLAGS.vpn_image_id: - image = self._get_image(context, kwargs['image_id']) + vpn = kwargs['image_id'] == FLAGS.vpn_image_id - # FIXME(ja): if image is cloudpipe, this breaks + if not vpn: + image = images.get(context, kwargs['image_id']) + # FIXME(ja): if image is vpn, this breaks # get defaults from imagestore image_id = image['imageId'] kernel_id = image.get('kernelId', FLAGS.default_kernel) @@ -552,11 +518,10 @@ class CloudController(object): ramdisk_id = kwargs.get('ramdisk_id', ramdisk_id) # make sure we have access to kernel and ramdisk - self._get_image(context, kernel_id) - self._get_image(context, ramdisk_id) + images.get(context, kernel_id) + images.get(context, ramdisk_id) logging.debug("Going to run instances...") - reservation_id = utils.generate_uid('r') launch_time = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) key_data = None if kwargs.has_key('key_name'): @@ -565,107 +530,122 @@ class CloudController(object): raise exception.ApiError('Key Pair %s not found' % kwargs['key_name']) key_data = key_pair.public_key - network_topic = yield self._get_network_topic(context) + # TODO: Get the real security group of launch in here security_group = "default" + + reservation_id = utils.generate_uid('r') + base_options = {} + base_options['image_id'] = image_id + base_options['kernel_id'] = kernel_id + base_options['ramdisk_id'] = ramdisk_id + base_options['reservation_id'] = reservation_id + base_options['key_data'] = key_data + base_options['key_name'] = kwargs.get('key_name', None) + base_options['user_id'] = context.user.id + base_options['project_id'] = context.project.id + base_options['user_data'] = kwargs.get('user_data', '') + base_options['instance_type'] = kwargs.get('instance_type', 'm1.small') + base_options['security_group'] = security_group + for num in range(int(kwargs['max_count'])): - is_vpn = False - if image_id == FLAGS.vpn_image_id: - is_vpn = True - inst = self.instdir.new() - allocate_data = yield rpc.call(network_topic, - {"method": "allocate_fixed_ip", - "args": {"user_id": context.user.id, - "project_id": context.project.id, - "security_group": security_group, - "is_vpn": is_vpn, - "hostname": inst.instance_id}}) - inst['image_id'] = image_id - inst['kernel_id'] = kernel_id - inst['ramdisk_id'] = ramdisk_id - inst['user_data'] = kwargs.get('user_data', '') - inst['instance_type'] = kwargs.get('instance_type', 'm1.small') - inst['reservation_id'] = reservation_id - inst['launch_time'] = launch_time - inst['key_data'] = key_data or '' - inst['key_name'] = kwargs.get('key_name', '') - inst['user_id'] = context.user.id - inst['project_id'] = context.project.id - inst['ami_launch_index'] = num - inst['security_group'] = security_group - inst['hostname'] = inst.instance_id - for (key, value) in allocate_data.iteritems(): - inst[key] = value - - inst.save() + instance_ref = db.instance_create(context, base_options) + inst_id = instance_ref['id'] + + inst = {} + inst['mac_address'] = utils.generate_mac() + inst['launch_index'] = num + inst['hostname'] = instance_ref['str_id'] + db.instance_update(context, inst_id, inst) + address = self.network_manager.allocate_fixed_ip(context, + inst_id, + vpn) + + # TODO(vish): This probably should be done in the scheduler + # network is setup when host is assigned + network_topic = yield self._get_network_topic(context) + rpc.call(network_topic, + {"method": "setup_fixed_ip", + "args": {"context": None, + "address": address}}) + rpc.cast(FLAGS.compute_topic, {"method": "run_instance", - "args": {"instance_id": inst.instance_id}}) - logging.debug("Casting to node for %s's instance with IP of %s" % - (context.user.name, inst['private_dns_name'])) - # TODO: Make Network figure out the network name from ip. - defer.returnValue(self._format_run_instances(context, reservation_id)) + "args": {"context": None, + "instance_id": inst_id}}) + logging.debug("Casting to node for %s/%s's instance %s" % + (context.project.name, context.user.name, inst_id)) + defer.returnValue(self._format_run_instances(context, + reservation_id)) + @rbac.allow('projectmanager', 'sysadmin') @defer.inlineCallbacks def terminate_instances(self, context, instance_id, **kwargs): logging.debug("Going to start terminating instances") - network_topic = yield self._get_network_topic(context) - for i in instance_id: - logging.debug("Going to try and terminate %s" % i) + for id_str in instance_id: + logging.debug("Going to try and terminate %s" % id_str) try: - instance = self._get_instance(context, i) + instance_ref = db.instance_get_by_str(context, id_str) except exception.NotFound: logging.warning("Instance %s was not found during terminate" - % i) + % id_str) continue - elastic_ip = network_model.get_public_ip_for_instance(i) - if elastic_ip: - logging.debug("Disassociating address %s" % elastic_ip) - # NOTE(vish): Right now we don't really care if the ip is - # disassociated. We may need to worry about - # checking this later. Perhaps in the scheduler? - rpc.cast(network_topic, - {"method": "disassociate_elastic_ip", - "args": {"elastic_ip": elastic_ip}}) - fixed_ip = instance.get('private_dns_name', None) - if fixed_ip: - logging.debug("Deallocating address %s" % fixed_ip) + # FIXME(ja): where should network deallocate occur? + address = db.instance_get_floating_address(context, + instance_ref['id']) + if address: + logging.debug("Disassociating address %s" % address) # NOTE(vish): Right now we don't really care if the ip is - # actually removed. We may need to worry about + # disassociated. We may need to worry about # checking this later. Perhaps in the scheduler? + network_topic = yield self._get_network_topic(context) rpc.cast(network_topic, - {"method": "deallocate_fixed_ip", - "args": {"fixed_ip": fixed_ip}}) - - if instance.get('node_name', 'unassigned') != 'unassigned': - # NOTE(joshua?): It's also internal default - rpc.cast('%s.%s' % (FLAGS.compute_topic, instance['node_name']), + {"method": "disassociate_floating_ip", + "args": {"context": None, + "address": address}}) + + address = db.instance_get_fixed_address(context, + instance_ref['id']) + if address: + logging.debug("Deallocating address %s" % address) + # NOTE(vish): Currently, nothing needs to be done on the + # network node until release. If this changes, + # we will need to cast here. + self.network.deallocate_fixed_ip(context, address) + + host = instance_ref['host'] + if host: + rpc.cast(db.queue_get_for(context, FLAGS.compute_topic, host), {"method": "terminate_instance", - "args": {"instance_id": i}}) + "args": {"context": None, + "instance_id": instance_ref['id']}}) else: - instance.destroy() + db.instance_destroy(context, instance_ref['id']) defer.returnValue(True) @rbac.allow('projectmanager', 'sysadmin') def reboot_instances(self, context, instance_id, **kwargs): """instance_id is a list of instance ids""" - for i in instance_id: - instance = self._get_instance(context, i) - rpc.cast('%s.%s' % (FLAGS.compute_topic, instance['node_name']), - {"method": "reboot_instance", - "args": {"instance_id": i}}) + for id_str in instance_id: + instance_ref = db.instance_get_by_str(context, id_str) + host = instance_ref['host'] + rpc.cast(db.queue_get_for(context, FLAGS.compute_topic, host), + {"method": "reboot_instance", + "args": {"context": None, + "instance_id": instance_ref['id']}}) return defer.succeed(True) @rbac.allow('projectmanager', 'sysadmin') def delete_volume(self, context, volume_id, **kwargs): # TODO: return error if not authorized - volume = self._get_volume(context, volume_id) - volume_node = volume['node_name'] - rpc.cast('%s.%s' % (FLAGS.volume_topic, volume_node), + volume_ref = db.volume_get_by_str(context, volume_id) + host = volume_ref['host'] + rpc.cast(db.queue_get_for(context, FLAGS.volume_topic, host), {"method": "delete_volume", - "args": {"volume_id": volume_id}}) + "args": {"context": None, + "volume_id": volume_ref['id']}}) return defer.succeed(True) @rbac.allow('all') @@ -716,23 +696,3 @@ class CloudController(object): raise exception.ApiError('operation_type must be add or remove') result = images.modify(context, image_id, operation_type) return defer.succeed(result) - - def update_state(self, topic, value): - """ accepts status reports from the queue and consolidates them """ - # TODO(jmc): if an instance has disappeared from - # the node, call instance_death - if topic == "instances": - return defer.succeed(True) - aggregate_state = getattr(self, topic) - node_name = value.keys()[0] - items = value[node_name] - - logging.debug("Updating %s state for %s" % (topic, node_name)) - - for item_id in items.keys(): - if (aggregate_state.has_key('pending') and - aggregate_state['pending'].has_key(item_id)): - del aggregate_state['pending'][item_id] - aggregate_state[node_name] = items - - return defer.succeed(True) diff --git a/nova/endpoint/images.py b/nova/endpoint/images.py index 2a88d66af..4579cd81a 100644 --- a/nova/endpoint/images.py +++ b/nova/endpoint/images.py @@ -18,7 +18,7 @@ """ Proxy AMI-related calls from the cloud controller, to the running -objectstore daemon. +objectstore service. """ import json @@ -26,6 +26,7 @@ import urllib import boto.s3.connection +from nova import exception from nova import flags from nova import utils from nova.auth import manager @@ -55,7 +56,6 @@ def register(context, image_location): return image_id - def list(context, filter_list=[]): """ return a list of all images that a user can see @@ -71,6 +71,14 @@ def list(context, filter_list=[]): return [i for i in result if i['imageId'] in filter_list] return result +def get(context, image_id): + """return a image object if the context has permissions""" + result = list(context, [image_id]) + if not result: + raise exception.NotFound('Image %s could not be found' % image_id) + image = result[0] + return image + def deregister(context, image_id): """ unregister an image """ diff --git a/nova/flags.py b/nova/flags.py index 2bca36f7e..7b0c95a3c 100644 --- a/nova/flags.py +++ b/nova/flags.py @@ -22,6 +22,7 @@ where they're used. """ import getopt +import os import socket import sys @@ -34,7 +35,7 @@ class FlagValues(gflags.FlagValues): Unknown flags will be ignored when parsing the command line, but the command line will be kept so that it can be replayed if new flags are defined after the initial parsing. - + """ def __init__(self): @@ -50,7 +51,7 @@ class FlagValues(gflags.FlagValues): # leftover args at the end sneaky_unparsed_args = {"value": None} original_argv = list(argv) - + if self.IsGnuGetOpt(): orig_getopt = getattr(getopt, 'gnu_getopt') orig_name = 'gnu_getopt' @@ -74,14 +75,14 @@ class FlagValues(gflags.FlagValues): unparsed_args = sneaky_unparsed_args['value'] if unparsed_args: if self.IsGnuGetOpt(): - args = argv[:1] + unparsed + args = argv[:1] + unparsed_args else: args = argv[:1] + original_argv[-len(unparsed_args):] else: args = argv[:1] finally: setattr(getopt, orig_name, orig_getopt) - + # Store the arguments for later, we'll need them for new flags # added at runtime self.__dict__['__stored_argv'] = original_argv @@ -92,7 +93,7 @@ class FlagValues(gflags.FlagValues): def SetDirty(self, name): """Mark a flag as dirty so that accessing it will case a reparse.""" self.__dict__['__dirty'].append(name) - + def IsDirty(self, name): return name in self.__dict__['__dirty'] @@ -113,12 +114,12 @@ class FlagValues(gflags.FlagValues): for k in self.__dict__['__dirty']: setattr(self, k, getattr(new_flags, k)) self.ClearDirty() - + def __setitem__(self, name, flag): gflags.FlagValues.__setitem__(self, name, flag) if self.WasAlreadyParsed(): self.SetDirty(name) - + def __getitem__(self, name): if self.IsDirty(name): self.ParseNewFlags() @@ -202,9 +203,20 @@ DEFINE_string('vpn_key_suffix', DEFINE_integer('auth_token_ttl', 3600, 'Seconds for auth tokens to linger') +DEFINE_string('sql_connection', + 'sqlite:///%s/nova.sqlite' % os.path.abspath("./"), + 'connection string for sql database') + +DEFINE_string('compute_manager', 'nova.compute.manager.ComputeManager', + 'Manager for compute') +DEFINE_string('network_manager', 'nova.network.manager.VlanManager', + 'Manager for network') +DEFINE_string('volume_manager', 'nova.volume.manager.AOEManager', + 'Manager for volume') + +DEFINE_string('host', socket.gethostname(), + 'name of this node') + # UNUSED DEFINE_string('node_availability_zone', 'nova', 'availability zone of this node') -DEFINE_string('node_name', socket.gethostname(), - 'name of this node') - diff --git a/nova/network/exception.py b/nova/manager.py index 2a3f5ec14..e9aa50c56 100644 --- a/nova/network/exception.py +++ b/nova/manager.py @@ -15,34 +15,25 @@ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. - """ -Exceptions for network errors. +Base class for managers of different parts of the system """ -from nova import exception - - -class NoMoreAddresses(exception.Error): - """No More Addresses are available in the network""" - pass - - -class AddressNotAllocated(exception.Error): - """The specified address has not been allocated""" - pass - - -class AddressAlreadyAssociated(exception.Error): - """The specified address has already been associated""" - pass +from nova import utils +from nova import flags -class AddressNotAssociated(exception.Error): - """The specified address is not associated""" - pass +FLAGS = flags.FLAGS +flags.DEFINE_string('db_driver', 'nova.db.api', + 'driver to use for volume creation') -class NotValidNetworkSize(exception.Error): - """The network size is not valid""" - pass +class Manager(object): + """DB driver is injected in the init method""" + def __init__(self, host=None, db_driver=None): + if not host: + host = FLAGS.host + self.host = host + if not db_driver: + db_driver = FLAGS.db_driver + self.db = utils.import_object(db_driver) # pylint: disable-msg=C0103 diff --git a/nova/network/linux_net.py b/nova/network/linux_net.py index 9e5aabd97..41aeb5da7 100644 --- a/nova/network/linux_net.py +++ b/nova/network/linux_net.py @@ -23,6 +23,7 @@ import signal # TODO(ja): does the definition of network_path belong here? +from nova import db from nova import flags from nova import utils @@ -32,102 +33,108 @@ flags.DEFINE_string('dhcpbridge_flagfile', '/etc/nova/nova-dhcpbridge.conf', 'location of flagfile for dhcpbridge') - -def execute(cmd, addl_env=None): - """Wrapper around utils.execute for fake_network""" - if FLAGS.fake_network: - logging.debug("FAKE NET: %s", cmd) - return "fake", 0 - else: - return utils.execute(cmd, addl_env=addl_env) - - -def runthis(desc, cmd): - """Wrapper around utils.runthis for fake_network""" - if FLAGS.fake_network: - return execute(cmd) - else: - return utils.runthis(desc, cmd) - - -def device_exists(device): - """Check if ethernet device exists""" - (_out, err) = execute("ifconfig %s" % device) - return not err - - -def confirm_rule(cmd): - """Delete and re-add iptables rule""" - execute("sudo iptables --delete %s" % (cmd)) - execute("sudo iptables -I %s" % (cmd)) - - -def remove_rule(cmd): - """Remove iptables rule""" - execute("sudo iptables --delete %s" % (cmd)) - - -def bind_public_ip(public_ip, interface): - """Bind ip to an interface""" - runthis("Binding IP to interface: %s", - "sudo ip addr add %s dev %s" % (public_ip, interface)) - - -def unbind_public_ip(public_ip, interface): - """Unbind a public ip from an interface""" - runthis("Binding IP to interface: %s", - "sudo ip addr del %s dev %s" % (public_ip, interface)) - - -def vlan_create(net): - """Create a vlan on on a bridge device unless vlan already exists""" - if not device_exists("vlan%s" % net['vlan']): - logging.debug("Starting VLAN inteface for %s network", (net['vlan'])) - execute("sudo vconfig set_name_type VLAN_PLUS_VID_NO_PAD") - execute("sudo vconfig add %s %s" % (FLAGS.bridge_dev, net['vlan'])) - execute("sudo ifconfig vlan%s up" % (net['vlan'])) - - -def bridge_create(net): - """Create a bridge on a vlan unless it already exists""" - if not device_exists(net['bridge_name']): - logging.debug("Starting Bridge inteface for %s network", (net['vlan'])) - execute("sudo brctl addbr %s" % (net['bridge_name'])) - execute("sudo brctl setfd %s 0" % (net.bridge_name)) - # execute("sudo brctl setageing %s 10" % (net.bridge_name)) - execute("sudo brctl stp %s off" % (net['bridge_name'])) - execute("sudo brctl addif %s vlan%s" % (net['bridge_name'], - net['vlan'])) - if net.bridge_gets_ip: - execute("sudo ifconfig %s %s broadcast %s netmask %s up" % \ - (net['bridge_name'], net.gateway, net.broadcast, net.netmask)) - confirm_rule("FORWARD --in-interface %s -j ACCEPT" % - (net['bridge_name'])) +flags.DEFINE_string('networks_path', utils.abspath('../networks'), + 'Location to keep network config files') +flags.DEFINE_string('public_interface', 'vlan1', + 'Interface for public IP addresses') +flags.DEFINE_string('bridge_dev', 'eth0', + 'network device for bridges') + + +DEFAULT_PORTS = [("tcp", 80), ("tcp", 22), ("udp", 1194), ("tcp", 443)] + + +def bind_floating_ip(floating_ip): + """Bind ip to public interface""" + _execute("sudo ip addr add %s dev %s" % (floating_ip, + FLAGS.public_interface)) + + +def unbind_floating_ip(floating_ip): + """Unbind a public ip from public interface""" + _execute("sudo ip addr del %s dev %s" % (floating_ip, + FLAGS.public_interface)) + + +def ensure_vlan_forward(public_ip, port, private_ip): + """Sets up forwarding rules for vlan""" + _confirm_rule("FORWARD -d %s -p udp --dport 1194 -j ACCEPT" % private_ip) + _confirm_rule( + "PREROUTING -t nat -d %s -p udp --dport %s -j DNAT --to %s:1194" + % (public_ip, port, private_ip)) + + +def ensure_floating_forward(floating_ip, fixed_ip): + """Ensure floating ip forwarding rule""" + _confirm_rule("PREROUTING -t nat -d %s -j DNAT --to %s" + % (floating_ip, fixed_ip)) + _confirm_rule("POSTROUTING -t nat -s %s -j SNAT --to %s" + % (fixed_ip, floating_ip)) + # TODO(joshua): Get these from the secgroup datastore entries + _confirm_rule("FORWARD -d %s -p icmp -j ACCEPT" + % (fixed_ip)) + for (protocol, port) in DEFAULT_PORTS: + _confirm_rule( + "FORWARD -d %s -p %s --dport %s -j ACCEPT" + % (fixed_ip, protocol, port)) + + +def remove_floating_forward(floating_ip, fixed_ip): + """Remove forwarding for floating ip""" + _remove_rule("PREROUTING -t nat -d %s -j DNAT --to %s" + % (floating_ip, fixed_ip)) + _remove_rule("POSTROUTING -t nat -s %s -j SNAT --to %s" + % (fixed_ip, floating_ip)) + _remove_rule("FORWARD -d %s -p icmp -j ACCEPT" + % (fixed_ip)) + for (protocol, port) in DEFAULT_PORTS: + _remove_rule("FORWARD -d %s -p %s --dport %s -j ACCEPT" + % (fixed_ip, protocol, port)) + + +def ensure_vlan_bridge(vlan_num, bridge, net_attrs=None): + """Create a vlan and bridge unless they already exist""" + interface = ensure_vlan(vlan_num) + ensure_bridge(bridge, interface, net_attrs) + + +def ensure_vlan(vlan_num): + """Create a vlan unless it already exists""" + interface = "vlan%s" % vlan_num + if not _device_exists(interface): + logging.debug("Starting VLAN inteface %s", interface) + _execute("sudo vconfig set_name_type VLAN_PLUS_VID_NO_PAD") + _execute("sudo vconfig add %s %s" % (FLAGS.bridge_dev, vlan_num)) + _execute("sudo ifconfig %s up" % interface) + return interface + + +def ensure_bridge(bridge, interface, net_attrs=None): + """Create a bridge unless it already exists""" + if not _device_exists(bridge): + logging.debug("Starting Bridge inteface for %s", interface) + _execute("sudo brctl addbr %s" % bridge) + _execute("sudo brctl setfd %s 0" % bridge) + # _execute("sudo brctl setageing %s 10" % bridge) + _execute("sudo brctl stp %s off" % bridge) + _execute("sudo brctl addif %s %s" % (bridge, interface)) + if net_attrs: + _execute("sudo ifconfig %s %s broadcast %s netmask %s up" % \ + (bridge, + net_attrs['gateway'], + net_attrs['broadcast'], + net_attrs['netmask'])) + _confirm_rule("FORWARD --in-interface %s -j ACCEPT" % bridge) else: - execute("sudo ifconfig %s up" % net['bridge_name']) - - -def _dnsmasq_cmd(net): - """Builds dnsmasq command""" - cmd = ['sudo -E dnsmasq', - ' --strict-order', - ' --bind-interfaces', - ' --conf-file=', - ' --pid-file=%s' % dhcp_file(net['vlan'], 'pid'), - ' --listen-address=%s' % net.dhcp_listen_address, - ' --except-interface=lo', - ' --dhcp-range=%s,static,120s' % net.dhcp_range_start, - ' --dhcp-hostsfile=%s' % dhcp_file(net['vlan'], 'conf'), - ' --dhcp-script=%s' % bin_file('nova-dhcpbridge'), - ' --leasefile-ro'] - return ''.join(cmd) + _execute("sudo ifconfig %s up" % bridge) -def host_dhcp(address): - """Return a host string for an address object""" - return "%s,%s.novalocal,%s" % (address['mac'], - address['hostname'], - address.address) +def get_dhcp_hosts(context, network_id): + """Get a string containing a network's hosts config in dnsmasq format""" + hosts = [] + for fixed_ip in db.network_get_associated_fixed_ips(context, network_id): + hosts.append(_host_dhcp(fixed_ip['str_id'])) + return '\n'.join(hosts) # TODO(ja): if the system has restarted or pid numbers have wrapped @@ -135,17 +142,17 @@ def host_dhcp(address): # dnsmasq. As well, sending a HUP only reloads the hostfile, # so any configuration options (like dchp-range, vlan, ...) # aren't reloaded -def start_dnsmasq(network): +def update_dhcp(context, network_id): """(Re)starts a dnsmasq server for a given network if a dnsmasq instance is already running then send a HUP signal causing it to reload, otherwise spawn a new instance """ - with open(dhcp_file(network['vlan'], 'conf'), 'w') as f: - for address in network.assigned_objs: - f.write("%s\n" % host_dhcp(address)) + network_ref = db.network_get(context, network_id) + with open(_dhcp_file(network_ref['vlan'], 'conf'), 'w') as f: + f.write(get_dhcp_hosts(context, network_id)) - pid = dnsmasq_pid_for(network) + pid = _dnsmasq_pid_for(network_ref['vlan']) # if dnsmasq is already running, then tell it to reload if pid: @@ -159,13 +166,64 @@ def start_dnsmasq(network): # FLAGFILE and DNSMASQ_INTERFACE in env env = {'FLAGFILE': FLAGS.dhcpbridge_flagfile, - 'DNSMASQ_INTERFACE': network['bridge_name']} - execute(_dnsmasq_cmd(network), addl_env=env) + 'DNSMASQ_INTERFACE': network_ref['bridge']} + command = _dnsmasq_cmd(network_ref) + _execute(command, addl_env=env) + + +def _host_dhcp(address): + """Return a host string for an address""" + instance_ref = db.fixed_ip_get_instance(None, address) + return "%s,%s.novalocal,%s" % (instance_ref['mac_address'], + instance_ref['hostname'], + address) + + +def _execute(cmd, *args, **kwargs): + """Wrapper around utils._execute for fake_network""" + if FLAGS.fake_network: + logging.debug("FAKE NET: %s", cmd) + return "fake", 0 + else: + return utils.execute(cmd, *args, **kwargs) + + +def _device_exists(device): + """Check if ethernet device exists""" + (_out, err) = _execute("ifconfig %s" % device, check_exit_code=False) + return not err + + +def _confirm_rule(cmd): + """Delete and re-add iptables rule""" + _execute("sudo iptables --delete %s" % (cmd), check_exit_code=False) + _execute("sudo iptables -I %s" % (cmd)) + + +def _remove_rule(cmd): + """Remove iptables rule""" + _execute("sudo iptables --delete %s" % (cmd)) + + +def _dnsmasq_cmd(net): + """Builds dnsmasq command""" + cmd = ['sudo -E dnsmasq', + ' --strict-order', + ' --bind-interfaces', + ' --conf-file=', + ' --pid-file=%s' % _dhcp_file(net['vlan'], 'pid'), + ' --listen-address=%s' % net['gateway'], + ' --except-interface=lo', + ' --dhcp-range=%s,static,120s' % net['dhcp_start'], + ' --dhcp-hostsfile=%s' % _dhcp_file(net['vlan'], 'conf'), + ' --dhcp-script=%s' % _bin_file('nova-dhcpbridge'), + ' --leasefile-ro'] + return ''.join(cmd) -def stop_dnsmasq(network): +def _stop_dnsmasq(network): """Stops the dnsmasq instance for a given network""" - pid = dnsmasq_pid_for(network) + pid = _dnsmasq_pid_for(network) if pid: try: @@ -174,18 +232,18 @@ def stop_dnsmasq(network): logging.debug("Killing dnsmasq threw %s", exc) -def dhcp_file(vlan, kind): +def _dhcp_file(vlan, kind): """Return path to a pid, leases or conf file for a vlan""" return os.path.abspath("%s/nova-%s.%s" % (FLAGS.networks_path, vlan, kind)) -def bin_file(script): +def _bin_file(script): """Return the absolute path to scipt in the bin directory""" return os.path.abspath(os.path.join(__file__, "../../../bin", script)) -def dnsmasq_pid_for(network): +def _dnsmasq_pid_for(vlan): """Returns he pid for prior dnsmasq instance for a vlan Returns None if no pid file exists @@ -193,7 +251,7 @@ def dnsmasq_pid_for(network): If machine has rebooted pid might be incorrect (caller should check) """ - pid_file = dhcp_file(network['vlan'], 'pid') + pid_file = _dhcp_file(vlan, 'pid') if os.path.exists(pid_file): with open(pid_file, 'r') as f: diff --git a/nova/network/manager.py b/nova/network/manager.py new file mode 100644 index 000000000..7a3bcfc2f --- /dev/null +++ b/nova/network/manager.py @@ -0,0 +1,365 @@ +# 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. + +""" +Network Hosts are responsible for allocating ips and setting up network +""" + +import logging +import math + +import IPy + +from nova import db +from nova import exception +from nova import flags +from nova import manager +from nova import utils + + +FLAGS = flags.FLAGS +flags.DEFINE_string('flat_network_bridge', 'br100', + 'Bridge for simple network instances') +flags.DEFINE_list('flat_network_ips', + ['192.168.0.2', '192.168.0.3', '192.168.0.4'], + 'Available ips for simple network') +flags.DEFINE_string('flat_network_network', '192.168.0.0', + 'Network for simple network') +flags.DEFINE_string('flat_network_netmask', '255.255.255.0', + 'Netmask for simple network') +flags.DEFINE_string('flat_network_gateway', '192.168.0.1', + 'Broadcast for simple network') +flags.DEFINE_string('flat_network_broadcast', '192.168.0.255', + 'Broadcast for simple network') +flags.DEFINE_string('flat_network_dns', '8.8.4.4', + 'Dns for simple network') +flags.DEFINE_integer('vlan_start', 100, 'First VLAN for private networks') +flags.DEFINE_integer('num_networks', 1000, 'Number of networks to support') +flags.DEFINE_string('vpn_ip', utils.get_my_ip(), + 'Public IP for the cloudpipe VPN servers') +flags.DEFINE_integer('vpn_start', 1000, 'First Vpn port for private networks') +flags.DEFINE_integer('network_size', 256, + 'Number of addresses in each private subnet') +flags.DEFINE_string('public_range', '4.4.4.0/24', 'Public IP address block') +flags.DEFINE_string('private_range', '10.0.0.0/8', 'Private IP address block') +flags.DEFINE_integer('cnt_vpn_clients', 5, + 'Number of addresses reserved for vpn clients') +flags.DEFINE_string('network_driver', 'nova.network.linux_net', + 'Driver to use for network creation') +flags.DEFINE_bool('update_dhcp_on_disassociate', False, + 'Whether to update dhcp when fixed_ip is disassocated') + + +class AddressAlreadyAllocated(exception.Error): + """Address was already allocated""" + pass + + +class NetworkManager(manager.Manager): + """Implements common network manager functionality + + This class must be subclassed. + """ + def __init__(self, network_driver=None, *args, **kwargs): + if not network_driver: + network_driver = FLAGS.network_driver + self.driver = utils.import_object(network_driver) + super(NetworkManager, self).__init__(*args, **kwargs) + + def set_network_host(self, context, project_id): + """Safely sets the host of the projects network""" + logging.debug("setting network host") + network_ref = self.db.project_get_network(context, project_id) + # TODO(vish): can we minimize db access by just getting the + # id here instead of the ref? + network_id = network_ref['id'] + host = self.db.network_set_host(context, + network_id, + FLAGS.host) + self._on_set_network_host(context, network_id) + return host + + def allocate_fixed_ip(self, context, instance_id, *args, **kwargs): + """Gets a fixed ip from the pool""" + raise NotImplementedError() + + def deallocate_fixed_ip(self, context, instance_id, *args, **kwargs): + """Returns a fixed ip to the pool""" + raise NotImplementedError() + + def setup_fixed_ip(self, context, address): + """Sets up rules for fixed ip""" + raise NotImplementedError() + + def _on_set_network_host(self, context, network_id): + """Called when this host becomes the host for a project""" + raise NotImplementedError() + + def setup_compute_network(self, context, project_id): + """Sets up matching network for compute hosts""" + raise NotImplementedError() + + def allocate_floating_ip(self, context, project_id): + """Gets an floating ip from the pool""" + # TODO(vish): add floating ips through manage command + return self.db.floating_ip_allocate_address(context, + FLAGS.host, + project_id) + + def associate_floating_ip(self, context, floating_address, fixed_address): + """Associates an floating ip to a fixed ip""" + self.db.floating_ip_fixed_ip_associate(context, + floating_address, + fixed_address) + self.driver.bind_floating_ip(floating_address) + self.driver.ensure_floating_forward(floating_address, fixed_address) + + def disassociate_floating_ip(self, context, floating_address): + """Disassociates a floating ip""" + fixed_address = self.db.floating_ip_disassociate(context, + floating_address) + self.driver.unbind_floating_ip(floating_address) + self.driver.remove_floating_forward(floating_address, fixed_address) + + def deallocate_floating_ip(self, context, floating_address): + """Returns an floating ip to the pool""" + self.db.floating_ip_deallocate(context, floating_address) + + @property + def _bottom_reserved_ips(self): # pylint: disable-msg=R0201 + """Number of reserved ips at the bottom of the range""" + return 2 # network, gateway + + @property + def _top_reserved_ips(self): # pylint: disable-msg=R0201 + """Number of reserved ips at the top of the range""" + return 1 # broadcast + + def _create_fixed_ips(self, context, network_id): + """Create all fixed ips for network""" + network_ref = self.db.network_get(context, network_id) + # NOTE(vish): should these be properties of the network as opposed + # to properties of the manager class? + bottom_reserved = self._bottom_reserved_ips + top_reserved = self._top_reserved_ips + project_net = IPy.IP(network_ref['cidr']) + num_ips = len(project_net) + for index in range(num_ips): + address = str(project_net[index]) + if index < bottom_reserved or num_ips - index < top_reserved: + reserved = True + else: + reserved = False + self.db.fixed_ip_create(context, {'network_id': network_id, + 'address': address, + 'reserved': reserved}) + + +class FlatManager(NetworkManager): + """Basic network where no vlans are used""" + + def allocate_fixed_ip(self, context, instance_id, *args, **kwargs): + """Gets a fixed ip from the pool""" + network_ref = self.db.project_get_network(context, context.project.id) + address = self.db.fixed_ip_associate_pool(context, + network_ref['id'], + instance_id) + self.db.fixed_ip_update(context, address, {'allocated': True}) + return address + + def deallocate_fixed_ip(self, context, address, *args, **kwargs): + """Returns a fixed ip to the pool""" + self.db.fixed_ip_update(context, address, {'allocated': False}) + self.db.fixed_ip_disassociate(context, address) + + def setup_compute_network(self, context, project_id): + """Network is created manually""" + pass + + def setup_fixed_ip(self, context, address): + """Currently no setup""" + pass + + def _on_set_network_host(self, context, network_id): + """Called when this host becomes the host for a project""" + # NOTE(vish): should there be two types of network objects + # in the datastore? + net = {} + net['injected'] = True + net['network_str'] = FLAGS.flat_network_network + net['netmask'] = FLAGS.flat_network_netmask + net['bridge'] = FLAGS.flat_network_bridge + net['gateway'] = FLAGS.flat_network_gateway + net['broadcast'] = FLAGS.flat_network_broadcast + net['dns'] = FLAGS.flat_network_dns + self.db.network_update(context, network_id, net) + # NOTE(vish): Rignt now we are putting all of the fixed ips in + # one large pool, but ultimately it may be better to + # have each network manager have its own network that + # it is responsible for and its own pool of ips. + for address in FLAGS.flat_network_ips: + self.db.fixed_ip_create(context, {'address': address}) + + +class VlanManager(NetworkManager): + """Vlan network with dhcp""" + def allocate_fixed_ip(self, context, instance_id, *args, **kwargs): + """Gets a fixed ip from the pool""" + network_ref = self.db.project_get_network(context, context.project.id) + if kwargs.get('vpn', None): + address = network_ref['vpn_private_address'] + self.db.fixed_ip_associate(context, address, instance_id) + else: + address = self.db.fixed_ip_associate_pool(context, + network_ref['id'], + instance_id) + self.db.fixed_ip_update(context, address, {'allocated': True}) + return address + + def deallocate_fixed_ip(self, context, address, *args, **kwargs): + """Returns a fixed ip to the pool""" + self.db.fixed_ip_update(context, address, {'allocated': False}) + fixed_ip_ref = self.db.fixed_ip_get_by_address(context, address) + if not fixed_ip_ref['leased']: + self.db.fixed_ip_disassociate(context, address) + # NOTE(vish): dhcp server isn't updated until next setup, this + # means there will stale entries in the conf file + # the code below will update the file if necessary + if FLAGS.update_dhcp_on_disassociate: + network_ref = self.db.fixed_ip_get_network(context, address) + self.driver.update_dhcp(context, network_ref['id']) + + + def setup_fixed_ip(self, context, address): + """Sets forwarding rules and dhcp for fixed ip""" + fixed_ip_ref = self.db.fixed_ip_get_by_address(context, address) + network_ref = self.db.fixed_ip_get_network(context, address) + if self.db.instance_is_vpn(context, fixed_ip_ref['instance_id']): + self.driver.ensure_vlan_forward(network_ref['vpn_public_address'], + network_ref['vpn_public_port'], + network_ref['vpn_private_address']) + self.driver.update_dhcp(context, network_ref['id']) + + def lease_fixed_ip(self, context, mac, address): + """Called by dhcp-bridge when ip is leased""" + logging.debug("Leasing IP %s", address) + fixed_ip_ref = self.db.fixed_ip_get_by_address(context, address) + if not fixed_ip_ref['allocated']: + logging.warn("IP %s leased that was already deallocated", address) + return + instance_ref = self.db.fixed_ip_get_instance(context, address) + if not instance_ref: + raise exception.Error("IP %s leased that isn't associated" % + address) + if instance_ref['mac_address'] != mac: + raise exception.Error("IP %s leased to bad mac %s vs %s" % + (address, instance_ref['mac_address'], mac)) + self.db.fixed_ip_update(context, + fixed_ip_ref['str_id'], + {'leased': True}) + + def release_fixed_ip(self, context, mac, address): + """Called by dhcp-bridge when ip is released""" + logging.debug("Releasing IP %s", address) + fixed_ip_ref = self.db.fixed_ip_get_by_address(context, address) + if not fixed_ip_ref['leased']: + logging.warn("IP %s released that was not leased", address) + return + instance_ref = self.db.fixed_ip_get_instance(context, address) + if not instance_ref: + raise exception.Error("IP %s released that isn't associated" % + address) + if instance_ref['mac_address'] != mac: + raise exception.Error("IP %s released from bad mac %s vs %s" % + (address, instance_ref['mac_address'], mac)) + self.db.fixed_ip_update(context, address, {'leased': False}) + if not fixed_ip_ref['allocated']: + self.db.fixed_ip_disassociate(context, address) + # NOTE(vish): dhcp server isn't updated until next setup, this + # means there will stale entries in the conf file + # the code below will update the file if necessary + if FLAGS.update_dhcp_on_disassociate: + network_ref = self.db.fixed_ip_get_network(context, address) + self.driver.update_dhcp(context, network_ref['id']) + + def allocate_network(self, context, project_id): + """Set up the network""" + self._ensure_indexes(context) + network_ref = db.network_create(context, {'project_id': project_id}) + network_id = network_ref['id'] + private_net = IPy.IP(FLAGS.private_range) + index = db.network_get_index(context, network_id) + vlan = FLAGS.vlan_start + index + start = index * FLAGS.network_size + significant_bits = 32 - int(math.log(FLAGS.network_size, 2)) + cidr = "%s/%s" % (private_net[start], significant_bits) + project_net = IPy.IP(cidr) + + net = {} + net['cidr'] = cidr + # NOTE(vish): we could turn these into properties + net['netmask'] = str(project_net.netmask()) + net['gateway'] = str(project_net[1]) + net['broadcast'] = str(project_net.broadcast()) + net['vpn_private_address'] = str(project_net[2]) + net['dhcp_start'] = str(project_net[3]) + net['vlan'] = vlan + net['bridge'] = 'br%s' % vlan + net['vpn_public_address'] = FLAGS.vpn_ip + net['vpn_public_port'] = FLAGS.vpn_start + index + db.network_update(context, network_id, net) + self._create_fixed_ips(context, network_id) + return network_id + + def setup_compute_network(self, context, project_id): + """Sets up matching network for compute hosts""" + network_ref = self.db.project_get_network(context, project_id) + self.driver.ensure_vlan_bridge(network_ref['vlan'], + network_ref['bridge']) + + def restart_nets(self): + """Ensure the network for each user is enabled""" + # TODO(vish): Implement this + pass + + def _ensure_indexes(self, context): + """Ensure the indexes for the network exist + + This could use a manage command instead of keying off of a flag""" + if not self.db.network_index_count(context): + for index in range(FLAGS.num_networks): + self.db.network_index_create(context, {'index': index}) + + def _on_set_network_host(self, context, network_id): + """Called when this host becomes the host for a project""" + network_ref = self.db.network_get(context, network_id) + self.driver.ensure_vlan_bridge(network_ref['vlan'], + network_ref['bridge'], + network_ref) + + @property + def _bottom_reserved_ips(self): + """Number of reserved ips at the bottom of the range""" + return super(VlanManager, self)._bottom_reserved_ips + 1 # vpn server + + @property + def _top_reserved_ips(self): + """Number of reserved ips at the top of the range""" + parent_reserved = super(VlanManager, self)._top_reserved_ips + return parent_reserved + FLAGS.cnt_vpn_clients + diff --git a/nova/network/model.py b/nova/network/model.py deleted file mode 100644 index 557fc92a6..000000000 --- a/nova/network/model.py +++ /dev/null @@ -1,642 +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. - -""" -Model Classes for network control, including VLANs, DHCP, and IP allocation. -""" - -import logging -import os -import time - -import IPy -from nova import datastore -from nova import exception as nova_exception -from nova import flags -from nova import utils -from nova.auth import manager -from nova.network import exception -from nova.network import linux_net - - -FLAGS = flags.FLAGS -flags.DEFINE_string('networks_path', utils.abspath('../networks'), - 'Location to keep network config files') -flags.DEFINE_integer('public_vlan', 1, 'VLAN for public IP addresses') -flags.DEFINE_string('public_interface', 'vlan1', - 'Interface for public IP addresses') -flags.DEFINE_string('bridge_dev', 'eth1', - 'network device for bridges') -flags.DEFINE_integer('vlan_start', 100, 'First VLAN for private networks') -flags.DEFINE_integer('vlan_end', 4093, 'Last VLAN for private networks') -flags.DEFINE_integer('network_size', 256, - 'Number of addresses in each private subnet') -flags.DEFINE_string('public_range', '4.4.4.0/24', 'Public IP address block') -flags.DEFINE_string('private_range', '10.0.0.0/8', 'Private IP address block') -flags.DEFINE_integer('cnt_vpn_clients', 5, - 'Number of addresses reserved for vpn clients') -flags.DEFINE_integer('cloudpipe_start_port', 12000, - 'Starting port for mapped CloudPipe external ports') - - -logging.getLogger().setLevel(logging.DEBUG) - - -class Vlan(datastore.BasicModel): - """Tracks vlans assigned to project it the datastore""" - def __init__(self, project, vlan): # pylint: disable-msg=W0231 - """ - Since we don't want to try and find a vlan by its identifier, - but by a project id, we don't call super-init. - """ - self.project_id = project - self.vlan_id = vlan - - @property - def identifier(self): - """Datastore identifier""" - return "%s:%s" % (self.project_id, self.vlan_id) - - @classmethod - def create(cls, project, vlan): - """Create a Vlan object""" - instance = cls(project, vlan) - instance.save() - return instance - - @classmethod - @datastore.absorb_connection_error - def lookup(cls, project): - """Returns object by project if it exists in datastore or None""" - set_name = cls._redis_set_name(cls.__name__) - vlan = datastore.Redis.instance().hget(set_name, project) - if vlan: - return cls(project, vlan) - else: - return None - - @classmethod - @datastore.absorb_connection_error - def dict_by_project(cls): - """A hash of project:vlan""" - set_name = cls._redis_set_name(cls.__name__) - return datastore.Redis.instance().hgetall(set_name) or {} - - @classmethod - @datastore.absorb_connection_error - def dict_by_vlan(cls): - """A hash of vlan:project""" - set_name = cls._redis_set_name(cls.__name__) - retvals = {} - hashset = datastore.Redis.instance().hgetall(set_name) or {} - for (key, val) in hashset.iteritems(): - retvals[val] = key - return retvals - - @classmethod - @datastore.absorb_connection_error - def all(cls): - set_name = cls._redis_set_name(cls.__name__) - elements = datastore.Redis.instance().hgetall(set_name) - for project in elements: - yield cls(project, elements[project]) - - @datastore.absorb_connection_error - def save(self): - """ - Vlan saves state into a giant hash named "vlans", with keys of - project_id and value of vlan number. Therefore, we skip the - default way of saving into "vlan:ID" and adding to a set of "vlans". - """ - set_name = self._redis_set_name(self.__class__.__name__) - datastore.Redis.instance().hset(set_name, - self.project_id, - self.vlan_id) - - @datastore.absorb_connection_error - def destroy(self): - """Removes the object from the datastore""" - set_name = self._redis_set_name(self.__class__.__name__) - datastore.Redis.instance().hdel(set_name, self.project_id) - - def subnet(self): - """Returns a string containing the subnet""" - vlan = int(self.vlan_id) - network = IPy.IP(FLAGS.private_range) - start = (vlan - FLAGS.vlan_start) * FLAGS.network_size - # minus one for the gateway. - return "%s-%s" % (network[start], - network[start + FLAGS.network_size - 1]) - - -class FixedIp(datastore.BasicModel): - """Represents a fixed ip in the datastore""" - - def __init__(self, address): - self.address = address - super(FixedIp, self).__init__() - - @property - def identifier(self): - return self.address - - # NOTE(vish): address states allocated, leased, deallocated - def default_state(self): - return {'address': self.address, - 'state': 'none'} - - @classmethod - # pylint: disable-msg=R0913 - def create(cls, user_id, project_id, address, mac, hostname, network_id): - """Creates an FixedIp object""" - addr = cls(address) - addr['user_id'] = user_id - addr['project_id'] = project_id - addr['mac'] = mac - if hostname is None: - hostname = "ip-%s" % address.replace('.', '-') - addr['hostname'] = hostname - addr['network_id'] = network_id - addr['state'] = 'allocated' - addr.save() - return addr - - def save(self): - is_new = self.is_new_record() - success = super(FixedIp, self).save() - if success and is_new: - self.associate_with("network", self['network_id']) - - def destroy(self): - self.unassociate_with("network", self['network_id']) - super(FixedIp, self).destroy() - - -class ElasticIp(FixedIp): - """Represents an elastic ip in the datastore""" - override_type = "address" - - def default_state(self): - return {'address': self.address, - 'instance_id': 'available', - 'private_ip': 'available'} - - -# CLEANUP: -# TODO(ja): does vlanpool "keeper" need to know the min/max - -# shouldn't FLAGS always win? -class BaseNetwork(datastore.BasicModel): - """Implements basic logic for allocating ips in a network""" - override_type = 'network' - address_class = FixedIp - - @property - def identifier(self): - """Datastore identifier""" - return self.network_id - - def default_state(self): - """Default values for new objects""" - return {'network_id': self.network_id, 'network_str': self.network_str} - - @classmethod - # pylint: disable-msg=R0913 - def create(cls, user_id, project_id, security_group, vlan, network_str): - """Create a BaseNetwork object""" - network_id = "%s:%s" % (project_id, security_group) - net = cls(network_id, network_str) - net['user_id'] = user_id - net['project_id'] = project_id - net["vlan"] = vlan - net["bridge_name"] = "br%s" % vlan - net.save() - return net - - def __init__(self, network_id, network_str=None): - self.network_id = network_id - self.network_str = network_str - super(BaseNetwork, self).__init__() - if self.is_new_record(): - self._create_assigned_set() - - @property - def network(self): - """Returns a string representing the network""" - return IPy.IP(self['network_str']) - - @property - def netmask(self): - """Returns the netmask of this network""" - return self.network.netmask() - - @property - def gateway(self): - """Returns the network gateway address""" - return self.network[1] - - @property - def broadcast(self): - """Returns the network broadcast address""" - return self.network.broadcast() - - @property - def bridge_name(self): - """Returns the bridge associated with this network""" - return "br%s" % (self["vlan"]) - - @property - def user(self): - """Returns the user associated with this network""" - return manager.AuthManager().get_user(self['user_id']) - - @property - def project(self): - """Returns the project associated with this network""" - return manager.AuthManager().get_project(self['project_id']) - - # pylint: disable-msg=R0913 - def _add_host(self, user_id, project_id, ip_address, mac, hostname): - """Add a host to the datastore""" - self.address_class.create(user_id, project_id, ip_address, - mac, hostname, self.identifier) - - def _rem_host(self, ip_address): - """Remove a host from the datastore""" - self.address_class(ip_address).destroy() - - def _create_assigned_set(self): - for idx in range(self.num_bottom_reserved_ips, - len(self.network) - self.num_top_reserved_ips): - redis = datastore.Redis.instance() - redis.sadd(self._available_key, str(self.network[idx])) - - @property - def _available_key(self): - return 'available:%s' % self.identifier - - @property - def num_available_ips(self): - redis = datastore.Redis.instance() - return redis.scard(self._available_key) - - @property - def assigned(self): - """Returns a list of all assigned addresses""" - return self.address_class.associated_keys('network', self.identifier) - - @property - def assigned_objs(self): - """Returns a list of all assigned addresses as objects""" - return self.address_class.associated_to('network', self.identifier) - - def get_address(self, ip_address): - """Returns a specific ip as an object""" - if ip_address in self.assigned: - return self.address_class(ip_address) - return None - - @property - def num_bottom_reserved_ips(self): - """Returns number of ips reserved at the bottom of the range""" - return 2 # Network, Gateway - - @property - def num_top_reserved_ips(self): - """Returns number of ips reserved at the top of the range""" - return 1 # Broadcast - - def allocate_ip(self, user_id, project_id, mac, hostname=None): - """Allocates an ip to a mac address""" - address = datastore.Redis.instance().spop(self._available_key) - if not address: - raise exception.NoMoreAddresses("Project %s with network %s" % - (project_id, str(self.network))) - logging.debug("Allocating IP %s to %s", address, project_id) - self._add_host(user_id, project_id, address, mac, hostname) - self.express(address=address) - return address - - def lease_ip(self, ip_str): - """Called when DHCP lease is activated""" - if not ip_str in self.assigned: - raise exception.AddressNotAllocated() - address = self.get_address(ip_str) - if address: - logging.debug("Leasing allocated IP %s", ip_str) - address['state'] = 'leased' - address.save() - - def release_ip(self, ip_str): - """Called when DHCP lease expires - - Removes the ip from the assigned list""" - if not ip_str in self.assigned: - raise exception.AddressNotAllocated() - logging.debug("Releasing IP %s", ip_str) - self._rem_host(ip_str) - self.deexpress(address=ip_str) - datastore.Redis.instance().sadd(self._available_key, ip_str) - - def deallocate_ip(self, ip_str): - """Deallocates an allocated ip""" - if not ip_str in self.assigned: - raise exception.AddressNotAllocated() - address = self.get_address(ip_str) - if address: - if address['state'] != 'leased': - # NOTE(vish): address hasn't been leased, so release it - self.release_ip(ip_str) - else: - logging.debug("Deallocating allocated IP %s", ip_str) - address['state'] == 'deallocated' - address.save() - - def express(self, address=None): - """Set up network. Implemented in subclasses""" - pass - - def deexpress(self, address=None): - """Tear down network. Implemented in subclasses""" - pass - - -class BridgedNetwork(BaseNetwork): - """ - Virtual Network that can express itself to create a vlan and - a bridge (with or without an IP address/netmask/gateway) - - properties: - bridge_name - string (example value: br42) - vlan - integer (example value: 42) - bridge_dev - string (example: eth0) - bridge_gets_ip - boolean used during bridge creation - - if bridge_gets_ip then network address for bridge uses the properties: - gateway - broadcast - netmask - """ - - bridge_gets_ip = False - override_type = 'network' - - @classmethod - def get_network_for_project(cls, - user_id, - project_id, - security_group='default'): - """Returns network for a given project""" - vlan = get_vlan_for_project(project_id) - network_str = vlan.subnet() - return cls.create(user_id, project_id, security_group, vlan.vlan_id, - network_str) - - def __init__(self, *args, **kwargs): - super(BridgedNetwork, self).__init__(*args, **kwargs) - self['bridge_dev'] = FLAGS.bridge_dev - - def express(self, address=None): - super(BridgedNetwork, self).express(address=address) - linux_net.vlan_create(self) - linux_net.bridge_create(self) - - -class DHCPNetwork(BridgedNetwork): - """Network supporting DHCP""" - bridge_gets_ip = True - override_type = 'network' - - def __init__(self, *args, **kwargs): - super(DHCPNetwork, self).__init__(*args, **kwargs) - if not(os.path.exists(FLAGS.networks_path)): - os.makedirs(FLAGS.networks_path) - - @property - def num_bottom_reserved_ips(self): - # For cloudpipe - return super(DHCPNetwork, self).num_bottom_reserved_ips + 1 - - @property - def num_top_reserved_ips(self): - return super(DHCPNetwork, self).num_top_reserved_ips + \ - FLAGS.cnt_vpn_clients - - @property - def dhcp_listen_address(self): - """Address where dhcp server should listen""" - return self.gateway - - @property - def dhcp_range_start(self): - """Starting address dhcp server should use""" - return self.network[self.num_bottom_reserved_ips] - - def express(self, address=None): - super(DHCPNetwork, self).express(address=address) - if len(self.assigned) > 0: - logging.debug("Starting dnsmasq server for network with vlan %s", - self['vlan']) - linux_net.start_dnsmasq(self) - else: - logging.debug("Not launching dnsmasq: no hosts.") - self.express_vpn() - - def allocate_vpn_ip(self, user_id, project_id, mac, hostname=None): - """Allocates the reserved ip to a vpn instance""" - address = str(self.network[2]) - self._add_host(user_id, project_id, address, mac, hostname) - self.express(address=address) - return address - - def express_vpn(self): - """Sets up routing rules for vpn""" - private_ip = str(self.network[2]) - linux_net.confirm_rule("FORWARD -d %s -p udp --dport 1194 -j ACCEPT" - % (private_ip, )) - linux_net.confirm_rule( - "PREROUTING -t nat -d %s -p udp --dport %s -j DNAT --to %s:1194" - % (self.project.vpn_ip, self.project.vpn_port, private_ip)) - - def deexpress(self, address=None): - # if this is the last address, stop dns - super(DHCPNetwork, self).deexpress(address=address) - if len(self.assigned) == 0: - linux_net.stop_dnsmasq(self) - else: - linux_net.start_dnsmasq(self) - -DEFAULT_PORTS = [("tcp", 80), ("tcp", 22), ("udp", 1194), ("tcp", 443)] - - -class PublicNetworkController(BaseNetwork): - """Handles elastic ips""" - override_type = 'network' - address_class = ElasticIp - - def __init__(self, *args, **kwargs): - network_id = "public:default" - super(PublicNetworkController, self).__init__(network_id, - FLAGS.public_range, *args, **kwargs) - self['user_id'] = "public" - self['project_id'] = "public" - self["create_time"] = time.strftime('%Y-%m-%dT%H:%M:%SZ', - time.gmtime()) - self["vlan"] = FLAGS.public_vlan - self.save() - self.express() - - def deallocate_ip(self, ip_str): - # NOTE(vish): cleanup is now done on release by the parent class - self.release_ip(ip_str) - - def associate_address(self, public_ip, private_ip, instance_id): - """Associates a public ip to a private ip and instance id""" - if not public_ip in self.assigned: - raise exception.AddressNotAllocated() - # TODO(josh): Keep an index going both ways - for addr in self.assigned_objs: - if addr.get('private_ip', None) == private_ip: - raise exception.AddressAlreadyAssociated() - addr = self.get_address(public_ip) - if addr.get('private_ip', 'available') != 'available': - raise exception.AddressAlreadyAssociated() - addr['private_ip'] = private_ip - addr['instance_id'] = instance_id - addr.save() - self.express(address=public_ip) - - def disassociate_address(self, public_ip): - """Disassociates a public ip with its private ip""" - if not public_ip in self.assigned: - raise exception.AddressNotAllocated() - addr = self.get_address(public_ip) - if addr.get('private_ip', 'available') == 'available': - raise exception.AddressNotAssociated() - self.deexpress(address=public_ip) - addr['private_ip'] = 'available' - addr['instance_id'] = 'available' - addr.save() - - def express(self, address=None): - if address: - if not address in self.assigned: - raise exception.AddressNotAllocated() - addresses = [self.get_address(address)] - else: - addresses = self.assigned_objs - for addr in addresses: - if addr.get('private_ip', 'available') == 'available': - continue - public_ip = addr['address'] - private_ip = addr['private_ip'] - linux_net.bind_public_ip(public_ip, FLAGS.public_interface) - linux_net.confirm_rule("PREROUTING -t nat -d %s -j DNAT --to %s" - % (public_ip, private_ip)) - linux_net.confirm_rule("POSTROUTING -t nat -s %s -j SNAT --to %s" - % (private_ip, public_ip)) - # TODO(joshua): Get these from the secgroup datastore entries - linux_net.confirm_rule("FORWARD -d %s -p icmp -j ACCEPT" - % (private_ip)) - for (protocol, port) in DEFAULT_PORTS: - linux_net.confirm_rule( - "FORWARD -d %s -p %s --dport %s -j ACCEPT" - % (private_ip, protocol, port)) - - def deexpress(self, address=None): - addr = self.get_address(address) - private_ip = addr['private_ip'] - linux_net.unbind_public_ip(address, FLAGS.public_interface) - linux_net.remove_rule("PREROUTING -t nat -d %s -j DNAT --to %s" - % (address, private_ip)) - linux_net.remove_rule("POSTROUTING -t nat -s %s -j SNAT --to %s" - % (private_ip, address)) - linux_net.remove_rule("FORWARD -d %s -p icmp -j ACCEPT" - % (private_ip)) - for (protocol, port) in DEFAULT_PORTS: - linux_net.remove_rule("FORWARD -d %s -p %s --dport %s -j ACCEPT" - % (private_ip, protocol, port)) - - -# FIXME(todd): does this present a race condition, or is there some -# piece of architecture that mitigates it (only one queue -# listener per net)? -def get_vlan_for_project(project_id): - """Allocate vlan IDs to individual users""" - vlan = Vlan.lookup(project_id) - if vlan: - return vlan - known_vlans = Vlan.dict_by_vlan() - for vnum in range(FLAGS.vlan_start, FLAGS.vlan_end): - vstr = str(vnum) - if not vstr in known_vlans: - return Vlan.create(project_id, vnum) - old_project_id = known_vlans[vstr] - if not manager.AuthManager().get_project(old_project_id): - vlan = Vlan.lookup(old_project_id) - if vlan: - # NOTE(todd): This doesn't check for vlan id match, because - # it seems to be assumed that vlan<=>project is - # always a 1:1 mapping. It could be made way - # sexier if it didn't fight against the way - # BasicModel worked and used associate_with - # to build connections to projects. - # NOTE(josh): This is here because we want to make sure we - # don't orphan any VLANs. It is basically - # garbage collection for after projects abandoned - # their reference. - vlan.destroy() - vlan.project_id = project_id - vlan.save() - return vlan - else: - return Vlan.create(project_id, vnum) - raise exception.AddressNotAllocated("Out of VLANs") - - -def get_project_network(project_id, security_group='default'): - """Gets a project's private network, allocating one if needed""" - project = manager.AuthManager().get_project(project_id) - if not project: - raise nova_exception.NotFound("Project %s doesn't exist." % project_id) - manager_id = project.project_manager_id - return DHCPNetwork.get_network_for_project(manager_id, - project.id, - security_group) - - -def get_network_by_address(address): - """Gets the network for a given private ip""" - address_record = FixedIp.lookup(address) - if not address_record: - raise exception.AddressNotAllocated() - return get_project_network(address_record['project_id']) - - -def get_network_by_interface(iface, security_group='default'): - """Gets the network for a given interface""" - vlan = iface.rpartition("br")[2] - project_id = Vlan.dict_by_vlan().get(vlan) - return get_project_network(project_id, security_group) - - -def get_public_ip_for_instance(instance_id): - """Gets the public ip for a given instance""" - # FIXME(josh): this should be a lookup - iteration won't scale - for address_record in ElasticIp.all(): - if address_record.get('instance_id', 'available') == instance_id: - return address_record['address'] diff --git a/nova/network/service.py b/nova/network/service.py deleted file mode 100644 index 3dba0a9ef..000000000 --- a/nova/network/service.py +++ /dev/null @@ -1,256 +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. - -""" -Network Hosts are responsible for allocating ips and setting up network -""" - -from nova import datastore -from nova import exception -from nova import flags -from nova import service -from nova import utils -from nova.auth import manager -from nova.network import exception as network_exception -from nova.network import model -from nova.network import vpn - - -FLAGS = flags.FLAGS -flags.DEFINE_string('network_type', - 'flat', - 'Service Class for Networking') -flags.DEFINE_string('flat_network_bridge', 'br100', - 'Bridge for simple network instances') -flags.DEFINE_list('flat_network_ips', - ['192.168.0.2', '192.168.0.3', '192.168.0.4'], - 'Available ips for simple network') -flags.DEFINE_string('flat_network_network', '192.168.0.0', - 'Network for simple network') -flags.DEFINE_string('flat_network_netmask', '255.255.255.0', - 'Netmask for simple network') -flags.DEFINE_string('flat_network_gateway', '192.168.0.1', - 'Broadcast for simple network') -flags.DEFINE_string('flat_network_broadcast', '192.168.0.255', - 'Broadcast for simple network') -flags.DEFINE_string('flat_network_dns', '8.8.4.4', - 'Dns for simple network') - - -def type_to_class(network_type): - """Convert a network_type string into an actual Python class""" - if network_type == 'flat': - return FlatNetworkService - elif network_type == 'vlan': - return VlanNetworkService - raise exception.NotFound("Couldn't find %s network type" % network_type) - - -def setup_compute_network(network_type, user_id, project_id, security_group): - """Sets up the network on a compute host""" - srv = type_to_class(network_type) - srv.setup_compute_network(user_id, - project_id, - security_group) - - -def get_host_for_project(project_id): - """Get host allocated to project from datastore""" - redis = datastore.Redis.instance() - return redis.get(_host_key(project_id)) - - -def _host_key(project_id): - """Returns redis host key for network""" - return "networkhost:%s" % project_id - - -class BaseNetworkService(service.Service): - """Implements common network service functionality - - This class must be subclassed. - """ - def __init__(self, *args, **kwargs): - self.network = model.PublicNetworkController() - super(BaseNetworkService, self).__init__(*args, **kwargs) - - def set_network_host(self, user_id, project_id, *args, **kwargs): - """Safely sets the host of the projects network""" - redis = datastore.Redis.instance() - key = _host_key(project_id) - if redis.setnx(key, FLAGS.node_name): - self._on_set_network_host(user_id, project_id, - security_group='default', - *args, **kwargs) - return FLAGS.node_name - else: - return redis.get(key) - - def allocate_fixed_ip(self, user_id, project_id, - security_group='default', - *args, **kwargs): - """Subclass implements getting fixed ip from the pool""" - raise NotImplementedError() - - def deallocate_fixed_ip(self, fixed_ip, *args, **kwargs): - """Subclass implements return of ip to the pool""" - raise NotImplementedError() - - def _on_set_network_host(self, user_id, project_id, - *args, **kwargs): - """Called when this host becomes the host for a project""" - pass - - @classmethod - def setup_compute_network(cls, user_id, project_id, security_group, - *args, **kwargs): - """Sets up matching network for compute hosts""" - raise NotImplementedError() - - def allocate_elastic_ip(self, user_id, project_id): - """Gets a elastic ip from the pool""" - # NOTE(vish): Replicating earlier decision to use 'public' as - # mac address name, although this should probably - # be done inside of the PublicNetworkController - return self.network.allocate_ip(user_id, project_id, 'public') - - def associate_elastic_ip(self, elastic_ip, fixed_ip, instance_id): - """Associates an elastic ip to a fixed ip""" - self.network.associate_address(elastic_ip, fixed_ip, instance_id) - - def disassociate_elastic_ip(self, elastic_ip): - """Disassociates a elastic ip""" - self.network.disassociate_address(elastic_ip) - - def deallocate_elastic_ip(self, elastic_ip): - """Returns a elastic ip to the pool""" - self.network.deallocate_ip(elastic_ip) - - -class FlatNetworkService(BaseNetworkService): - """Basic network where no vlans are used""" - - @classmethod - def setup_compute_network(cls, user_id, project_id, security_group, - *args, **kwargs): - """Network is created manually""" - pass - - def allocate_fixed_ip(self, - user_id, - project_id, - security_group='default', - *args, **kwargs): - """Gets a fixed ip from the pool - - Flat network just grabs the next available ip from the pool - """ - # NOTE(vish): Some automation could be done here. For example, - # creating the flat_network_bridge and setting up - # a gateway. This is all done manually atm. - redis = datastore.Redis.instance() - if not redis.exists('ips') and not len(redis.keys('instances:*')): - for fixed_ip in FLAGS.flat_network_ips: - redis.sadd('ips', fixed_ip) - fixed_ip = redis.spop('ips') - if not fixed_ip: - raise network_exception.NoMoreAddresses() - # TODO(vish): some sort of dns handling for hostname should - # probably be done here. - return {'inject_network': True, - 'network_type': FLAGS.network_type, - 'mac_address': utils.generate_mac(), - 'private_dns_name': str(fixed_ip), - 'bridge_name': FLAGS.flat_network_bridge, - 'network_network': FLAGS.flat_network_network, - 'network_netmask': FLAGS.flat_network_netmask, - 'network_gateway': FLAGS.flat_network_gateway, - 'network_broadcast': FLAGS.flat_network_broadcast, - 'network_dns': FLAGS.flat_network_dns} - - def deallocate_fixed_ip(self, fixed_ip, *args, **kwargs): - """Returns an ip to the pool""" - datastore.Redis.instance().sadd('ips', fixed_ip) - - -class VlanNetworkService(BaseNetworkService): - """Vlan network with dhcp""" - # NOTE(vish): A lot of the interactions with network/model.py can be - # simplified and improved. Also there it may be useful - # to support vlans separately from dhcp, instead of having - # both of them together in this class. - # pylint: disable-msg=W0221 - def allocate_fixed_ip(self, - user_id, - project_id, - security_group='default', - is_vpn=False, - hostname=None, - *args, **kwargs): - """Gets a fixed ip from the pool""" - mac = utils.generate_mac() - net = model.get_project_network(project_id) - if is_vpn: - fixed_ip = net.allocate_vpn_ip(user_id, - project_id, - mac, - hostname) - else: - fixed_ip = net.allocate_ip(user_id, - project_id, - mac, - hostname) - return {'network_type': FLAGS.network_type, - 'bridge_name': net['bridge_name'], - 'mac_address': mac, - 'private_dns_name': fixed_ip} - - def deallocate_fixed_ip(self, fixed_ip, - *args, **kwargs): - """Returns an ip to the pool""" - return model.get_network_by_address(fixed_ip).deallocate_ip(fixed_ip) - - def lease_ip(self, fixed_ip): - """Called by bridge when ip is leased""" - return model.get_network_by_address(fixed_ip).lease_ip(fixed_ip) - - def release_ip(self, fixed_ip): - """Called by bridge when ip is released""" - return model.get_network_by_address(fixed_ip).release_ip(fixed_ip) - - def restart_nets(self): - """Ensure the network for each user is enabled""" - for project in manager.AuthManager().get_projects(): - model.get_project_network(project.id).express() - - def _on_set_network_host(self, user_id, project_id, - *args, **kwargs): - """Called when this host becomes the host for a project""" - vpn.NetworkData.create(project_id) - - @classmethod - def setup_compute_network(cls, user_id, project_id, security_group, - *args, **kwargs): - """Sets up matching network for compute hosts""" - # NOTE(vish): Use BridgedNetwork instead of DHCPNetwork because - # we don't want to run dnsmasq on the client machines - net = model.BridgedNetwork.get_network_for_project( - user_id, - project_id, - security_group) - net.express() diff --git a/nova/network/vpn.py b/nova/network/vpn.py deleted file mode 100644 index 85366ed89..000000000 --- a/nova/network/vpn.py +++ /dev/null @@ -1,126 +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. - -"""Network Data for projects""" - -from nova import datastore -from nova import exception -from nova import flags -from nova import utils - - -FLAGS = flags.FLAGS -flags.DEFINE_string('vpn_ip', utils.get_my_ip(), - 'Public IP for the cloudpipe VPN servers') -flags.DEFINE_integer('vpn_start_port', 1000, - 'Start port for the cloudpipe VPN servers') -flags.DEFINE_integer('vpn_end_port', 2000, - 'End port for the cloudpipe VPN servers') - - -class NoMorePorts(exception.Error): - """No ports available to allocate for the given ip""" - pass - - -class NetworkData(datastore.BasicModel): - """Manages network host, and vpn ip and port for projects""" - def __init__(self, project_id): - self.project_id = project_id - super(NetworkData, self).__init__() - - @property - def identifier(self): - """Identifier used for key in redis""" - return self.project_id - - @classmethod - def create(cls, project_id): - """Creates a vpn for project - - This method finds a free ip and port and stores the associated - values in the datastore. - """ - # TODO(vish): will we ever need multiiple ips per host? - port = cls.find_free_port_for_ip(FLAGS.vpn_ip) - network_data = cls(project_id) - # save ip for project - network_data['host'] = FLAGS.node_name - network_data['project'] = project_id - network_data['ip'] = FLAGS.vpn_ip - network_data['port'] = port - network_data.save() - return network_data - - @classmethod - def find_free_port_for_ip(cls, vpn_ip): - """Finds a free port for a given ip from the redis set""" - # TODO(vish): these redis commands should be generalized and - # placed into a base class. Conceptually, it is - # similar to an association, but we are just - # storing a set of values instead of keys that - # should be turned into objects. - cls._ensure_set_exists(vpn_ip) - - port = datastore.Redis.instance().spop(cls._redis_ports_key(vpn_ip)) - if not port: - raise NoMorePorts() - return port - - @classmethod - def _redis_ports_key(cls, vpn_ip): - """Key that ports are stored under in redis""" - return 'ip:%s:ports' % vpn_ip - - @classmethod - def _ensure_set_exists(cls, vpn_ip): - """Creates the set of ports for the ip if it doesn't already exist""" - # TODO(vish): these ports should be allocated through an admin - # command instead of a flag - redis = datastore.Redis.instance() - if (not redis.exists(cls._redis_ports_key(vpn_ip)) and - not redis.exists(cls._redis_association_name('ip', vpn_ip))): - for i in range(FLAGS.vpn_start_port, FLAGS.vpn_end_port + 1): - redis.sadd(cls._redis_ports_key(vpn_ip), i) - - @classmethod - def num_ports_for_ip(cls, vpn_ip): - """Calculates the number of free ports for a given ip""" - cls._ensure_set_exists(vpn_ip) - return datastore.Redis.instance().scard('ip:%s:ports' % vpn_ip) - - @property - def ip(self): # pylint: disable-msg=C0103 - """The ip assigned to the project""" - return self['ip'] - - @property - def port(self): - """The port assigned to the project""" - return int(self['port']) - - def save(self): - """Saves the association to the given ip""" - self.associate_with('ip', self.ip) - super(NetworkData, self).save() - - def destroy(self): - """Cleans up datastore and adds port back to pool""" - self.unassociate_with('ip', self.ip) - datastore.Redis.instance().sadd('ip:%s:ports' % self.ip, self.port) - super(NetworkData, self).destroy() diff --git a/nova/process.py b/nova/process.py index 425d9f162..74725c157 100644 --- a/nova/process.py +++ b/nova/process.py @@ -18,9 +18,10 @@ # under the License. """ -Process pool, still buggy right now. +Process pool using twisted threading """ +import logging import StringIO from twisted.internet import defer @@ -29,30 +30,14 @@ from twisted.internet import protocol from twisted.internet import reactor from nova import flags +from nova.utils import ProcessExecutionError FLAGS = flags.FLAGS flags.DEFINE_integer('process_pool_size', 4, 'Number of processes to use in the process pool') - -# NOTE(termie): this is copied from twisted.internet.utils but since -# they don't export it I've copied and modified -class UnexpectedErrorOutput(IOError): - """ - Standard error data was received where it was not expected. This is a - subclass of L{IOError} to preserve backward compatibility with the previous - error behavior of L{getProcessOutput}. - - @ivar processEnded: A L{Deferred} which will fire when the process which - produced the data on stderr has ended (exited and all file descriptors - closed). - """ - def __init__(self, stdout=None, stderr=None): - IOError.__init__(self, "got stdout: %r\nstderr: %r" % (stdout, stderr)) - - -# This is based on _BackRelay from twister.internal.utils, but modified to -# capture both stdout and stderr, without odd stderr handling, and also to +# This is based on _BackRelay from twister.internal.utils, but modified to +# capture both stdout and stderr, without odd stderr handling, and also to # handle stdin class BackRelayWithInput(protocol.ProcessProtocol): """ @@ -62,22 +47,23 @@ class BackRelayWithInput(protocol.ProcessProtocol): @ivar deferred: A L{Deferred} which will be called back with all of stdout and all of stderr as well (as a tuple). C{terminate_on_stderr} is true and any bytes are received over stderr, this will fire with an - L{_UnexpectedErrorOutput} instance and the attribute will be set to + L{_ProcessExecutionError} instance and the attribute will be set to C{None}. - @ivar onProcessEnded: If C{terminate_on_stderr} is false and bytes are - received over stderr, this attribute will refer to a L{Deferred} which - will be called back when the process ends. This C{Deferred} is also - associated with the L{_UnexpectedErrorOutput} which C{deferred} fires - with earlier in this case so that users can determine when the process + @ivar onProcessEnded: If C{terminate_on_stderr} is false and bytes are + received over stderr, this attribute will refer to a L{Deferred} which + will be called back when the process ends. This C{Deferred} is also + associated with the L{_ProcessExecutionError} which C{deferred} fires + with earlier in this case so that users can determine when the process has actually ended, in addition to knowing when bytes have been received via stderr. """ - def __init__(self, deferred, started_deferred=None, - terminate_on_stderr=False, check_exit_code=True, - process_input=None): + def __init__(self, deferred, cmd, started_deferred=None, + terminate_on_stderr=False, check_exit_code=True, + process_input=None): self.deferred = deferred + self.cmd = cmd self.stdout = StringIO.StringIO() self.stderr = StringIO.StringIO() self.started_deferred = started_deferred @@ -85,14 +71,18 @@ class BackRelayWithInput(protocol.ProcessProtocol): self.check_exit_code = check_exit_code self.process_input = process_input self.on_process_ended = None - + + def _build_execution_error(self, exit_code=None): + return ProcessExecutionError(cmd=self.cmd, + exit_code=exit_code, + stdout=self.stdout.getvalue(), + stderr=self.stderr.getvalue()) + def errReceived(self, text): self.stderr.write(text) if self.terminate_on_stderr and (self.deferred is not None): self.on_process_ended = defer.Deferred() - self.deferred.errback(UnexpectedErrorOutput( - stdout=self.stdout.getvalue(), - stderr=self.stderr.getvalue())) + self.deferred.errback(self._build_execution_error()) self.deferred = None self.transport.loseConnection() @@ -102,15 +92,19 @@ class BackRelayWithInput(protocol.ProcessProtocol): def processEnded(self, reason): if self.deferred is not None: stdout, stderr = self.stdout.getvalue(), self.stderr.getvalue() - try: - if self.check_exit_code: - reason.trap(error.ProcessDone) - self.deferred.callback((stdout, stderr)) - except: - # NOTE(justinsb): This logic is a little suspicious to me... - # If the callback throws an exception, then errback will be - # called also. However, this is what the unit tests test for... - self.deferred.errback(UnexpectedErrorOutput(stdout, stderr)) + exit_code = reason.value.exitCode + if self.check_exit_code and exit_code <> 0: + self.deferred.errback(self._build_execution_error(exit_code)) + else: + try: + if self.check_exit_code: + reason.trap(error.ProcessDone) + self.deferred.callback((stdout, stderr)) + except: + # NOTE(justinsb): This logic is a little suspicious to me... + # If the callback throws an exception, then errback will be + # called also. However, this is what the unit tests test for... + self.deferred.errback(self._build_execution_error(exit_code)) elif self.on_process_ended is not None: self.on_process_ended.errback(reason) @@ -122,8 +116,8 @@ class BackRelayWithInput(protocol.ProcessProtocol): self.transport.write(self.process_input) self.transport.closeStdin() -def get_process_output(executable, args=None, env=None, path=None, - process_reactor=None, check_exit_code=True, +def get_process_output(executable, args=None, env=None, path=None, + process_reactor=None, check_exit_code=True, process_input=None, started_deferred=None, terminate_on_stderr=False): if process_reactor is None: @@ -131,10 +125,15 @@ def get_process_output(executable, args=None, env=None, path=None, args = args and args or () env = env and env and {} deferred = defer.Deferred() + cmd = executable + if args: + cmd = cmd + " " + ' '.join(args) + logging.debug("Running cmd: %s", cmd) process_handler = BackRelayWithInput( - deferred, - started_deferred=started_deferred, - check_exit_code=check_exit_code, + deferred, + cmd, + started_deferred=started_deferred, + check_exit_code=check_exit_code, process_input=process_input, terminate_on_stderr=terminate_on_stderr) # NOTE(vish): commands come in as unicode, but self.executes needs @@ -142,7 +141,7 @@ def get_process_output(executable, args=None, env=None, path=None, executable = str(executable) if not args is None: args = [str(x) for x in args] - process_reactor.spawnProcess( process_handler, executable, + process_reactor.spawnProcess( process_handler, executable, (executable,)+tuple(args), env, path) return deferred diff --git a/nova/server.py b/nova/server.py index c6b60e090..d4563bfe0 100644 --- a/nova/server.py +++ b/nova/server.py @@ -60,7 +60,7 @@ def stop(pidfile): sys.stderr.write(message % pidfile) return # not an error in a restart - # Try killing the daemon process + # Try killing the daemon process try: while 1: os.kill(pid, signal.SIGTERM) diff --git a/nova/service.py b/nova/service.py index 96281bc6b..870dd6ceb 100644 --- a/nova/service.py +++ b/nova/service.py @@ -28,75 +28,132 @@ from twisted.internet import defer from twisted.internet import task from twisted.application import service -from nova import datastore +from nova import db +from nova import exception from nova import flags from nova import rpc -from nova.compute import model +from nova import utils FLAGS = flags.FLAGS - flags.DEFINE_integer('report_interval', 10, 'seconds between nodes reporting state to cloud', lower_bound=1) + class Service(object, service.Service): - """Base class for workers that run on hosts""" + """Base class for workers that run on hosts.""" + + def __init__(self, host, binary, topic, manager, *args, **kwargs): + self.host = host + self.binary = binary + self.topic = topic + manager_class = utils.import_class(manager) + self.manager = manager_class(host=host, *args, **kwargs) + self.model_disconnected = False + super(Service, self).__init__(*args, **kwargs) + try: + service_ref = db.service_get_by_args(None, + self.host, + self.binary) + self.service_id = service_ref['id'] + except exception.NotFound: + self._create_service_ref() + + + def _create_service_ref(self): + service_ref = db.service_create(None, {'host': self.host, + 'binary': self.binary, + 'topic': self.topic, + 'report_count': 0}) + self.service_id = service_ref['id'] + + def __getattr__(self, key): + try: + return super(Service, self).__getattr__(key) + except AttributeError: + return getattr(self.manager, key) @classmethod def create(cls, - report_interval=None, # defaults to flag - bin_name=None, # defaults to basename of executable - topic=None): # defaults to basename - "nova-" part - """Instantiates class and passes back application object""" + host=None, + binary=None, + topic=None, + manager=None, + report_interval=None): + """Instantiates class and passes back application object. + + Args: + host, defaults to FLAGS.host + binary, defaults to basename of executable + topic, defaults to bin_name - "nova-" part + manager, defaults to FLAGS.<topic>_manager + report_interval, defaults to FLAGS.report_interval + """ + if not host: + host = FLAGS.host + if not binary: + binary = os.path.basename(inspect.stack()[-1][1]) + if not topic: + topic = binary.rpartition("nova-")[2] + if not manager: + manager = FLAGS.get('%s_manager' % topic, None) if not report_interval: - # NOTE(vish): set here because if it is set to flag in the - # parameter list, it wrongly uses the default report_interval = FLAGS.report_interval - # NOTE(vish): magic to automatically determine bin_name and topic - if not bin_name: - bin_name = os.path.basename(inspect.stack()[-1][1]) - if not topic: - topic = bin_name.rpartition("nova-")[2] - logging.warn("Starting %s node" % topic) - node_instance = cls() - + logging.warn("Starting %s node", topic) + service_obj = cls(host, binary, topic, manager) conn = rpc.Connection.instance() consumer_all = rpc.AdapterConsumer( connection=conn, - topic='%s' % topic, - proxy=node_instance) - + topic=topic, + proxy=service_obj) consumer_node = rpc.AdapterConsumer( connection=conn, - topic='%s.%s' % (topic, FLAGS.node_name), - proxy=node_instance) + topic='%s.%s' % (topic, host), + proxy=service_obj) - pulse = task.LoopingCall(node_instance.report_state, - FLAGS.node_name, - bin_name) + pulse = task.LoopingCall(service_obj.report_state) pulse.start(interval=report_interval, now=False) consumer_all.attach_to_twisted() consumer_node.attach_to_twisted() # This is the parent service that twistd will be looking for when it - # parses this file, return it so that we can get it into globals below - application = service.Application(bin_name) - node_instance.setServiceParent(application) + # parses this file, return it so that we can get it into globals. + application = service.Application(binary) + service_obj.setServiceParent(application) return application + def kill(self, context=None): + """Destroy the service object in the datastore""" + try: + db.service_destroy(context, self.service_id) + except exception.NotFound: + logging.warn("Service killed that has no database entry") + @defer.inlineCallbacks - def report_state(self, nodename, daemon): - # TODO(termie): make this pattern be more elegant. -todd + def report_state(self, context=None): + """Update the state of this service in the datastore.""" try: - record = model.Daemon(nodename, daemon) - record.heartbeat() + try: + service_ref = db.service_get(context, self.service_id) + except exception.NotFound: + logging.debug("The service database object disappeared, " + "Recreating it.") + self._create_service_ref() + service_ref = db.service_get(context, self.service_id) + + db.service_update(context, + self.service_id, + {'report_count': service_ref['report_count'] + 1}) + + # TODO(termie): make this pattern be more elegant. if getattr(self, "model_disconnected", False): self.model_disconnected = False logging.error("Recovered model server connection!") - except datastore.ConnectionError, ex: + # TODO(vish): this should probably only catch connection errors + except Exception: # pylint: disable-msg=W0702 if not getattr(self, "model_disconnected", False): self.model_disconnected = True logging.exception("model server went away") diff --git a/nova/tests/access_unittest.py b/nova/tests/access_unittest.py index fa0a090a0..59e1683db 100644 --- a/nova/tests/access_unittest.py +++ b/nova/tests/access_unittest.py @@ -33,8 +33,6 @@ class Context(object): class AccessTestCase(test.BaseTestCase): def setUp(self): super(AccessTestCase, self).setUp() - FLAGS.connection_type = 'fake' - FLAGS.fake_storage = True um = manager.AuthManager() # Make test users try: diff --git a/nova/tests/auth_unittest.py b/nova/tests/auth_unittest.py index 0b404bfdc..b54e68274 100644 --- a/nova/tests/auth_unittest.py +++ b/nova/tests/auth_unittest.py @@ -32,11 +32,9 @@ FLAGS = flags.FLAGS class AuthTestCase(test.BaseTestCase): - flush_db = False def setUp(self): super(AuthTestCase, self).setUp() - self.flags(connection_type='fake', - fake_storage=True) + self.flags(connection_type='fake') self.manager = manager.AuthManager() def test_001_can_create_users(self): diff --git a/nova/tests/cloud_unittest.py b/nova/tests/cloud_unittest.py index 19aa23b9e..c36d5a34f 100644 --- a/nova/tests/cloud_unittest.py +++ b/nova/tests/cloud_unittest.py @@ -27,9 +27,9 @@ from xml.etree import ElementTree from nova import flags from nova import rpc from nova import test +from nova import utils from nova.auth import manager from nova.compute import power_state -from nova.compute import service from nova.endpoint import api from nova.endpoint import cloud @@ -40,8 +40,7 @@ FLAGS = flags.FLAGS class CloudTestCase(test.BaseTestCase): def setUp(self): super(CloudTestCase, self).setUp() - self.flags(connection_type='fake', - fake_storage=True) + self.flags(connection_type='fake') self.conn = rpc.Connection.instance() logging.getLogger().setLevel(logging.DEBUG) @@ -50,7 +49,7 @@ class CloudTestCase(test.BaseTestCase): self.cloud = cloud.CloudController() # set up a service - self.compute = service.ComputeService() + self.compute = utils.import_class(FLAGS.compute_manager) self.compute_consumer = rpc.AdapterConsumer(connection=self.conn, topic=FLAGS.compute_topic, proxy=self.compute) diff --git a/nova/tests/compute_unittest.py b/nova/tests/compute_unittest.py index da0f82e3a..de2bf3d3b 100644 --- a/nova/tests/compute_unittest.py +++ b/nova/tests/compute_unittest.py @@ -15,113 +15,115 @@ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. +""" +Tests For Compute +""" +import datetime import logging -import time + from twisted.internet import defer -from xml.etree import ElementTree +from nova import db from nova import exception from nova import flags from nova import test from nova import utils -from nova.compute import model -from nova.compute import service +from nova.auth import manager FLAGS = flags.FLAGS -class InstanceXmlTestCase(test.TrialTestCase): - # @defer.inlineCallbacks - def test_serialization(self): - # TODO: Reimplement this, it doesn't make sense in redis-land - return - - # instance_id = 'foo' - # first_node = node.Node() - # inst = yield first_node.run_instance(instance_id) - # - # # force the state so that we can verify that it changes - # inst._s['state'] = node.Instance.NOSTATE - # xml = inst.toXml() - # self.assert_(ElementTree.parse(StringIO.StringIO(xml))) - # - # second_node = node.Node() - # new_inst = node.Instance.fromXml(second_node._conn, pool=second_node._pool, xml=xml) - # self.assertEqual(new_inst.state, node.Instance.RUNNING) - # rv = yield first_node.terminate_instance(instance_id) - - -class ComputeConnectionTestCase(test.TrialTestCase): - def setUp(self): +class ComputeTestCase(test.TrialTestCase): + """Test case for compute""" + def setUp(self): # pylint: disable-msg=C0103 logging.getLogger().setLevel(logging.DEBUG) - super(ComputeConnectionTestCase, self).setUp() - self.flags(connection_type='fake', - fake_storage=True) - self.compute = service.ComputeService() - - def create_instance(self): - instdir = model.InstanceDirectory() - inst = instdir.new() - # TODO(ja): add ami, ari, aki, user_data + super(ComputeTestCase, self).setUp() + self.flags(connection_type='fake') + self.compute = utils.import_object(FLAGS.compute_manager) + self.manager = manager.AuthManager() + self.user = self.manager.create_user('fake', 'fake', 'fake') + self.project = self.manager.create_project('fake', 'fake', 'fake') + self.context = None + + def tearDown(self): # pylint: disable-msg=C0103 + self.manager.delete_user(self.user) + self.manager.delete_project(self.project) + + def _create_instance(self): + """Create a test instance""" + inst = {} + inst['image_id'] = 'ami-test' inst['reservation_id'] = 'r-fakeres' inst['launch_time'] = '10' - inst['user_id'] = 'fake' - inst['project_id'] = 'fake' + inst['user_id'] = self.user.id + inst['project_id'] = self.project.id inst['instance_type'] = 'm1.tiny' - inst['node_name'] = FLAGS.node_name inst['mac_address'] = utils.generate_mac() inst['ami_launch_index'] = 0 - inst.save() - return inst['instance_id'] + return db.instance_create(self.context, inst)['id'] @defer.inlineCallbacks - def test_run_describe_terminate(self): - instance_id = self.create_instance() + def test_run_terminate(self): + """Make sure it is possible to run and terminate instance""" + instance_id = self._create_instance() - rv = yield self.compute.run_instance(instance_id) + yield self.compute.run_instance(self.context, instance_id) - rv = yield self.compute.describe_instances() - logging.info("Running instances: %s", rv) - self.assertEqual(rv[instance_id].name, instance_id) + instances = db.instance_get_all(None) + logging.info("Running instances: %s", instances) + self.assertEqual(len(instances), 1) - rv = yield self.compute.terminate_instance(instance_id) + yield self.compute.terminate_instance(self.context, instance_id) - rv = yield self.compute.describe_instances() - logging.info("After terminating instances: %s", rv) - self.assertEqual(rv, {}) + instances = db.instance_get_all(None) + logging.info("After terminating instances: %s", instances) + self.assertEqual(len(instances), 0) @defer.inlineCallbacks - def test_reboot(self): - instance_id = self.create_instance() - rv = yield self.compute.run_instance(instance_id) - - rv = yield self.compute.describe_instances() - self.assertEqual(rv[instance_id].name, instance_id) - - yield self.compute.reboot_instance(instance_id) + def test_run_terminate_timestamps(self): + """Make sure it is possible to run and terminate instance""" + instance_id = self._create_instance() + instance_ref = db.instance_get(self.context, instance_id) + self.assertEqual(instance_ref['launched_at'], None) + self.assertEqual(instance_ref['terminated_at'], None) + launch = datetime.datetime.utcnow() + yield self.compute.run_instance(self.context, instance_id) + instance_ref = db.instance_get(self.context, instance_id) + self.assert_(instance_ref['launched_at'] > launch) + self.assertEqual(instance_ref['terminated_at'], None) + terminate = datetime.datetime.utcnow() + yield self.compute.terminate_instance(self.context, instance_id) + instance_ref = db.instance_get({'deleted': True}, instance_id) + self.assert_(instance_ref['launched_at'] < terminate) + self.assert_(instance_ref['terminated_at'] > terminate) - rv = yield self.compute.describe_instances() - self.assertEqual(rv[instance_id].name, instance_id) - rv = yield self.compute.terminate_instance(instance_id) + @defer.inlineCallbacks + def test_reboot(self): + """Ensure instance can be rebooted""" + instance_id = self._create_instance() + yield self.compute.run_instance(self.context, instance_id) + yield self.compute.reboot_instance(self.context, instance_id) + yield self.compute.terminate_instance(self.context, instance_id) @defer.inlineCallbacks def test_console_output(self): - instance_id = self.create_instance() - rv = yield self.compute.run_instance(instance_id) + """Make sure we can get console output from instance""" + instance_id = self._create_instance() + yield self.compute.run_instance(self.context, instance_id) - console = yield self.compute.get_console_output(instance_id) + console = yield self.compute.get_console_output(self.context, + instance_id) self.assert_(console) - rv = yield self.compute.terminate_instance(instance_id) + yield self.compute.terminate_instance(self.context, instance_id) @defer.inlineCallbacks def test_run_instance_existing(self): - instance_id = self.create_instance() - rv = yield self.compute.run_instance(instance_id) - - rv = yield self.compute.describe_instances() - self.assertEqual(rv[instance_id].name, instance_id) - - self.assertRaises(exception.Error, self.compute.run_instance, instance_id) - rv = yield self.compute.terminate_instance(instance_id) + """Ensure failure when running an instance that already exists""" + instance_id = self._create_instance() + yield self.compute.run_instance(self.context, instance_id) + self.assertFailure(self.compute.run_instance(self.context, + instance_id), + exception.Error) + yield self.compute.terminate_instance(self.context, instance_id) diff --git a/nova/tests/fake_flags.py b/nova/tests/fake_flags.py index a7310fb26..8f4754650 100644 --- a/nova/tests/fake_flags.py +++ b/nova/tests/fake_flags.py @@ -20,9 +20,20 @@ from nova import flags FLAGS = flags.FLAGS +flags.DECLARE('volume_driver', 'nova.volume.manager') +FLAGS.volume_driver = 'nova.volume.driver.FakeAOEDriver' FLAGS.connection_type = 'fake' -FLAGS.fake_storage = True FLAGS.fake_rabbit = True -FLAGS.fake_network = True FLAGS.auth_driver = 'nova.auth.ldapdriver.FakeLdapDriver' +flags.DECLARE('network_size', 'nova.network.manager') +flags.DECLARE('num_networks', 'nova.network.manager') +flags.DECLARE('fake_network', 'nova.network.manager') +FLAGS.network_size = 16 +FLAGS.num_networks = 5 +FLAGS.fake_network = True +flags.DECLARE('num_shelves', 'nova.volume.manager') +flags.DECLARE('blades_per_shelf', 'nova.volume.manager') +FLAGS.num_shelves = 2 +FLAGS.blades_per_shelf = 4 FLAGS.verbose = True +FLAGS.sql_connection = 'sqlite:///nova.sqlite' diff --git a/nova/tests/model_unittest.py b/nova/tests/model_unittest.py deleted file mode 100644 index dc2441c24..000000000 --- a/nova/tests/model_unittest.py +++ /dev/null @@ -1,292 +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. - -from datetime import datetime, timedelta -import logging -import time - -from nova import flags -from nova import test -from nova import utils -from nova.compute import model - - -FLAGS = flags.FLAGS - - -class ModelTestCase(test.TrialTestCase): - def setUp(self): - super(ModelTestCase, self).setUp() - self.flags(connection_type='fake', - fake_storage=True) - - def tearDown(self): - model.Instance('i-test').destroy() - model.Host('testhost').destroy() - model.Daemon('testhost', 'nova-testdaemon').destroy() - - def create_instance(self): - inst = model.Instance('i-test') - inst['reservation_id'] = 'r-test' - inst['launch_time'] = '10' - inst['user_id'] = 'fake' - inst['project_id'] = 'fake' - inst['instance_type'] = 'm1.tiny' - inst['mac_address'] = utils.generate_mac() - inst['ami_launch_index'] = 0 - inst['private_dns_name'] = '10.0.0.1' - inst.save() - return inst - - def create_host(self): - host = model.Host('testhost') - host.save() - return host - - def create_daemon(self): - daemon = model.Daemon('testhost', 'nova-testdaemon') - daemon.save() - return daemon - - def create_session_token(self): - session_token = model.SessionToken('tk12341234') - session_token['user'] = 'testuser' - session_token.save() - return session_token - - def test_create_instance(self): - """store with create_instace, then test that a load finds it""" - instance = self.create_instance() - old = model.Instance(instance.identifier) - self.assertFalse(old.is_new_record()) - - def test_delete_instance(self): - """create, then destroy, then make sure loads a new record""" - instance = self.create_instance() - instance.destroy() - newinst = model.Instance('i-test') - self.assertTrue(newinst.is_new_record()) - - def test_instance_added_to_set(self): - """create, then check that it is listed in global set""" - instance = self.create_instance() - found = False - for x in model.InstanceDirectory().all: - if x.identifier == 'i-test': - found = True - self.assert_(found) - - def test_instance_associates_project(self): - """create, then check that it is listed for the project""" - instance = self.create_instance() - found = False - for x in model.InstanceDirectory().by_project(instance.project): - if x.identifier == 'i-test': - found = True - self.assert_(found) - - def test_instance_associates_ip(self): - """create, then check that it is listed for the ip""" - instance = self.create_instance() - found = False - x = model.InstanceDirectory().by_ip(instance['private_dns_name']) - self.assertEqual(x.identifier, 'i-test') - - def test_instance_associates_node(self): - """create, then check that it is listed for the node_name""" - instance = self.create_instance() - found = False - for x in model.InstanceDirectory().by_node(FLAGS.node_name): - if x.identifier == 'i-test': - found = True - self.assertFalse(found) - instance['node_name'] = 'test_node' - instance.save() - for x in model.InstanceDirectory().by_node('test_node'): - if x.identifier == 'i-test': - found = True - self.assert_(found) - - - def test_host_class_finds_hosts(self): - host = self.create_host() - self.assertEqual('testhost', model.Host.lookup('testhost').identifier) - - def test_host_class_doesnt_find_missing_hosts(self): - rv = model.Host.lookup('woahnelly') - self.assertEqual(None, rv) - - def test_create_host(self): - """store with create_host, then test that a load finds it""" - host = self.create_host() - old = model.Host(host.identifier) - self.assertFalse(old.is_new_record()) - - def test_delete_host(self): - """create, then destroy, then make sure loads a new record""" - instance = self.create_host() - instance.destroy() - newinst = model.Host('testhost') - self.assertTrue(newinst.is_new_record()) - - def test_host_added_to_set(self): - """create, then check that it is included in list""" - instance = self.create_host() - found = False - for x in model.Host.all(): - if x.identifier == 'testhost': - found = True - self.assert_(found) - - def test_create_daemon_two_args(self): - """create a daemon with two arguments""" - d = self.create_daemon() - d = model.Daemon('testhost', 'nova-testdaemon') - self.assertFalse(d.is_new_record()) - - def test_create_daemon_single_arg(self): - """Create a daemon using the combined host:bin format""" - d = model.Daemon("testhost:nova-testdaemon") - d.save() - d = model.Daemon('testhost:nova-testdaemon') - self.assertFalse(d.is_new_record()) - - def test_equality_of_daemon_single_and_double_args(self): - """Create a daemon using the combined host:bin arg, find with 2""" - d = model.Daemon("testhost:nova-testdaemon") - d.save() - d = model.Daemon('testhost', 'nova-testdaemon') - self.assertFalse(d.is_new_record()) - - def test_equality_daemon_of_double_and_single_args(self): - """Create a daemon using the combined host:bin arg, find with 2""" - d = self.create_daemon() - d = model.Daemon('testhost:nova-testdaemon') - self.assertFalse(d.is_new_record()) - - def test_delete_daemon(self): - """create, then destroy, then make sure loads a new record""" - instance = self.create_daemon() - instance.destroy() - newinst = model.Daemon('testhost', 'nova-testdaemon') - self.assertTrue(newinst.is_new_record()) - - def test_daemon_heartbeat(self): - """Create a daemon, sleep, heartbeat, check for update""" - d = self.create_daemon() - ts = d['updated_at'] - time.sleep(2) - d.heartbeat() - d2 = model.Daemon('testhost', 'nova-testdaemon') - ts2 = d2['updated_at'] - self.assert_(ts2 > ts) - - def test_daemon_added_to_set(self): - """create, then check that it is included in list""" - instance = self.create_daemon() - found = False - for x in model.Daemon.all(): - if x.identifier == 'testhost:nova-testdaemon': - found = True - self.assert_(found) - - def test_daemon_associates_host(self): - """create, then check that it is listed for the host""" - instance = self.create_daemon() - found = False - for x in model.Daemon.by_host('testhost'): - if x.identifier == 'testhost:nova-testdaemon': - found = True - self.assertTrue(found) - - def test_create_session_token(self): - """create""" - d = self.create_session_token() - d = model.SessionToken(d.token) - self.assertFalse(d.is_new_record()) - - def test_delete_session_token(self): - """create, then destroy, then make sure loads a new record""" - instance = self.create_session_token() - instance.destroy() - newinst = model.SessionToken(instance.token) - self.assertTrue(newinst.is_new_record()) - - def test_session_token_added_to_set(self): - """create, then check that it is included in list""" - instance = self.create_session_token() - found = False - for x in model.SessionToken.all(): - if x.identifier == instance.token: - found = True - self.assert_(found) - - def test_session_token_associates_user(self): - """create, then check that it is listed for the user""" - instance = self.create_session_token() - found = False - for x in model.SessionToken.associated_to('user', 'testuser'): - if x.identifier == instance.identifier: - found = True - self.assertTrue(found) - - def test_session_token_generation(self): - instance = model.SessionToken.generate('username', 'TokenType') - self.assertFalse(instance.is_new_record()) - - def test_find_generated_session_token(self): - instance = model.SessionToken.generate('username', 'TokenType') - found = model.SessionToken.lookup(instance.identifier) - self.assert_(found) - - def test_update_session_token_expiry(self): - instance = model.SessionToken('tk12341234') - oldtime = datetime.utcnow() - instance['expiry'] = oldtime.strftime(utils.TIME_FORMAT) - instance.update_expiry() - expiry = utils.parse_isotime(instance['expiry']) - self.assert_(expiry > datetime.utcnow()) - - def test_session_token_lookup_when_expired(self): - instance = model.SessionToken.generate("testuser") - instance['expiry'] = datetime.utcnow().strftime(utils.TIME_FORMAT) - instance.save() - inst = model.SessionToken.lookup(instance.identifier) - self.assertFalse(inst) - - def test_session_token_lookup_when_not_expired(self): - instance = model.SessionToken.generate("testuser") - inst = model.SessionToken.lookup(instance.identifier) - self.assert_(inst) - - def test_session_token_is_expired_when_expired(self): - instance = model.SessionToken.generate("testuser") - instance['expiry'] = datetime.utcnow().strftime(utils.TIME_FORMAT) - self.assert_(instance.is_expired()) - - def test_session_token_is_expired_when_not_expired(self): - instance = model.SessionToken.generate("testuser") - self.assertFalse(instance.is_expired()) - - def test_session_token_ttl(self): - instance = model.SessionToken.generate("testuser") - now = datetime.utcnow() - delta = timedelta(hours=1) - instance['expiry'] = (now + delta).strftime(utils.TIME_FORMAT) - # give 5 seconds of fuzziness - self.assert_(abs(instance.ttl() - FLAGS.auth_token_ttl) < 5) diff --git a/nova/tests/network_unittest.py b/nova/tests/network_unittest.py index 00b0b97e7..dc5277f02 100644 --- a/nova/tests/network_unittest.py +++ b/nova/tests/network_unittest.py @@ -22,14 +22,13 @@ import IPy import os import logging +from nova import db +from nova import exception from nova import flags from nova import test from nova import utils from nova.auth import manager -from nova.network import model -from nova.network import service -from nova.network import vpn -from nova.network.exception import NoMoreAddresses +from nova.endpoint import api FLAGS = flags.FLAGS @@ -41,183 +40,180 @@ class NetworkTestCase(test.TrialTestCase): # NOTE(vish): if you change these flags, make sure to change the # flags in the corresponding section in nova-dhcpbridge self.flags(connection_type='fake', - fake_storage=True, fake_network=True, auth_driver='nova.auth.ldapdriver.FakeLdapDriver', - network_size=32) + network_size=16, + num_networks=5) logging.getLogger().setLevel(logging.DEBUG) self.manager = manager.AuthManager() self.user = self.manager.create_user('netuser', 'netuser', 'netuser') self.projects = [] - self.projects.append(self.manager.create_project('netuser', - 'netuser', - 'netuser')) - for i in range(0, 6): + self.network = utils.import_object(FLAGS.network_manager) + self.context = api.APIRequestContext(None, project=None, user=self.user) + for i in range(5): name = 'project%s' % i self.projects.append(self.manager.create_project(name, 'netuser', name)) - vpn.NetworkData.create(self.projects[i].id) - self.service = service.VlanNetworkService() + # create the necessary network data for the project + self.network.set_network_host(self.context, self.projects[i].id) + instance_ref = db.instance_create(None, + {'mac_address': utils.generate_mac()}) + self.instance_id = instance_ref['id'] + instance_ref = db.instance_create(None, + {'mac_address': utils.generate_mac()}) + self.instance2_id = instance_ref['id'] def tearDown(self): # pylint: disable-msg=C0103 super(NetworkTestCase, self).tearDown() + # TODO(termie): this should really be instantiating clean datastores + # in between runs, one failure kills all the tests + db.instance_destroy(None, self.instance_id) + db.instance_destroy(None, self.instance2_id) for project in self.projects: self.manager.delete_project(project) self.manager.delete_user(self.user) - def test_public_network_allocation(self): + def _create_address(self, project_num, instance_id=None): + """Create an address in given project num""" + if instance_id is None: + instance_id = self.instance_id + self.context.project = self.projects[project_num] + return self.network.allocate_fixed_ip(self.context, instance_id) + + def test_public_network_association(self): """Makes sure that we can allocaate a public ip""" + # TODO(vish): better way of adding floating ips pubnet = IPy.IP(flags.FLAGS.public_range) - address = self.service.allocate_elastic_ip(self.user.id, - self.projects[0].id) - self.assertTrue(IPy.IP(address) in pubnet) + address = str(pubnet[0]) + try: + db.floating_ip_get_by_address(None, address) + except exception.NotFound: + db.floating_ip_create(None, {'address': address, + 'host': FLAGS.host}) + float_addr = self.network.allocate_floating_ip(self.context, + self.projects[0].id) + fix_addr = self._create_address(0) + self.assertEqual(float_addr, str(pubnet[0])) + self.network.associate_floating_ip(self.context, float_addr, fix_addr) + address = db.instance_get_floating_address(None, self.instance_id) + self.assertEqual(address, float_addr) + self.network.disassociate_floating_ip(self.context, float_addr) + address = db.instance_get_floating_address(None, self.instance_id) + self.assertEqual(address, None) + self.network.deallocate_floating_ip(self.context, float_addr) + self.network.deallocate_fixed_ip(self.context, fix_addr) def test_allocate_deallocate_fixed_ip(self): """Makes sure that we can allocate and deallocate a fixed ip""" - result = self.service.allocate_fixed_ip( - self.user.id, self.projects[0].id) - address = result['private_dns_name'] - mac = result['mac_address'] - net = model.get_project_network(self.projects[0].id, "default") - self.assertEqual(True, is_in_project(address, self.projects[0].id)) - hostname = "test-host" - issue_ip(mac, address, hostname, net.bridge_name) - self.service.deallocate_fixed_ip(address) + address = self._create_address(0) + self.assertTrue(is_allocated_in_project(address, self.projects[0].id)) + lease_ip(address) + self.network.deallocate_fixed_ip(self.context, address) # Doesn't go away until it's dhcp released - self.assertEqual(True, is_in_project(address, self.projects[0].id)) + self.assertTrue(is_allocated_in_project(address, self.projects[0].id)) - release_ip(mac, address, hostname, net.bridge_name) - self.assertEqual(False, is_in_project(address, self.projects[0].id)) + release_ip(address) + self.assertFalse(is_allocated_in_project(address, self.projects[0].id)) def test_side_effects(self): """Ensures allocating and releasing has no side effects""" - hostname = "side-effect-host" - result = self.service.allocate_fixed_ip(self.user.id, - self.projects[0].id) - mac = result['mac_address'] - address = result['private_dns_name'] - result = self.service.allocate_fixed_ip(self.user, - self.projects[1].id) - secondmac = result['mac_address'] - secondaddress = result['private_dns_name'] - - net = model.get_project_network(self.projects[0].id, "default") - secondnet = model.get_project_network(self.projects[1].id, "default") - - self.assertEqual(True, is_in_project(address, self.projects[0].id)) - self.assertEqual(True, is_in_project(secondaddress, - self.projects[1].id)) - self.assertEqual(False, is_in_project(address, self.projects[1].id)) + address = self._create_address(0) + address2 = self._create_address(1, self.instance2_id) + + self.assertTrue(is_allocated_in_project(address, self.projects[0].id)) + self.assertTrue(is_allocated_in_project(address2, self.projects[1].id)) + self.assertFalse(is_allocated_in_project(address, self.projects[1].id)) # Addresses are allocated before they're issued - issue_ip(mac, address, hostname, net.bridge_name) - issue_ip(secondmac, secondaddress, hostname, secondnet.bridge_name) + lease_ip(address) + lease_ip(address2) - self.service.deallocate_fixed_ip(address) - release_ip(mac, address, hostname, net.bridge_name) - self.assertEqual(False, is_in_project(address, self.projects[0].id)) + self.network.deallocate_fixed_ip(self.context, address) + release_ip(address) + self.assertFalse(is_allocated_in_project(address, self.projects[0].id)) # First address release shouldn't affect the second - self.assertEqual(True, is_in_project(secondaddress, - self.projects[1].id)) + self.assertTrue(is_allocated_in_project(address2, self.projects[1].id)) - self.service.deallocate_fixed_ip(secondaddress) - release_ip(secondmac, secondaddress, hostname, secondnet.bridge_name) - self.assertEqual(False, is_in_project(secondaddress, - self.projects[1].id)) + self.network.deallocate_fixed_ip(self.context, address2) + release_ip(address2) + self.assertFalse(is_allocated_in_project(address2, + self.projects[1].id)) def test_subnet_edge(self): """Makes sure that private ips don't overlap""" - result = self.service.allocate_fixed_ip(self.user.id, - self.projects[0].id) - firstaddress = result['private_dns_name'] - hostname = "toomany-hosts" + first = self._create_address(0) + lease_ip(first) + instance_ids = [] for i in range(1, 5): - project_id = self.projects[i].id - result = self.service.allocate_fixed_ip( - self.user, project_id) - mac = result['mac_address'] - address = result['private_dns_name'] - result = self.service.allocate_fixed_ip( - self.user, project_id) - mac2 = result['mac_address'] - address2 = result['private_dns_name'] - result = self.service.allocate_fixed_ip( - self.user, project_id) - mac3 = result['mac_address'] - address3 = result['private_dns_name'] - net = model.get_project_network(project_id, "default") - issue_ip(mac, address, hostname, net.bridge_name) - issue_ip(mac2, address2, hostname, net.bridge_name) - issue_ip(mac3, address3, hostname, net.bridge_name) - self.assertEqual(False, is_in_project(address, - self.projects[0].id)) - self.assertEqual(False, is_in_project(address2, - self.projects[0].id)) - self.assertEqual(False, is_in_project(address3, - self.projects[0].id)) - self.service.deallocate_fixed_ip(address) - self.service.deallocate_fixed_ip(address2) - self.service.deallocate_fixed_ip(address3) - release_ip(mac, address, hostname, net.bridge_name) - release_ip(mac2, address2, hostname, net.bridge_name) - release_ip(mac3, address3, hostname, net.bridge_name) - net = model.get_project_network(self.projects[0].id, "default") - self.service.deallocate_fixed_ip(firstaddress) + mac = utils.generate_mac() + instance_ref = db.instance_create(None, + {'mac_address': mac}) + instance_ids.append(instance_ref['id']) + address = self._create_address(i, instance_ref['id']) + mac = utils.generate_mac() + instance_ref = db.instance_create(None, + {'mac_address': mac}) + instance_ids.append(instance_ref['id']) + address2 = self._create_address(i, instance_ref['id']) + mac = utils.generate_mac() + instance_ref = db.instance_create(None, + {'mac_address': mac}) + instance_ids.append(instance_ref['id']) + address3 = self._create_address(i, instance_ref['id']) + lease_ip(address) + lease_ip(address2) + lease_ip(address3) + self.assertFalse(is_allocated_in_project(address, + self.projects[0].id)) + self.assertFalse(is_allocated_in_project(address2, + self.projects[0].id)) + self.assertFalse(is_allocated_in_project(address3, + self.projects[0].id)) + self.network.deallocate_fixed_ip(self.context, address) + self.network.deallocate_fixed_ip(self.context, address2) + self.network.deallocate_fixed_ip(self.context, address3) + release_ip(address) + release_ip(address2) + release_ip(address3) + for instance_id in instance_ids: + db.instance_destroy(None, instance_id) + release_ip(first) + self.network.deallocate_fixed_ip(self.context, first) def test_vpn_ip_and_port_looks_valid(self): """Ensure the vpn ip and port are reasonable""" self.assert_(self.projects[0].vpn_ip) - self.assert_(self.projects[0].vpn_port >= FLAGS.vpn_start_port) - self.assert_(self.projects[0].vpn_port <= FLAGS.vpn_end_port) - - def test_too_many_vpns(self): - """Ensure error is raised if we run out of vpn ports""" - vpns = [] - for i in xrange(vpn.NetworkData.num_ports_for_ip(FLAGS.vpn_ip)): - vpns.append(vpn.NetworkData.create("vpnuser%s" % i)) - self.assertRaises(vpn.NoMorePorts, vpn.NetworkData.create, "boom") - for network_datum in vpns: - network_datum.destroy() + self.assert_(self.projects[0].vpn_port >= FLAGS.vpn_start) + self.assert_(self.projects[0].vpn_port <= FLAGS.vpn_start + + FLAGS.num_networks) + + def test_too_many_networks(self): + """Ensure error is raised if we run out of networks""" + projects = [] + networks_left = FLAGS.num_networks - db.network_count(None) + for i in range(networks_left): + project = self.manager.create_project('many%s' % i, self.user) + projects.append(project) + self.assertRaises(db.NoMoreNetworks, + self.manager.create_project, + 'boom', + self.user) + for project in projects: + self.manager.delete_project(project) def test_ips_are_reused(self): """Makes sure that ip addresses that are deallocated get reused""" - net = model.get_project_network(self.projects[0].id, "default") - - hostname = "reuse-host" - macs = {} - addresses = {} - num_available_ips = net.num_available_ips - for i in range(num_available_ips - 1): - result = self.service.allocate_fixed_ip(self.user.id, - self.projects[0].id) - macs[i] = result['mac_address'] - addresses[i] = result['private_dns_name'] - issue_ip(macs[i], addresses[i], hostname, net.bridge_name) - - result = self.service.allocate_fixed_ip(self.user.id, - self.projects[0].id) - mac = result['mac_address'] - address = result['private_dns_name'] - - issue_ip(mac, address, hostname, net.bridge_name) - self.service.deallocate_fixed_ip(address) - release_ip(mac, address, hostname, net.bridge_name) - - result = self.service.allocate_fixed_ip( - self.user, self.projects[0].id) - secondmac = result['mac_address'] - secondaddress = result['private_dns_name'] - self.assertEqual(address, secondaddress) - issue_ip(secondmac, secondaddress, hostname, net.bridge_name) - self.service.deallocate_fixed_ip(secondaddress) - release_ip(secondmac, secondaddress, hostname, net.bridge_name) - - for i in range(len(addresses)): - self.service.deallocate_fixed_ip(addresses[i]) - release_ip(macs[i], addresses[i], hostname, net.bridge_name) + address = self._create_address(0) + lease_ip(address) + self.network.deallocate_fixed_ip(self.context, address) + release_ip(address) + + address2 = self._create_address(0) + self.assertEqual(address, address2) + self.network.deallocate_fixed_ip(self.context, address2) def test_available_ips(self): """Make sure the number of available ips for the network is correct @@ -230,43 +226,53 @@ class NetworkTestCase(test.TrialTestCase): There are ips reserved at the bottom and top of the range. services (network, gateway, CloudPipe, broadcast) """ - net = model.get_project_network(self.projects[0].id, "default") - num_preallocated_ips = len(net.assigned) + network = db.project_get_network(None, self.projects[0].id) net_size = flags.FLAGS.network_size - num_available_ips = net_size - (net.num_bottom_reserved_ips + - num_preallocated_ips + - net.num_top_reserved_ips) - self.assertEqual(num_available_ips, net.num_available_ips) + total_ips = (db.network_count_available_ips(None, network['id']) + + db.network_count_reserved_ips(None, network['id']) + + db.network_count_allocated_ips(None, network['id'])) + self.assertEqual(total_ips, net_size) def test_too_many_addresses(self): """Test for a NoMoreAddresses exception when all fixed ips are used. """ - net = model.get_project_network(self.projects[0].id, "default") - - hostname = "toomany-hosts" - macs = {} - addresses = {} - num_available_ips = net.num_available_ips + network = db.project_get_network(None, self.projects[0].id) + num_available_ips = db.network_count_available_ips(None, + network['id']) + addresses = [] + instance_ids = [] for i in range(num_available_ips): - result = self.service.allocate_fixed_ip(self.user.id, - self.projects[0].id) - macs[i] = result['mac_address'] - addresses[i] = result['private_dns_name'] - issue_ip(macs[i], addresses[i], hostname, net.bridge_name) + mac = utils.generate_mac() + instance_ref = db.instance_create(None, + {'mac_address': mac}) + instance_ids.append(instance_ref['id']) + address = self._create_address(0, instance_ref['id']) + addresses.append(address) + lease_ip(address) + + self.assertEqual(db.network_count_available_ips(None, + network['id']), 0) + self.assertRaises(db.NoMoreAddresses, + self.network.allocate_fixed_ip, + self.context, + 'foo') - self.assertEqual(net.num_available_ips, 0) - self.assertRaises(NoMoreAddresses, self.service.allocate_fixed_ip, - self.user.id, self.projects[0].id) - - for i in range(len(addresses)): - self.service.deallocate_fixed_ip(addresses[i]) - release_ip(macs[i], addresses[i], hostname, net.bridge_name) - self.assertEqual(net.num_available_ips, num_available_ips) + for i in range(num_available_ips): + self.network.deallocate_fixed_ip(self.context, addresses[i]) + release_ip(addresses[i]) + db.instance_destroy(None, instance_ids[i]) + self.assertEqual(db.network_count_available_ips(None, + network['id']), + num_available_ips) -def is_in_project(address, project_id): +def is_allocated_in_project(address, project_id): """Returns true if address is in specified project""" - return address in model.get_project_network(project_id).assigned + project_net = db.project_get_network(None, project_id) + network = db.fixed_ip_get_network(None, address) + instance = db.fixed_ip_get_instance(None, address) + # instance exists until release + return instance is not None and network['id'] == project_net['id'] def binpath(script): @@ -274,22 +280,28 @@ def binpath(script): return os.path.abspath(os.path.join(__file__, "../../../bin", script)) -def issue_ip(mac, private_ip, hostname, interface): +def lease_ip(private_ip): """Run add command on dhcpbridge""" - cmd = "%s add %s %s %s" % (binpath('nova-dhcpbridge'), - mac, private_ip, hostname) - env = {'DNSMASQ_INTERFACE': interface, + network_ref = db.fixed_ip_get_network(None, private_ip) + instance_ref = db.fixed_ip_get_instance(None, private_ip) + cmd = "%s add %s %s fake" % (binpath('nova-dhcpbridge'), + instance_ref['mac_address'], + private_ip) + env = {'DNSMASQ_INTERFACE': network_ref['bridge'], 'TESTING': '1', 'FLAGFILE': FLAGS.dhcpbridge_flagfile} (out, err) = utils.execute(cmd, addl_env=env) logging.debug("ISSUE_IP: %s, %s ", out, err) -def release_ip(mac, private_ip, hostname, interface): +def release_ip(private_ip): """Run del command on dhcpbridge""" - cmd = "%s del %s %s %s" % (binpath('nova-dhcpbridge'), - mac, private_ip, hostname) - env = {'DNSMASQ_INTERFACE': interface, + network_ref = db.fixed_ip_get_network(None, private_ip) + instance_ref = db.fixed_ip_get_instance(None, private_ip) + cmd = "%s del %s %s fake" % (binpath('nova-dhcpbridge'), + instance_ref['mac_address'], + private_ip) + env = {'DNSMASQ_INTERFACE': network_ref['bridge'], 'TESTING': '1', 'FLAGFILE': FLAGS.dhcpbridge_flagfile} (out, err) = utils.execute(cmd, addl_env=env) diff --git a/nova/tests/real_flags.py b/nova/tests/real_flags.py index 121f4eb41..71da04992 100644 --- a/nova/tests/real_flags.py +++ b/nova/tests/real_flags.py @@ -21,7 +21,6 @@ from nova import flags FLAGS = flags.FLAGS FLAGS.connection_type = 'libvirt' -FLAGS.fake_storage = False FLAGS.fake_rabbit = False FLAGS.fake_network = False FLAGS.verbose = False diff --git a/nova/tests/service_unittest.py b/nova/tests/service_unittest.py new file mode 100644 index 000000000..01da0eb8a --- /dev/null +++ b/nova/tests/service_unittest.py @@ -0,0 +1,182 @@ +# 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. + +""" +Unit Tests for remote procedure calls using queue +""" + +import mox + +from nova import exception +from nova import flags +from nova import rpc +from nova import test +from nova import service +from nova import manager + +FLAGS = flags.FLAGS +flags.DEFINE_string("fake_manager", "nova.tests.service_unittest.FakeManager", + "Manager for testing") + + +class FakeManager(manager.Manager): + """Fake manager for tests""" + pass + + +class ServiceTestCase(test.BaseTestCase): + """Test cases for rpc""" + + def setUp(self): # pylint: disable=C0103 + super(ServiceTestCase, self).setUp() + self.mox.StubOutWithMock(service, 'db') + + def test_create(self): + host = 'foo' + binary = 'nova-fake' + topic = 'fake' + self.mox.StubOutWithMock(rpc, + 'AdapterConsumer', + use_mock_anything=True) + self.mox.StubOutWithMock( + service.task, 'LoopingCall', use_mock_anything=True) + rpc.AdapterConsumer(connection=mox.IgnoreArg(), + topic=topic, + proxy=mox.IsA(service.Service)).AndReturn( + rpc.AdapterConsumer) + + rpc.AdapterConsumer(connection=mox.IgnoreArg(), + topic='%s.%s' % (topic, host), + proxy=mox.IsA(service.Service)).AndReturn( + rpc.AdapterConsumer) + + # Stub out looping call a bit needlessly since we don't have an easy + # way to cancel it (yet) when the tests finishes + service.task.LoopingCall(mox.IgnoreArg()).AndReturn( + service.task.LoopingCall) + service.task.LoopingCall.start(interval=mox.IgnoreArg(), + now=mox.IgnoreArg()) + + rpc.AdapterConsumer.attach_to_twisted() + rpc.AdapterConsumer.attach_to_twisted() + service_create = {'host': host, + 'binary': binary, + 'topic': topic, + 'report_count': 0} + service_ref = {'host': host, + 'binary': binary, + 'report_count': 0, + 'id': 1} + + service.db.service_get_by_args(None, + host, + binary).AndRaise(exception.NotFound()) + service.db.service_create(None, + service_create).AndReturn(service_ref) + self.mox.ReplayAll() + + app = service.Service.create(host=host, binary=binary) + self.assert_(app) + + # We're testing sort of weird behavior in how report_state decides + # whether it is disconnected, it looks for a variable on itself called + # 'model_disconnected' and report_state doesn't really do much so this + # these are mostly just for coverage + def test_report_state(self): + host = 'foo' + binary = 'bar' + service_ref = {'host': host, + 'binary': binary, + 'report_count': 0, + 'id': 1} + service.db.__getattr__('report_state') + service.db.service_get_by_args(None, + host, + binary).AndReturn(service_ref) + service.db.service_update(None, service_ref['id'], + mox.ContainsKeyValue('report_count', 1)) + + self.mox.ReplayAll() + s = service.Service() + rv = yield s.report_state(host, binary) + + def test_report_state_no_service(self): + host = 'foo' + binary = 'bar' + service_create = {'host': host, + 'binary': binary, + 'report_count': 0} + service_ref = {'host': host, + 'binary': binary, + 'report_count': 0, + 'id': 1} + + service.db.__getattr__('report_state') + service.db.service_get_by_args(None, + host, + binary).AndRaise(exception.NotFound()) + service.db.service_create(None, + service_create).AndReturn(service_ref) + service.db.service_get(None, service_ref['id']).AndReturn(service_ref) + service.db.service_update(None, service_ref['id'], + mox.ContainsKeyValue('report_count', 1)) + + self.mox.ReplayAll() + s = service.Service() + rv = yield s.report_state(host, binary) + + def test_report_state_newly_disconnected(self): + host = 'foo' + binary = 'bar' + service_ref = {'host': host, + 'binary': binary, + 'report_count': 0, + 'id': 1} + + service.db.__getattr__('report_state') + service.db.service_get_by_args(None, + host, + binary).AndRaise(Exception()) + + self.mox.ReplayAll() + s = service.Service() + rv = yield s.report_state(host, binary) + + self.assert_(s.model_disconnected) + + def test_report_state_newly_connected(self): + host = 'foo' + binary = 'bar' + service_ref = {'host': host, + 'binary': binary, + 'report_count': 0, + 'id': 1} + + service.db.__getattr__('report_state') + service.db.service_get_by_args(None, + host, + binary).AndReturn(service_ref) + service.db.service_update(None, service_ref['id'], + mox.ContainsKeyValue('report_count', 1)) + + self.mox.ReplayAll() + s = service.Service() + s.model_disconnected = True + rv = yield s.report_state(host, binary) + + self.assert_(not s.model_disconnected) diff --git a/nova/tests/storage_unittest.py b/nova/tests/storage_unittest.py deleted file mode 100644 index f400cd2fd..000000000 --- a/nova/tests/storage_unittest.py +++ /dev/null @@ -1,115 +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. - -import logging - -from nova import exception -from nova import flags -from nova import test -from nova.compute import node -from nova.volume import storage - - -FLAGS = flags.FLAGS - - -class StorageTestCase(test.TrialTestCase): - def setUp(self): - logging.getLogger().setLevel(logging.DEBUG) - super(StorageTestCase, self).setUp() - self.mynode = node.Node() - self.mystorage = None - self.flags(connection_type='fake', - fake_storage=True) - self.mystorage = storage.BlockStore() - - def test_run_create_volume(self): - vol_size = '0' - user_id = 'fake' - project_id = 'fake' - volume_id = self.mystorage.create_volume(vol_size, user_id, project_id) - # TODO(termie): get_volume returns differently than create_volume - self.assertEqual(volume_id, - storage.get_volume(volume_id)['volume_id']) - - rv = self.mystorage.delete_volume(volume_id) - self.assertRaises(exception.Error, - storage.get_volume, - volume_id) - - def test_too_big_volume(self): - vol_size = '1001' - user_id = 'fake' - project_id = 'fake' - self.assertRaises(TypeError, - self.mystorage.create_volume, - vol_size, user_id, project_id) - - def test_too_many_volumes(self): - vol_size = '1' - user_id = 'fake' - project_id = 'fake' - num_shelves = FLAGS.last_shelf_id - FLAGS.first_shelf_id + 1 - total_slots = FLAGS.slots_per_shelf * num_shelves - vols = [] - for i in xrange(total_slots): - vid = self.mystorage.create_volume(vol_size, user_id, project_id) - vols.append(vid) - self.assertRaises(storage.NoMoreVolumes, - self.mystorage.create_volume, - vol_size, user_id, project_id) - for id in vols: - self.mystorage.delete_volume(id) - - def test_run_attach_detach_volume(self): - # Create one volume and one node to test with - instance_id = "storage-test" - vol_size = "5" - user_id = "fake" - project_id = 'fake' - mountpoint = "/dev/sdf" - volume_id = self.mystorage.create_volume(vol_size, user_id, project_id) - - volume_obj = storage.get_volume(volume_id) - volume_obj.start_attach(instance_id, mountpoint) - rv = yield self.mynode.attach_volume(volume_id, - instance_id, - mountpoint) - self.assertEqual(volume_obj['status'], "in-use") - self.assertEqual(volume_obj['attachStatus'], "attached") - self.assertEqual(volume_obj['instance_id'], instance_id) - self.assertEqual(volume_obj['mountpoint'], mountpoint) - - self.assertRaises(exception.Error, - self.mystorage.delete_volume, - volume_id) - - rv = yield self.mystorage.detach_volume(volume_id) - volume_obj = storage.get_volume(volume_id) - self.assertEqual(volume_obj['status'], "available") - - rv = self.mystorage.delete_volume(volume_id) - self.assertRaises(exception.Error, - storage.get_volume, - volume_id) - - def test_multi_node(self): - # TODO(termie): Figure out how to test with two nodes, - # each of them having a different FLAG for storage_node - # This will allow us to test cross-node interactions - pass diff --git a/nova/tests/volume_unittest.py b/nova/tests/volume_unittest.py index 540b71585..1d665b502 100644 --- a/nova/tests/volume_unittest.py +++ b/nova/tests/volume_unittest.py @@ -15,149 +15,159 @@ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. - +""" +Tests for Volume Code +""" import logging -import shutil -import tempfile from twisted.internet import defer -from nova import compute from nova import exception +from nova import db from nova import flags from nova import test -from nova.volume import service as volume_service - +from nova import utils FLAGS = flags.FLAGS class VolumeTestCase(test.TrialTestCase): - def setUp(self): + """Test Case for volumes""" + def setUp(self): # pylint: disable-msg=C0103 logging.getLogger().setLevel(logging.DEBUG) super(VolumeTestCase, self).setUp() - self.compute = compute.service.ComputeService() - self.volume = None - self.tempdir = tempfile.mkdtemp() - self.flags(connection_type='fake', - fake_storage=True, - aoe_export_dir=self.tempdir) - self.volume = volume_service.VolumeService() - - def tearDown(self): - shutil.rmtree(self.tempdir) + self.compute = utils.import_object(FLAGS.compute_manager) + self.flags(connection_type='fake') + self.volume = utils.import_object(FLAGS.volume_manager) + self.context = None + + @staticmethod + def _create_volume(size='0'): + """Create a volume object""" + vol = {} + vol['size'] = size + vol['user_id'] = 'fake' + vol['project_id'] = 'fake' + vol['availability_zone'] = FLAGS.storage_availability_zone + vol['status'] = "creating" + vol['attach_status'] = "detached" + return db.volume_create(None, vol)['id'] @defer.inlineCallbacks - def test_run_create_volume(self): - vol_size = '0' - user_id = 'fake' - project_id = 'fake' - volume_id = yield self.volume.create_volume(vol_size, user_id, project_id) - # TODO(termie): get_volume returns differently than create_volume - self.assertEqual(volume_id, - volume_service.get_volume(volume_id)['volume_id']) - - rv = self.volume.delete_volume(volume_id) - self.assertRaises(exception.Error, volume_service.get_volume, volume_id) + def test_create_delete_volume(self): + """Test volume can be created and deleted""" + volume_id = self._create_volume() + yield self.volume.create_volume(self.context, volume_id) + self.assertEqual(volume_id, db.volume_get(None, volume_id).id) + + yield self.volume.delete_volume(self.context, volume_id) + self.assertRaises(exception.NotFound, + db.volume_get, + None, + volume_id) @defer.inlineCallbacks def test_too_big_volume(self): - vol_size = '1001' - user_id = 'fake' - project_id = 'fake' + """Ensure failure if a too large of a volume is requested""" + # FIXME(vish): validation needs to move into the data layer in + # volume_create + defer.returnValue(True) try: - yield self.volume.create_volume(vol_size, user_id, project_id) + volume_id = self._create_volume('1001') + yield self.volume.create_volume(self.context, volume_id) self.fail("Should have thrown TypeError") except TypeError: pass @defer.inlineCallbacks def test_too_many_volumes(self): - vol_size = '1' - user_id = 'fake' - project_id = 'fake' - num_shelves = FLAGS.last_shelf_id - FLAGS.first_shelf_id + 1 - total_slots = FLAGS.blades_per_shelf * num_shelves + """Ensure that NoMoreBlades is raised when we run out of volumes""" vols = [] - from nova import datastore - redis = datastore.Redis.instance() - for i in xrange(total_slots): - vid = yield self.volume.create_volume(vol_size, user_id, project_id) - vols.append(vid) - self.assertFailure(self.volume.create_volume(vol_size, - user_id, - project_id), - volume_service.NoMoreBlades) - for id in vols: - yield self.volume.delete_volume(id) + total_slots = FLAGS.num_shelves * FLAGS.blades_per_shelf + for _index in xrange(total_slots): + volume_id = self._create_volume() + yield self.volume.create_volume(self.context, volume_id) + vols.append(volume_id) + volume_id = self._create_volume() + self.assertFailure(self.volume.create_volume(self.context, + volume_id), + db.NoMoreBlades) + db.volume_destroy(None, volume_id) + for volume_id in vols: + yield self.volume.delete_volume(self.context, volume_id) @defer.inlineCallbacks def test_run_attach_detach_volume(self): - # Create one volume and one compute to test with - instance_id = "storage-test" - vol_size = "5" - user_id = "fake" - project_id = 'fake' + """Make sure volume can be attached and detached from instance""" + inst = {} + inst['image_id'] = 'ami-test' + inst['reservation_id'] = 'r-fakeres' + inst['launch_time'] = '10' + inst['user_id'] = 'fake' + inst['project_id'] = 'fake' + inst['instance_type'] = 'm1.tiny' + inst['mac_address'] = utils.generate_mac() + inst['ami_launch_index'] = 0 + instance_id = db.instance_create(self.context, inst)['id'] mountpoint = "/dev/sdf" - volume_id = yield self.volume.create_volume(vol_size, user_id, project_id) - volume_obj = volume_service.get_volume(volume_id) - volume_obj.start_attach(instance_id, mountpoint) + volume_id = self._create_volume() + yield self.volume.create_volume(self.context, volume_id) if FLAGS.fake_tests: - volume_obj.finish_attach() + db.volume_attached(None, volume_id, instance_id, mountpoint) else: - rv = yield self.compute.attach_volume(instance_id, - volume_id, - mountpoint) - self.assertEqual(volume_obj['status'], "in-use") - self.assertEqual(volume_obj['attach_status'], "attached") - self.assertEqual(volume_obj['instance_id'], instance_id) - self.assertEqual(volume_obj['mountpoint'], mountpoint) - - self.assertFailure(self.volume.delete_volume(volume_id), exception.Error) - volume_obj.start_detach() + yield self.compute.attach_volume(instance_id, + volume_id, + mountpoint) + vol = db.volume_get(None, volume_id) + self.assertEqual(vol['status'], "in-use") + self.assertEqual(vol['attach_status'], "attached") + self.assertEqual(vol['mountpoint'], mountpoint) + instance_ref = db.volume_get_instance(self.context, volume_id) + self.assertEqual(instance_ref['id'], instance_id) + + self.assertFailure(self.volume.delete_volume(self.context, volume_id), + exception.Error) if FLAGS.fake_tests: - volume_obj.finish_detach() + db.volume_detached(None, volume_id) else: - rv = yield self.volume.detach_volume(instance_id, - volume_id) - volume_obj = volume_service.get_volume(volume_id) - self.assertEqual(volume_obj['status'], "available") + yield self.compute.detach_volume(instance_id, + volume_id) + vol = db.volume_get(None, volume_id) + self.assertEqual(vol['status'], "available") - rv = self.volume.delete_volume(volume_id) + yield self.volume.delete_volume(self.context, volume_id) self.assertRaises(exception.Error, - volume_service.get_volume, + db.volume_get, + None, volume_id) + db.instance_destroy(self.context, instance_id) - def test_multiple_volume_race_condition(self): - vol_size = "5" - user_id = "fake" - project_id = 'fake' + @defer.inlineCallbacks + def test_concurrent_volumes_get_different_blades(self): + """Ensure multiple concurrent volumes get different blades""" + volume_ids = [] shelf_blades = [] + def _check(volume_id): - vol = volume_service.get_volume(volume_id) - shelf_blade = '%s.%s' % (vol['shelf_id'], vol['blade_id']) - self.assertTrue(shelf_blade not in shelf_blades, - "Same shelf/blade tuple came back twice") + """Make sure blades aren't duplicated""" + volume_ids.append(volume_id) + (shelf_id, blade_id) = db.volume_get_shelf_and_blade(None, + volume_id) + shelf_blade = '%s.%s' % (shelf_id, blade_id) + self.assert_(shelf_blade not in shelf_blades) shelf_blades.append(shelf_blade) - logging.debug("got %s" % shelf_blade) - return vol + logging.debug("Blade %s allocated", shelf_blade) deferreds = [] - for i in range(5): - d = self.volume.create_volume(vol_size, user_id, project_id) + total_slots = FLAGS.num_shelves * FLAGS.blades_per_shelf + for _index in xrange(total_slots): + volume_id = self._create_volume() + d = self.volume.create_volume(self.context, volume_id) d.addCallback(_check) d.addErrback(self.fail) deferreds.append(d) - def destroy_volumes(retvals): - overall_succes = True - for success, volume in retvals: - if not success: - overall_succes = False - else: - volume.destroy() - self.assertTrue(overall_succes) - d = defer.DeferredList(deferreds) - d.addCallback(destroy_volumes) - return d + yield defer.DeferredList(deferreds) + for volume_id in volume_ids: + self.volume.delete_volume(self.context, volume_id) def test_multi_node(self): # TODO(termie): Figure out how to test with two nodes, diff --git a/nova/utils.py b/nova/utils.py index ef8405fc0..011a5cb09 100644 --- a/nova/utils.py +++ b/nova/utils.py @@ -38,6 +38,16 @@ from nova import flags FLAGS = flags.FLAGS TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ" +class ProcessExecutionError(IOError): + def __init__( self, stdout=None, stderr=None, exit_code=None, cmd=None, + description=None): + if description is None: + description = "Unexpected error while running command." + if exit_code is None: + exit_code = '-' + message = "%s\nCommand: %s\nExit code: %s\nStdout: %r\nStderr: %r" % ( + description, cmd, exit_code, stdout, stderr) + IOError.__init__(self, message) def import_class(import_str): """Returns a class from a string including module and class""" @@ -48,6 +58,14 @@ def import_class(import_str): except (ImportError, ValueError, AttributeError): raise exception.NotFound('Class %s cannot be found' % class_str) +def import_object(import_str): + """Returns an object including a module or module and class""" + try: + __import__(import_str) + return sys.modules[import_str] + except ImportError: + cls = import_class(import_str) + return cls() def fetchfile(url, target): logging.debug("Fetching %s" % url) @@ -61,6 +79,7 @@ def fetchfile(url, target): execute("curl --fail %s -o %s" % (url, target)) def execute(cmd, process_input=None, addl_env=None, check_exit_code=True): + logging.debug("Running cmd: %s", cmd) env = os.environ.copy() if addl_env: env.update(addl_env) @@ -75,8 +94,11 @@ def execute(cmd, process_input=None, addl_env=None, check_exit_code=True): if obj.returncode: logging.debug("Result was %s" % (obj.returncode)) if check_exit_code and obj.returncode <> 0: - raise Exception( "Unexpected exit code: %s. result=%s" - % (obj.returncode, result)) + (stdout, stderr) = result + raise ProcessExecutionError(exit_code=obj.returncode, + stdout=stdout, + stderr=stderr, + cmd=cmd) return result @@ -107,7 +129,7 @@ def runthis(prompt, cmd, check_exit_code = True): exit_code = subprocess.call(cmd.split(" ")) logging.debug(prompt % (exit_code)) if check_exit_code and exit_code <> 0: - raise Exception( "Unexpected exit code: %s from cmd: %s" + raise Exception( "Unexpected exit code: %s from cmd: %s" % (exit_code, cmd)) @@ -127,8 +149,7 @@ def last_octet(address): def get_my_ip(): - ''' returns the actual ip of the local machine. - ''' + """Returns the actual ip of the local machine.""" if getattr(FLAGS, 'fake_tests', None): return '127.0.0.1' try: @@ -152,6 +173,36 @@ def parse_isotime(timestr): return datetime.datetime.strptime(timestr, TIME_FORMAT) +class LazyPluggable(object): + """A pluggable backend loaded lazily based on some value.""" + + def __init__(self, pivot, **backends): + self.__backends = backends + self.__pivot = pivot + self.__backend = None + + def __get_backend(self): + if not self.__backend: + backend_name = self.__pivot.value + if backend_name not in self.__backends: + raise exception.Error('Invalid backend: %s' % backend_name) + + backend = self.__backends[backend_name] + if type(backend) == type(tuple()): + name = backend[0] + fromlist = backend[1] + else: + name = backend + fromlist = backend + + self.__backend = __import__(name, None, None, fromlist) + logging.info('backend %s', self.__backend) + return self.__backend + + def __getattr__(self, key): + backend = self.__get_backend() + return getattr(backend, key) + def deferredToThread(f): def g(*args, **kwargs): return deferToThread(f, *args, **kwargs) diff --git a/nova/virt/fake.py b/nova/virt/fake.py index 155833f3f..4ae6afcc4 100644 --- a/nova/virt/fake.py +++ b/nova/virt/fake.py @@ -39,12 +39,12 @@ class FakeConnection(object): The interface to this class talks in terms of 'instances' (Amazon EC2 and internal Nova terminology), by which we mean 'running virtual machine' (XenAPI terminology) or domain (Xen or libvirt terminology). - + An instance has an ID, which is the identifier chosen by Nova to represent the instance further up the stack. This is unfortunately also called a 'name' elsewhere. As far as this layer is concerned, 'instance ID' and 'instance name' are synonyms. - + Note that the instance ID or name is not human-readable or customer-controlled -- it's an internal ID chosen by Nova. At the nova.virt layer, instances do not have human-readable names at all -- such @@ -101,7 +101,7 @@ class FakeConnection(object): cleaned up, and the virtualization platform should be in the state that it was before this call began. """ - + fake_instance = FakeInstance() self.instances[instance.name] = fake_instance fake_instance._state = power_state.RUNNING @@ -132,7 +132,15 @@ class FakeConnection(object): del self.instances[instance.name] return defer.succeed(None) - def get_info(self, instance_id): + def attach_volume(self, instance_name, device_path, mountpoint): + """Attach the disk at device_path to the instance at mountpoint""" + return True + + def detach_volume(self, instance_name, mountpoint): + """Detach the disk attached to the instance at mountpoint""" + return True + + def get_info(self, instance_name): """ Get a block of information about the given instance. This is returned as a dictionary containing 'state': The power_state of the instance, @@ -141,42 +149,42 @@ class FakeConnection(object): of virtual CPUs the instance has, 'cpu_time': The total CPU time used by the instance, in nanoseconds. """ - i = self.instances[instance_id] + i = self.instances[instance_name] return {'state': i._state, 'max_mem': 0, 'mem': 0, 'num_cpu': 2, 'cpu_time': 0} - def list_disks(self, instance_id): + def list_disks(self, instance_name): """ Return the IDs of all the virtual disks attached to the specified instance, as a list. These IDs are opaque to the caller (they are only useful for giving back to this layer as a parameter to disk_stats). These IDs only need to be unique for a given instance. - + Note that this function takes an instance ID, not a compute.service.Instance, so that it can be called by compute.monitor. """ return ['A_DISK'] - def list_interfaces(self, instance_id): + def list_interfaces(self, instance_name): """ Return the IDs of all the virtual network interfaces attached to the specified instance, as a list. These IDs are opaque to the caller (they are only useful for giving back to this layer as a parameter to interface_stats). These IDs only need to be unique for a given instance. - + Note that this function takes an instance ID, not a compute.service.Instance, so that it can be called by compute.monitor. """ return ['A_VIF'] - def block_stats(self, instance_id, disk_id): + def block_stats(self, instance_name, disk_id): """ Return performance counters associated with the given disk_id on the - given instance_id. These are returned as [rd_req, rd_bytes, wr_req, + given instance_name. These are returned as [rd_req, rd_bytes, wr_req, wr_bytes, errs], where rd indicates read, wr indicates write, req is the total number of I/O requests made, bytes is the total number of bytes transferred, and errs is the number of requests held up due to a @@ -188,13 +196,13 @@ class FakeConnection(object): statistics can be retrieved directly in aggregate form, without Nova having to do the aggregation. On those platforms, this method is unused. - + Note that this function takes an instance ID, not a compute.service.Instance, so that it can be called by compute.monitor. """ return [0L, 0L, 0L, 0L, null] - def interface_stats(self, instance_id, iface_id): + def interface_stats(self, instance_name, iface_id): """ Return performance counters associated with the given iface_id on the given instance_id. These are returned as [rx_bytes, rx_packets, @@ -209,7 +217,7 @@ class FakeConnection(object): statistics can be retrieved directly in aggregate form, without Nova having to do the aggregation. On those platforms, this method is unused. - + Note that this function takes an instance ID, not a compute.service.Instance, so that it can be called by compute.monitor. """ diff --git a/nova/virt/libvirt.qemu.xml.template b/nova/virt/libvirt.qemu.xml.template index 307f9d03a..17bd79b7c 100644 --- a/nova/virt/libvirt.qemu.xml.template +++ b/nova/virt/libvirt.qemu.xml.template @@ -1,7 +1,7 @@ <domain type='%(type)s'> <name>%(name)s</name> <os> - <type>hvm</type> + <type>hvm</type> <kernel>%(basepath)s/kernel</kernel> <initrd>%(basepath)s/ramdisk</initrd> <cmdline>root=/dev/vda1 console=ttyS0</cmdline> @@ -26,5 +26,4 @@ <target port='1'/> </serial> </devices> - <nova>%(nova)s</nova> </domain> diff --git a/nova/virt/libvirt.uml.xml.template b/nova/virt/libvirt.uml.xml.template index a72a6b8c3..c039d6d90 100644 --- a/nova/virt/libvirt.uml.xml.template +++ b/nova/virt/libvirt.uml.xml.template @@ -19,5 +19,4 @@ <source path='%(basepath)s/console.log'/> </console> </devices> - <nova>%(nova)s</nova> </domain> diff --git a/nova/virt/libvirt_conn.py b/nova/virt/libvirt_conn.py index bfab59369..d868e083c 100644 --- a/nova/virt/libvirt_conn.py +++ b/nova/virt/libvirt_conn.py @@ -21,7 +21,6 @@ A connection to a hypervisor (e.g. KVM) through libvirt. """ -import json import logging import os import shutil @@ -29,6 +28,7 @@ import shutil from twisted.internet import defer from twisted.internet import task +from nova import db from nova import exception from nova import flags from nova import process @@ -125,9 +125,9 @@ class LibvirtConnection(object): def destroy(self, instance): try: - virt_dom = self._conn.lookupByName(instance.name) + virt_dom = self._conn.lookupByName(instance['name']) virt_dom.destroy() - except Exception, _err: + except Exception as _err: pass # If the instance is already terminated, we're still happy d = defer.Deferred() @@ -139,12 +139,15 @@ class LibvirtConnection(object): timer = task.LoopingCall(f=None) def _wait_for_shutdown(): try: - instance.update_state() - if instance.state == power_state.SHUTDOWN: + state = self.get_info(instance['name'])['state'] + db.instance_set_state(None, instance['id'], state) + if state == power_state.SHUTDOWN: timer.stop() d.callback(None) except Exception: - instance.set_state(power_state.SHUTDOWN) + db.instance_set_state(None, + instance['id'], + power_state.SHUTDOWN) timer.stop() d.callback(None) timer.f = _wait_for_shutdown @@ -152,30 +155,51 @@ class LibvirtConnection(object): return d def _cleanup(self, instance): - target = os.path.abspath(instance.datamodel['basepath']) - logging.info("Deleting instance files at %s", target) + target = os.path.join(FLAGS.instances_path, instance['name']) + logging.info('instance %s: deleting instance files %s', + instance['name'], target) if os.path.exists(target): shutil.rmtree(target) @defer.inlineCallbacks @exception.wrap_exception + def attach_volume(self, instance_name, device_path, mountpoint): + yield process.simple_execute("sudo virsh attach-disk %s %s %s" % + (instance_name, + device_path, + mountpoint.rpartition('/dev/')[2])) + + @defer.inlineCallbacks + @exception.wrap_exception + def detach_volume(self, instance_name, mountpoint): + # NOTE(vish): despite the documentation, virsh detach-disk just + # wants the device name without the leading /dev/ + yield process.simple_execute("sudo virsh detach-disk %s %s" % + (instance_name, + mountpoint.rpartition('/dev/')[2])) + + @defer.inlineCallbacks + @exception.wrap_exception def reboot(self, instance): - xml = self.toXml(instance) - yield self._conn.lookupByName(instance.name).destroy() + xml = self.to_xml(instance) + yield self._conn.lookupByName(instance['name']).destroy() yield self._conn.createXML(xml, 0) d = defer.Deferred() timer = task.LoopingCall(f=None) def _wait_for_reboot(): try: - instance.update_state() - if instance.is_running(): - logging.debug('rebooted instance %s' % instance.name) + state = self.get_info(instance['name'])['state'] + db.instance_set_state(None, instance['id'], state) + if state == power_state.RUNNING: + logging.debug('instance %s: rebooted', instance['name']) timer.stop() d.callback(None) except Exception, exn: - logging.error('_wait_for_reboot failed: %s' % exn) - instance.set_state(power_state.SHUTDOWN) + logging.error('_wait_for_reboot failed: %s', exn) + db.instance_set_state(None, + instance['id'], + power_state.SHUTDOWN) timer.stop() d.callback(None) timer.f = _wait_for_reboot @@ -185,27 +209,33 @@ class LibvirtConnection(object): @defer.inlineCallbacks @exception.wrap_exception def spawn(self, instance): - xml = self.toXml(instance) - instance.set_state(power_state.NOSTATE, 'launching') + xml = self.to_xml(instance) + db.instance_set_state(None, + instance['id'], + power_state.NOSTATE, + 'launching') yield self._create_image(instance, xml) yield self._conn.createXML(xml, 0) # TODO(termie): this should actually register # a callback to check for successful boot - logging.debug("Instance is running") + logging.debug("instance %s: is running", instance['name']) local_d = defer.Deferred() timer = task.LoopingCall(f=None) def _wait_for_boot(): try: - instance.update_state() - if instance.is_running(): - logging.debug('booted instance %s' % instance.name) + state = self.get_info(instance['name'])['state'] + db.instance_set_state(None, instance['id'], state) + if state == power_state.RUNNING: + logging.debug('instance %s: booted', instance['name']) timer.stop() local_d.callback(None) - except Exception, exn: - logging.error("_wait_for_boot exception %s" % exn) - self.set_state(power_state.SHUTDOWN) - logging.error('Failed to boot instance %s' % instance.name) + except: + logging.exception('instance %s: failed to boot', + instance['name']) + db.instance_set_state(None, + instance['id'], + power_state.SHUTDOWN) timer.stop() local_d.callback(None) timer.f = _wait_for_boot @@ -213,10 +243,11 @@ class LibvirtConnection(object): yield local_d @defer.inlineCallbacks - def _create_image(self, instance, libvirt_xml): + def _create_image(self, inst, libvirt_xml): # syntactic nicety - data = instance.datamodel - basepath = lambda x='': self.basepath(instance, x) + basepath = lambda fname='': os.path.join(FLAGS.instances_path, + inst['name'], + fname) # ensure directories exist and are writable yield process.simple_execute('mkdir -p %s' % basepath()) @@ -225,71 +256,82 @@ class LibvirtConnection(object): # TODO(termie): these are blocking calls, it would be great # if they weren't. - logging.info('Creating image for: %s', data['instance_id']) + logging.info('instance %s: Creating image', inst['name']) f = open(basepath('libvirt.xml'), 'w') f.write(libvirt_xml) f.close() os.close(os.open(basepath('console.log'), os.O_CREAT | os.O_WRONLY, 0660)) - user = manager.AuthManager().get_user(data['user_id']) - project = manager.AuthManager().get_project(data['project_id']) + user = manager.AuthManager().get_user(inst['user_id']) + project = manager.AuthManager().get_project(inst['project_id']) + if not os.path.exists(basepath('disk')): - yield images.fetch(data['image_id'], basepath('disk-raw'), user, project) + yield images.fetch(inst.image_id, basepath('disk-raw'), user, project) if not os.path.exists(basepath('kernel')): - yield images.fetch(data['kernel_id'], basepath('kernel'), user, project) + yield images.fetch(inst.kernel_id, basepath('kernel'), user, project) if not os.path.exists(basepath('ramdisk')): - yield images.fetch(data['ramdisk_id'], basepath('ramdisk'), user, project) + yield images.fetch(inst.ramdisk_id, basepath('ramdisk'), user, project) execute = lambda cmd, process_input=None: \ process.simple_execute(cmd=cmd, process_input=process_input, check_exit_code=True) - key = data['key_data'] + key = str(inst['key_data']) net = None - if data.get('inject_network', False): + network_ref = db.project_get_network(None, project.id) + if network_ref['injected']: + address = db.instance_get_fixed_address(None, inst['id']) with open(FLAGS.injected_network_template) as f: - net = f.read() % {'address': data['private_dns_name'], - 'network': data['network_network'], - 'netmask': data['network_netmask'], - 'gateway': data['network_gateway'], - 'broadcast': data['network_broadcast'], - 'dns': data['network_dns']} + net = f.read() % {'address': address, + 'network': network_ref['network'], + 'netmask': network_ref['netmask'], + 'gateway': network_ref['gateway'], + 'broadcast': network_ref['broadcast'], + 'dns': network_ref['dns']} if key or net: - logging.info('Injecting data into image %s', data['image_id']) + if key: + logging.info('instance %s: injecting key into image %s', + inst['name'], inst.image_id) + if net: + logging.info('instance %s: injecting net into image %s', + inst['name'], inst.image_id) yield disk.inject_data(basepath('disk-raw'), key, net, execute=execute) if os.path.exists(basepath('disk')): yield process.simple_execute('rm -f %s' % basepath('disk')) - bytes = (instance_types.INSTANCE_TYPES[data['instance_type']]['local_gb'] + bytes = (instance_types.INSTANCE_TYPES[inst.instance_type]['local_gb'] * 1024 * 1024 * 1024) yield disk.partition( basepath('disk-raw'), basepath('disk'), bytes, execute=execute) if FLAGS.libvirt_type == 'uml': - execute('sudo chown root %s' % (basepath('disk'),)) - - def basepath(self, instance, path=''): - return os.path.abspath(os.path.join(instance.datamodel['basepath'], path)) + yield process.simple_execute('sudo chown root %s' % + basepath('disk')) - def toXml(self, instance): + def to_xml(self, instance): # TODO(termie): cache? - logging.debug("Starting the toXML method") - xml_info = instance.datamodel.copy() - # TODO(joshua): Make this xml express the attached disks as well - - # TODO(termie): lazy lazy hack because xml is annoying - xml_info['nova'] = json.dumps(instance.datamodel.copy()) - xml_info['type'] = FLAGS.libvirt_type + logging.debug('instance %s: starting toXML method', instance['name']) + network = db.project_get_network(None, instance['project_id']) + # FIXME(vish): stick this in db + instance_type = instance_types.INSTANCE_TYPES[instance['instance_type']] + xml_info = {'type': FLAGS.libvirt_type, + 'name': instance['name'], + 'basepath': os.path.join(FLAGS.instances_path, + instance['name']), + 'memory_kb': instance_type['memory_mb'] * 1024, + 'vcpus': instance_type['vcpus'], + 'bridge_name': network['bridge'], + 'mac_address': instance['mac_address']} libvirt_xml = self.libvirt_xml % xml_info - logging.debug("Finished the toXML method") + logging.debug('instance %s: finished toXML method', instance['name']) return libvirt_xml - def get_info(self, instance_id): - virt_dom = self._conn.lookupByName(instance_id) + def get_info(self, instance_name): + virt_dom = self._conn.lookupByName(instance_name) (state, max_mem, mem, num_cpu, cpu_time) = virt_dom.info() return {'state': state, 'max_mem': max_mem, @@ -297,8 +339,14 @@ class LibvirtConnection(object): 'num_cpu': num_cpu, 'cpu_time': cpu_time} - def get_disks(self, instance_id): - domain = self._conn.lookupByName(instance_id) + def get_disks(self, instance_name): + """ + Note that this function takes an instance name, not an Instance, so + that it can be called by monitor. + + Returns a list of all block devices for this domain. + """ + domain = self._conn.lookupByName(instance_name) # TODO(devcamcar): Replace libxml2 with etree. xml = domain.XMLDesc(0) doc = None @@ -333,8 +381,14 @@ class LibvirtConnection(object): return disks - def get_interfaces(self, instance_id): - domain = self._conn.lookupByName(instance_id) + def get_interfaces(self, instance_name): + """ + Note that this function takes an instance name, not an Instance, so + that it can be called by monitor. + + Returns a list of all network interfaces for this instance. + """ + domain = self._conn.lookupByName(instance_name) # TODO(devcamcar): Replace libxml2 with etree. xml = domain.XMLDesc(0) doc = None @@ -369,10 +423,18 @@ class LibvirtConnection(object): return interfaces - def block_stats(self, instance_id, disk): - domain = self._conn.lookupByName(instance_id) + def block_stats(self, instance_name, disk): + """ + Note that this function takes an instance name, not an Instance, so + that it can be called by monitor. + """ + domain = self._conn.lookupByName(instance_name) return domain.blockStats(disk) - def interface_stats(self, instance_id, interface): - domain = self._conn.lookupByName(instance_id) + def interface_stats(self, instance_name, interface): + """ + Note that this function takes an instance name, not an Instance, so + that it can be called by monitor. + """ + domain = self._conn.lookupByName(instance_name) return domain.interfaceStats(interface) diff --git a/nova/volume/driver.py b/nova/volume/driver.py new file mode 100644 index 000000000..4604b85d5 --- /dev/null +++ b/nova/volume/driver.py @@ -0,0 +1,108 @@ +# 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. + +""" +Drivers for volumes +""" + +import logging + +from twisted.internet import defer + +from nova import flags +from nova import process + + +FLAGS = flags.FLAGS +flags.DEFINE_string('volume_group', 'nova-volumes', + 'Name for the VG that will contain exported volumes') +flags.DEFINE_string('aoe_eth_dev', 'eth0', + 'Which device to export the volumes on') + + +class AOEDriver(object): + """Executes commands relating to AOE volumes""" + def __init__(self, execute=process.simple_execute, *args, **kwargs): + self._execute = execute + + @defer.inlineCallbacks + def create_volume(self, volume_name, size): + """Creates a logical volume""" + # NOTE(vish): makes sure that the volume group exists + yield self._execute("vgs %s" % FLAGS.volume_group) + if int(size) == 0: + sizestr = '100M' + else: + sizestr = '%sG' % size + yield self._execute( + "sudo lvcreate -L %s -n %s %s" % (sizestr, + volume_name, + FLAGS.volume_group)) + + @defer.inlineCallbacks + def delete_volume(self, volume_name): + """Deletes a logical volume""" + yield self._execute( + "sudo lvremove -f %s/%s" % (FLAGS.volume_group, + volume_name)) + + @defer.inlineCallbacks + def create_export(self, volume_name, shelf_id, blade_id): + """Creates an export for a logical volume""" + yield self._execute( + "sudo vblade-persist setup %s %s %s /dev/%s/%s" % + (shelf_id, + blade_id, + FLAGS.aoe_eth_dev, + FLAGS.volume_group, + volume_name)) + + @defer.inlineCallbacks + def discover_volume(self, _volume_name): + """Discover volume on a remote host""" + yield self._execute("sudo aoe-discover") + yield self._execute("sudo aoe-stat") + + @defer.inlineCallbacks + def remove_export(self, _volume_name, shelf_id, blade_id): + """Removes an export for a logical volume""" + yield self._execute( + "sudo vblade-persist stop %s %s" % (shelf_id, blade_id)) + yield self._execute( + "sudo vblade-persist destroy %s %s" % (shelf_id, blade_id)) + + @defer.inlineCallbacks + def ensure_exports(self): + """Runs all existing exports""" + # NOTE(ja): wait for blades to appear + yield self._execute("sleep 5") + yield self._execute("sudo vblade-persist auto all", + check_exit_code=False) + yield self._execute("sudo vblade-persist start all", + check_exit_code=False) + + +class FakeAOEDriver(AOEDriver): + """Logs calls instead of executing""" + def __init__(self, *args, **kwargs): + super(FakeAOEDriver, self).__init__(self.fake_execute) + + @staticmethod + def fake_execute(cmd, *_args, **_kwargs): + """Execute that simply logs the command""" + logging.debug("FAKE AOE: %s", cmd) diff --git a/nova/volume/manager.py b/nova/volume/manager.py new file mode 100644 index 000000000..174c036d6 --- /dev/null +++ b/nova/volume/manager.py @@ -0,0 +1,131 @@ +# 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. + +""" +Volume manager manages creating, attaching, detaching, and +destroying persistent storage volumes, ala EBS. +""" + +import logging + +from twisted.internet import defer + +from nova import exception +from nova import flags +from nova import manager +from nova import utils + + +FLAGS = flags.FLAGS +flags.DEFINE_string('storage_availability_zone', + 'nova', + 'availability zone of this service') +flags.DEFINE_string('volume_driver', 'nova.volume.driver.AOEDriver', + 'Driver to use for volume creation') +flags.DEFINE_integer('num_shelves', + 100, + 'Number of vblade shelves') +flags.DEFINE_integer('blades_per_shelf', + 16, + 'Number of vblade blades per shelf') + + +class AOEManager(manager.Manager): + """Manages Ata-Over_Ethernet volumes""" + def __init__(self, volume_driver=None, *args, **kwargs): + if not volume_driver: + volume_driver = FLAGS.volume_driver + self.driver = utils.import_object(volume_driver) + super(AOEManager, self).__init__(*args, **kwargs) + + def _ensure_blades(self, context): + """Ensure that blades have been created in datastore""" + total_blades = FLAGS.num_shelves * FLAGS.blades_per_shelf + if self.db.export_device_count(context) >= total_blades: + return + for shelf_id in xrange(FLAGS.num_shelves): + for blade_id in xrange(FLAGS.blades_per_shelf): + dev = {'shelf_id': shelf_id, 'blade_id': blade_id} + self.db.export_device_create(context, dev) + + @defer.inlineCallbacks + def create_volume(self, context, volume_id): + """Creates and exports the volume""" + logging.info("volume %s: creating", volume_id) + + volume_ref = self.db.volume_get(context, volume_id) + + self.db.volume_update(context, + volume_id, + {'host': FLAGS.host}) + + size = volume_ref['size'] + logging.debug("volume %s: creating lv of size %sG", volume_id, size) + yield self.driver.create_volume(volume_ref['str_id'], size) + + logging.debug("volume %s: allocating shelf & blade", volume_id) + self._ensure_blades(context) + rval = self.db.volume_allocate_shelf_and_blade(context, volume_id) + (shelf_id, blade_id) = rval + + logging.debug("volume %s: exporting shelf %s & blade %s", volume_id, + shelf_id, blade_id) + + yield self.driver.create_export(volume_ref['str_id'], + shelf_id, + blade_id) + # TODO(joshua): We need to trigger a fanout message + # for aoe-discover on all the nodes + + self.db.volume_update(context, volume_id, {'status': 'available'}) + + logging.debug("volume %s: re-exporting all values", volume_id) + yield self.driver.ensure_exports() + + logging.debug("volume %s: created successfully", volume_id) + defer.returnValue(volume_id) + + @defer.inlineCallbacks + def delete_volume(self, context, volume_id): + """Deletes and unexports volume""" + logging.debug("Deleting volume with id of: %s", volume_id) + volume_ref = self.db.volume_get(context, volume_id) + if volume_ref['attach_status'] == "attached": + raise exception.Error("Volume is still attached") + if volume_ref['host'] != FLAGS.host: + raise exception.Error("Volume is not local to this node") + shelf_id, blade_id = self.db.volume_get_shelf_and_blade(context, + volume_id) + yield self.driver.remove_export(volume_ref['str_id'], + shelf_id, + blade_id) + yield self.driver.delete_volume(volume_ref['str_id']) + self.db.volume_destroy(context, volume_id) + defer.returnValue(True) + + @defer.inlineCallbacks + def setup_compute_volume(self, context, volume_id): + """Setup remote volume on compute host + + Returns path to device. + """ + volume_ref = self.db.volume_get(context, volume_id) + yield self.driver.discover_volume(volume_ref['str_id']) + shelf_id, blade_id = self.db.volume_get_shelf_and_blade(context, + volume_id) + defer.returnValue("/dev/etherd/e%s.%s" % (shelf_id, blade_id)) diff --git a/nova/volume/service.py b/nova/volume/service.py deleted file mode 100644 index be62f621d..000000000 --- a/nova/volume/service.py +++ /dev/null @@ -1,322 +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 Storage manages creating, attaching, detaching, and -destroying persistent storage volumes, ala EBS. -Currently uses Ata-over-Ethernet. -""" - -import logging -import os - -from twisted.internet import defer - -from nova import datastore -from nova import exception -from nova import flags -from nova import process -from nova import service -from nova import utils -from nova import validate - - -FLAGS = flags.FLAGS -flags.DEFINE_string('storage_dev', '/dev/sdb', - 'Physical device to use for volumes') -flags.DEFINE_string('volume_group', 'nova-volumes', - 'Name for the VG that will contain exported volumes') -flags.DEFINE_string('aoe_eth_dev', 'eth0', - 'Which device to export the volumes on') -flags.DEFINE_integer('first_shelf_id', - utils.last_octet(utils.get_my_ip()) * 10, - 'AoE starting shelf_id for this service') -flags.DEFINE_integer('last_shelf_id', - utils.last_octet(utils.get_my_ip()) * 10 + 9, - 'AoE starting shelf_id for this service') -flags.DEFINE_string('aoe_export_dir', - '/var/lib/vblade-persist/vblades', - 'AoE directory where exports are created') -flags.DEFINE_integer('blades_per_shelf', - 16, - 'Number of AoE blades per shelf') -flags.DEFINE_string('storage_availability_zone', - 'nova', - 'availability zone of this service') -flags.DEFINE_boolean('fake_storage', False, - 'Should we make real storage volumes to attach?') - - -class NoMoreBlades(exception.Error): - pass - - -def get_volume(volume_id): - """ Returns a redis-backed volume object """ - volume_class = Volume - if FLAGS.fake_storage: - volume_class = FakeVolume - vol = volume_class.lookup(volume_id) - if vol: - return vol - raise exception.Error("Volume does not exist") - - -class VolumeService(service.Service): - """ - There is one VolumeNode running on each host. - However, each VolumeNode can report on the state of - *all* volumes in the cluster. - """ - def __init__(self): - super(VolumeService, self).__init__() - self.volume_class = Volume - if FLAGS.fake_storage: - self.volume_class = FakeVolume - self._init_volume_group() - - @defer.inlineCallbacks - @validate.rangetest(size=(0, 1000)) - def create_volume(self, size, user_id, project_id): - """ - Creates an exported volume (fake or real), - restarts exports to make it available. - Volume at this point has size, owner, and zone. - """ - logging.debug("Creating volume of size: %s" % (size)) - vol = yield self.volume_class.create(size, user_id, project_id) - logging.debug("restarting exports") - yield self._restart_exports() - defer.returnValue(vol['volume_id']) - - def by_node(self, node_id): - """ returns a list of volumes for a node """ - for volume_id in datastore.Redis.instance().smembers('volumes:%s' % (node_id)): - yield self.volume_class(volume_id=volume_id) - - @property - def all(self): - """ returns a list of all volumes """ - for volume_id in datastore.Redis.instance().smembers('volumes'): - yield self.volume_class(volume_id=volume_id) - - @defer.inlineCallbacks - def delete_volume(self, volume_id): - logging.debug("Deleting volume with id of: %s" % (volume_id)) - vol = get_volume(volume_id) - if vol['attach_status'] == "attached": - raise exception.Error("Volume is still attached") - if vol['node_name'] != FLAGS.node_name: - raise exception.Error("Volume is not local to this node") - yield vol.destroy() - defer.returnValue(True) - - @defer.inlineCallbacks - def _restart_exports(self): - if FLAGS.fake_storage: - return - # NOTE(vish): these commands sometimes sends output to stderr for warnings - yield process.simple_execute( "sudo vblade-persist auto all", - terminate_on_stderr=False) - yield process.simple_execute( "sudo vblade-persist start all", - terminate_on_stderr=False) - - @defer.inlineCallbacks - def _init_volume_group(self): - if FLAGS.fake_storage: - return - yield process.simple_execute( - "sudo pvcreate %s" % (FLAGS.storage_dev)) - yield process.simple_execute( - "sudo vgcreate %s %s" % (FLAGS.volume_group, - FLAGS.storage_dev)) - - -class Volume(datastore.BasicModel): - - def __init__(self, volume_id=None): - self.volume_id = volume_id - super(Volume, self).__init__() - - @property - def identifier(self): - return self.volume_id - - def default_state(self): - return {"volume_id": self.volume_id, - "node_name": "unassigned"} - - @classmethod - @defer.inlineCallbacks - def create(cls, size, user_id, project_id): - volume_id = utils.generate_uid('vol') - vol = cls(volume_id) - vol['node_name'] = FLAGS.node_name - vol['size'] = size - vol['user_id'] = user_id - vol['project_id'] = project_id - vol['availability_zone'] = FLAGS.storage_availability_zone - vol["instance_id"] = 'none' - vol["mountpoint"] = 'none' - vol['attach_time'] = 'none' - vol['status'] = "creating" # creating | available | in-use - vol['attach_status'] = "detached" # attaching | attached | detaching | detached - vol['delete_on_termination'] = 'False' - vol.save() - yield vol._create_lv() - yield vol._setup_export() - # TODO(joshua) - We need to trigger a fanout message for aoe-discover on all the nodes - vol['status'] = "available" - vol.save() - defer.returnValue(vol) - - def start_attach(self, instance_id, mountpoint): - """ """ - self['instance_id'] = instance_id - self['mountpoint'] = mountpoint - self['status'] = "in-use" - self['attach_status'] = "attaching" - self['attach_time'] = utils.isotime() - self['delete_on_termination'] = 'False' - self.save() - - def finish_attach(self): - """ """ - self['attach_status'] = "attached" - self.save() - - def start_detach(self): - """ """ - self['attach_status'] = "detaching" - self.save() - - def finish_detach(self): - self['instance_id'] = None - self['mountpoint'] = None - self['status'] = "available" - self['attach_status'] = "detached" - self.save() - - def save(self): - is_new = self.is_new_record() - super(Volume, self).save() - if is_new: - redis = datastore.Redis.instance() - key = self.__devices_key - # TODO(vish): these should be added by admin commands - more = redis.scard(self._redis_association_name("node", - self['node_name'])) - if (not redis.exists(key) and not more): - for shelf_id in range(FLAGS.first_shelf_id, - FLAGS.last_shelf_id + 1): - for blade_id in range(FLAGS.blades_per_shelf): - redis.sadd(key, "%s.%s" % (shelf_id, blade_id)) - self.associate_with("node", self['node_name']) - - @defer.inlineCallbacks - def destroy(self): - yield self._remove_export() - yield self._delete_lv() - self.unassociate_with("node", self['node_name']) - if self.get('shelf_id', None) and self.get('blade_id', None): - redis = datastore.Redis.instance() - key = self.__devices_key - redis.sadd(key, "%s.%s" % (self['shelf_id'], self['blade_id'])) - super(Volume, self).destroy() - - @defer.inlineCallbacks - def _create_lv(self): - if str(self['size']) == '0': - sizestr = '100M' - else: - sizestr = '%sG' % self['size'] - yield process.simple_execute( - "sudo lvcreate -L %s -n %s %s" % (sizestr, - self['volume_id'], - FLAGS.volume_group), - terminate_on_stderr=False) - - @defer.inlineCallbacks - def _delete_lv(self): - yield process.simple_execute( - "sudo lvremove -f %s/%s" % (FLAGS.volume_group, - self['volume_id']), - terminate_on_stderr=False) - - @property - def __devices_key(self): - return 'volume_devices:%s' % FLAGS.node_name - - @defer.inlineCallbacks - def _setup_export(self): - redis = datastore.Redis.instance() - key = self.__devices_key - device = redis.spop(key) - if not device: - raise NoMoreBlades() - (shelf_id, blade_id) = device.split('.') - self['aoe_device'] = "e%s.%s" % (shelf_id, blade_id) - self['shelf_id'] = shelf_id - self['blade_id'] = blade_id - self.save() - yield self._exec_setup_export() - - @defer.inlineCallbacks - def _exec_setup_export(self): - yield process.simple_execute( - "sudo vblade-persist setup %s %s %s /dev/%s/%s" % - (self['shelf_id'], - self['blade_id'], - FLAGS.aoe_eth_dev, - FLAGS.volume_group, - self['volume_id']), - terminate_on_stderr=False) - - @defer.inlineCallbacks - def _remove_export(self): - if not self.get('shelf_id', None) or not self.get('blade_id', None): - defer.returnValue(False) - yield self._exec_remove_export() - defer.returnValue(True) - - @defer.inlineCallbacks - def _exec_remove_export(self): - yield process.simple_execute( - "sudo vblade-persist stop %s %s" % (self['shelf_id'], - self['blade_id']), - terminate_on_stderr=False) - yield process.simple_execute( - "sudo vblade-persist destroy %s %s" % (self['shelf_id'], - self['blade_id']), - terminate_on_stderr=False) - - -class FakeVolume(Volume): - def _create_lv(self): - pass - - def _exec_setup_export(self): - fname = os.path.join(FLAGS.aoe_export_dir, self['aoe_device']) - f = file(fname, "w") - f.close() - - def _exec_remove_export(self): - os.unlink(os.path.join(FLAGS.aoe_export_dir, self['aoe_device'])) - - def _delete_lv(self): - pass diff --git a/run_tests.py b/run_tests.py index 77aa9088a..d5dc5f934 100644 --- a/run_tests.py +++ b/run_tests.py @@ -55,11 +55,11 @@ from nova.tests.api_unittest import * from nova.tests.cloud_unittest import * from nova.tests.compute_unittest import * from nova.tests.flags_unittest import * -from nova.tests.model_unittest import * from nova.tests.network_unittest import * from nova.tests.objectstore_unittest import * from nova.tests.process_unittest import * from nova.tests.rpc_unittest import * +from nova.tests.service_unittest import * from nova.tests.validator_unittest import * from nova.tests.volume_unittest import * diff --git a/tools/pip-requires b/tools/pip-requires index 13e8e5f45..dd69708ce 100644 --- a/tools/pip-requires +++ b/tools/pip-requires @@ -1,3 +1,4 @@ +SQLAlchemy==0.6.3 pep8==0.5.0 pylint==0.19 IPy==0.70 |