summaryrefslogtreecommitdiffstats
path: root/nova/virt
diff options
context:
space:
mode:
authorEwan Mellor <ewan.mellor@citrix.com>2010-07-18 18:15:12 +0100
committerEwan Mellor <ewan.mellor@citrix.com>2010-07-18 18:15:12 +0100
commitf39d6549d4e57941b14f328fa5a52a3a5f925d42 (patch)
tree24da962064d7741da065842f2032577aa0268ac5 /nova/virt
parentd5309eff30b1a826f075b28935de2a4b89eede6e (diff)
In preparation for XenAPI support, refactor the interface between
nova.compute and the hypervisor (i.e. libvirt). compute.node is no longer coupled tightly with libvirt. Instead, hypervisor connections are handled through a simple abstract interface. This has the additional advantage that there is no need to riddle the code with FLAGS.fake_libvirt checks, as we now have an interface behind which we can mock. The libvirt-specific code, and the fakevirt code used for unit tests, have moved into nova.virt. The fake_libvirt flag has been replaced with a connection_type flag, that will allow us to specify different connection types. The disk image handling (S3 or local disk image fetch) has moved into nova.virt.images, where it will be easier to share between connection types. The power_state values (Instance.RUNNING etc) and the INSTANCE_TYPES dictionary have moved into their own files (nova.compute.instance_types and nova.compute.power_state) so that we can share them without mutual dependencies between nova.compute.node and nova.virt.libvirt_conn.
Diffstat (limited to 'nova/virt')
-rw-r--r--nova/virt/__init__.py15
-rw-r--r--nova/virt/connection.py42
-rw-r--r--nova/virt/fake.py81
-rw-r--r--nova/virt/images.py55
-rw-r--r--nova/virt/libvirt_conn.py353
5 files changed, 546 insertions, 0 deletions
diff --git a/nova/virt/__init__.py b/nova/virt/__init__.py
new file mode 100644
index 000000000..3d598c463
--- /dev/null
+++ b/nova/virt/__init__.py
@@ -0,0 +1,15 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright (c) 2010 Citrix Systems, Inc.
+#
+# 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.
diff --git a/nova/virt/connection.py b/nova/virt/connection.py
new file mode 100644
index 000000000..25c817415
--- /dev/null
+++ b/nova/virt/connection.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.
+# Copyright (c) 2010 Citrix Systems, Inc.
+#
+# 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 nova import flags
+from nova.virt import fake
+from nova.virt import libvirt_conn
+
+
+FLAGS = flags.FLAGS
+
+
+def get_connection(read_only=False):
+ # TODO(termie): maybe lazy load after initial check for permissions
+ # TODO(termie): check whether we can be disconnected
+ t = FLAGS.connection_type
+ if t == 'fake':
+ conn = fake.get_connection(read_only)
+ elif t == 'libvirt':
+ conn = libvirt_conn.get_connection(read_only)
+ else:
+ raise Exception('Unknown connection type "%s"' % t)
+
+ if conn is None:
+ logging.error('Failed to open connection to the hypervisor')
+ sys.exit(1)
+ return conn
diff --git a/nova/virt/fake.py b/nova/virt/fake.py
new file mode 100644
index 000000000..d9ae5ac96
--- /dev/null
+++ b/nova/virt/fake.py
@@ -0,0 +1,81 @@
+# 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.
+# Copyright (c) 2010 Citrix Systems, Inc.
+#
+# 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.
+
+"""
+A fake (in-memory) hypervisor+api. Allows nova testing w/o a hypervisor.
+"""
+
+import logging
+
+from nova.compute import power_state
+
+
+def get_connection(_):
+ # The read_only parameter is ignored.
+ return FakeConnection.instance()
+
+
+class FakeConnection(object):
+ def __init__(self):
+ self.instances = {}
+
+ @classmethod
+ def instance(cls):
+ if not hasattr(cls, '_instance'):
+ cls._instance = cls()
+ return cls._instance
+
+ def list_instances(self):
+ return self.instances.keys()
+
+ def spawn(self, instance):
+ fake_instance = FakeInstance()
+ self.instances[instance.name] = fake_instance
+ fake_instance._state = power_state.RUNNING
+
+ def reboot(self, instance):
+ pass
+
+ def destroy(self, instance):
+ del self.instances[instance.name]
+
+ def get_info(self, instance_id):
+ i = self.instances[instance_id]
+ return {'state': i._state,
+ 'max_mem': 0,
+ 'mem': 0,
+ 'num_cpu': 2,
+ 'cpu_time': 0}
+
+ def list_disks(self, instance_id):
+ return ['A_DISK']
+
+ def list_interfaces(self, instance_id):
+ return ['A_VIF']
+
+ def block_stats(self, instance_id, disk_id):
+ return [0L, 0L, 0L, 0L, null]
+
+ def interface_stats(self, instance_id, iface_id):
+ return [0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L]
+
+
+class FakeInstance(object):
+ def __init__(self):
+ self._state = power_state.NOSTATE
diff --git a/nova/virt/images.py b/nova/virt/images.py
new file mode 100644
index 000000000..0b11c134e
--- /dev/null
+++ b/nova/virt/images.py
@@ -0,0 +1,55 @@
+# 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.
+# Copyright (c) 2010 Citrix Systems, Inc.
+#
+# 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.
+
+"""
+Handling of VM disk images.
+"""
+
+import os.path
+
+from nova import flags
+
+FLAGS = flags.FLAGS
+
+flags.DEFINE_bool('use_s3', True,
+ 'whether to get images from s3 or use local copy')
+
+
+def fetch(pool, image, path):
+ if FLAGS.use_s3:
+ f = _fetch_s3_image
+ else:
+ f = _fetch_local_image
+ return f(pool, image, path)
+
+def _fetch_s3_image(pool, image, path):
+ url = _image_url('%s/image' % image)
+ d = pool.simpleExecute('curl --silent %s -o %s' % (url, path))
+ return d
+
+def _fetch_local_image(pool, image, path):
+ source = _image_path('%s/image' % image)
+ d = pool.simpleExecute('cp %s %s' % (source, path))
+ return d
+
+def _image_path(path):
+ return os.path.join(FLAGS.images_path, path)
+
+def _image_url(path):
+ return "%s:%s/_images/%s" % (FLAGS.s3_host, FLAGS.s3_port, path)
diff --git a/nova/virt/libvirt_conn.py b/nova/virt/libvirt_conn.py
new file mode 100644
index 000000000..74fec650e
--- /dev/null
+++ b/nova/virt/libvirt_conn.py
@@ -0,0 +1,353 @@
+# 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.
+# Copyright (c) 2010 Citrix Systems, Inc.
+#
+# 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.
+
+"""
+A connection to a hypervisor (e.g. KVM) through libvirt.
+"""
+
+import json
+import logging
+import os.path
+import shutil
+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 utils
+from nova.compute import disk
+from nova.compute import instance_types
+from nova.compute import power_state
+from nova.virt import images
+
+libvirt = None
+libxml2 = None
+
+FLAGS = flags.FLAGS
+flags.DEFINE_string('libvirt_xml_template',
+ utils.abspath('compute/libvirt.xml.template'),
+ 'Libvirt XML Template')
+
+def get_connection(read_only):
+ # These are loaded late so that there's no need to install these
+ # libraries when not using libvirt.
+ global libvirt
+ global libxml2
+ if libvirt is None:
+ libvirt = __import__('libvirt')
+ if libxml2 is None:
+ libxml2 = __import__('libxml2')
+ return LibvirtConnection(read_only)
+
+
+class LibvirtConnection(object):
+ def __init__(self, read_only):
+ auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT],
+ 'root',
+ None]
+ if read_only:
+ self._conn = libvirt.openReadOnly('qemu:///system')
+ else:
+ self._conn = libvirt.openAuth('qemu:///system', auth, 0)
+ self._pool = process.ProcessPool()
+
+
+ def list_instances(self):
+ return [self._conn.lookupByID(x).name()
+ for x in self._conn.listDomainsID()]
+
+
+ def destroy(self, instance):
+ try:
+ virt_dom = self._conn.lookupByName(instance.name)
+ virt_dom.destroy()
+ except Exception, _err:
+ pass
+ # If the instance is already terminated, we're still happy
+ d = defer.Deferred()
+ d.addCallback(lambda x: self._cleanup())
+ # FIXME: What does this comment mean?
+ # TODO(termie): short-circuit me for tests
+ # WE'LL save this for when we do shutdown,
+ # instead of destroy - but destroy returns immediately
+ timer = task.LoopingCall(f=None)
+ def _wait_for_shutdown():
+ try:
+ instance.update_state()
+ if instance.state == power_state.SHUTDOWN:
+ timer.stop()
+ d.callback(None)
+ except Exception:
+ instance.set_state(power_state.SHUTDOWN)
+ timer.stop()
+ d.callback(None)
+ timer.f = _wait_for_shutdown
+ timer.start(interval=0.5, now=True)
+ return d
+
+
+ def _cleanup(self, instance):
+ target = os.path.abspath(instance.datamodel['basepath'])
+ logging.info("Deleting instance files at %s", target)
+ shutil.rmtree(target)
+
+
+ @defer.inlineCallbacks
+ @exception.wrap_exception
+ def reboot(self, instance):
+ xml = self.toXml(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)
+ timer.stop()
+ d.callback(None)
+ except Exception, exn:
+ logging.error('_wait_for_reboot failed: %s' % exn)
+ instance.set_state(power_state.SHUTDOWN)
+ timer.stop()
+ d.callback(None)
+ timer.f = _wait_for_reboot
+ timer.start(interval=0.5, now=True)
+ yield d
+
+
+ @defer.inlineCallbacks
+ @exception.wrap_exception
+ def spawn(self, instance):
+ xml = self.toXml(instance)
+ instance.set_state(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")
+
+ 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)
+ 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)
+ timer.stop()
+ local_d.callback(None)
+ timer.f = _wait_for_boot
+ timer.start(interval=0.5, now=True)
+ yield local_d
+
+
+ @defer.inlineCallbacks
+ def _create_image(self, instance, libvirt_xml):
+ # syntactic nicety
+ data = instance.datamodel
+ basepath = lambda x='': self.basepath(instance, x)
+
+ # ensure directories exist and are writable
+ yield self._pool.simpleExecute('mkdir -p %s' % basepath())
+ yield self._pool.simpleExecute('chmod 0777 %s' % basepath())
+
+
+ # TODO(termie): these are blocking calls, it would be great
+ # if they weren't.
+ logging.info('Creating image for: %s', data['instance_id'])
+ f = open(basepath('libvirt.xml'), 'w')
+ f.write(libvirt_xml)
+ f.close()
+
+ if not os.path.exists(basepath('disk')):
+ yield images.fetch(self._pool, data['image_id'], basepath('disk-raw'))
+ if not os.path.exists(basepath('kernel')):
+ yield images.fetch(self._pool, data['kernel_id'], basepath('kernel'))
+ if not os.path.exists(basepath('ramdisk')):
+ yield images.fetch(self._pool, data['ramdisk_id'], basepath('ramdisk'))
+
+ execute = lambda cmd, input=None: self._pool.simpleExecute(cmd=cmd,
+ input=input,
+ error_ok=1)
+
+ key = data['key_data']
+ net = None
+ if FLAGS.simple_network:
+ with open(FLAGS.simple_network_template) as f:
+ net = f.read() % {'address': data['private_dns_name'],
+ 'network': FLAGS.simple_network_network,
+ 'netmask': FLAGS.simple_network_netmask,
+ 'gateway': FLAGS.simple_network_gateway,
+ 'broadcast': FLAGS.simple_network_broadcast,
+ 'dns': FLAGS.simple_network_dns}
+ if key or net:
+ logging.info('Injecting data into image %s', data['image_id'])
+ yield disk.inject_data(basepath('disk-raw'), key, net, execute=execute)
+
+ if os.path.exists(basepath('disk')):
+ yield self._pool.simpleExecute('rm -f %s' % basepath('disk'))
+
+ bytes = (instance_types.INSTANCE_TYPES[data['instance_type']]['local_gb']
+ * 1024 * 1024 * 1024)
+ yield disk.partition(
+ basepath('disk-raw'), basepath('disk'), bytes, execute=execute)
+
+
+ def basepath(self, instance, path=''):
+ return os.path.abspath(os.path.join(instance.datamodel['basepath'], path))
+
+
+ def toXml(self, instance):
+ # TODO(termie): cache?
+ logging.debug("Starting the toXML method")
+ libvirt_xml = open(FLAGS.libvirt_xml_template).read()
+ 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())
+ libvirt_xml = libvirt_xml % xml_info
+ logging.debug("Finished the toXML method")
+
+ return libvirt_xml
+
+
+ def get_info(self, instance_id):
+ virt_dom = self._conn.lookupByName(instance_id)
+ (state, max_mem, mem, num_cpu, cpu_time) = virt_dom.info()
+ return {'state': state,
+ 'max_mem': max_mem,
+ 'mem': mem,
+ 'num_cpu': num_cpu,
+ 'cpu_time': cpu_time}
+
+
+ def get_disks(self, instance_id):
+ """
+ Note that this function takes an instance ID, 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_id)
+ # TODO(devcamcar): Replace libxml2 with etree.
+ xml = domain.XMLDesc(0)
+ doc = None
+
+ try:
+ doc = libxml2.parseDoc(xml)
+ except:
+ return []
+
+ ctx = doc.xpathNewContext()
+ disks = []
+
+ try:
+ ret = ctx.xpathEval('/domain/devices/disk')
+
+ for node in ret:
+ devdst = None
+
+ for child in node.children:
+ if child.name == 'target':
+ devdst = child.prop('dev')
+
+ if devdst == None:
+ continue
+
+ disks.append(devdst)
+ finally:
+ if ctx != None:
+ ctx.xpathFreeContext()
+ if doc != None:
+ doc.freeDoc()
+
+ return disks
+
+
+ def get_interfaces(self, instance_id):
+ """
+ Note that this function takes an instance ID, 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_id)
+ # TODO(devcamcar): Replace libxml2 with etree.
+ xml = domain.XMLDesc(0)
+ doc = None
+
+ try:
+ doc = libxml2.parseDoc(xml)
+ except:
+ return []
+
+ ctx = doc.xpathNewContext()
+ interfaces = []
+
+ try:
+ ret = ctx.xpathEval('/domain/devices/interface')
+
+ for node in ret:
+ devdst = None
+
+ for child in node.children:
+ if child.name == 'target':
+ devdst = child.prop('dev')
+
+ if devdst == None:
+ continue
+
+ interfaces.append(devdst)
+ finally:
+ if ctx != None:
+ ctx.xpathFreeContext()
+ if doc != None:
+ doc.freeDoc()
+
+ return interfaces
+
+
+ def block_stats(self, instance_id, disk):
+ """
+ Note that this function takes an instance ID, not an Instance, so
+ that it can be called by monitor.
+ """
+ domain = self._conn.lookupByName(instance_id)
+ return domain.blockStats(disk)
+
+
+ def interface_stats(self, instance_id, interface):
+ """
+ Note that this function takes an instance ID, not an Instance, so
+ that it can be called by monitor.
+ """
+ domain = self._conn.lookupByName(instance_id)
+ return domain.interfaceStats(interface)