14 from string import Template
17 libvirt.VIR_DOMAIN_NOSTATE: 'no state',
18 libvirt.VIR_DOMAIN_RUNNING: 'running',
19 libvirt.VIR_DOMAIN_BLOCKED: 'blocked on resource',
20 libvirt.VIR_DOMAIN_PAUSED: 'paused by user',
21 libvirt.VIR_DOMAIN_SHUTDOWN: 'being shut down',
22 libvirt.VIR_DOMAIN_SHUTOFF: 'shut off',
23 libvirt.VIR_DOMAIN_CRASHED: 'crashed',
26 REF_IMG_BASE_DIR = '/vservers/.lvref'
27 CON_BASE_DIR = '/vservers'
29 class Sliver_LV(accounts.Account):
30 """This class wraps LibVirt commands"""
34 # Need to add a tag at myplc to actually use this account
35 # type = 'sliver.LIBVIRT'
36 TYPE = 'sliver.LIBVIRT'
40 def create(name, rec = None):
41 ''' Create dirs, copy fs image, lxc_create '''
42 logger.verbose ('sliver_libvirt: %s create'%(name))
44 # Template for libvirt sliver configuration
46 with open('/vservers/.lvref/config_template.xml') as f:
47 template = Template(f.read())
48 config = template.substitute(name=name)
50 logger.log('Cannot find XML template file')
53 # Get the type of image from vref myplc tags specified as:
59 logger.log('sliver_libvirt: %s: WARNING - no vref attached defaults to lxc-debian' % (name))
60 vref = "lxc-squeeze-x86_64"
62 refImgDir = os.path.join(REF_IMG_BASE_DIR, vref)
63 containerDir = os.path.join(CON_BASE_DIR, name)
65 # check the template exists -- there's probably a better way..
66 if not os.path.isdir(refImgDir):
67 logger.log('sliver_libvirt: %s: ERROR Could not create sliver - reference image %s not found' % (name,vref))
70 # Copy the reference image fs
71 # shutil.copytree("/vservers/.lvref/%s"%vref, "/vservers/%s"%name, symlinks=True)
72 command = ['cp', '-r', refImgDir, containerDir]
73 logger.log_call(command, timeout=15*60)
75 # Set hostname. A valid hostname cannot have '_'
76 with open(os.path.join(containerDir, 'etc/hostname'), 'w') as f:
77 print >>f, name.replace('_', '-')
79 # Add slices group if not already present
80 command = ['/usr/sbin/groupadd slices']
81 logger.log_call(command, timeout=15*60)
84 command = ['/usr/sbin/useradd', '-g', 'slices', '-s', '/bin/sh', name, '-p', '*']
85 logger.log_call(command, timeout=15*60)
87 # Get a connection and lookup for the sliver before actually
88 # defining it, just in case it was already defined.
89 conn = Sliver_LV.getConnection()
91 dom = conn.lookupByName(name)
93 dom = conn.defineXML(config)
94 logger.verbose('lxc_create: %s -> %s'%(name, Sliver_LV.info(dom)))
98 logger.verbose ('sliver_libvirt: %s destroy'%(name))
100 dir = '/vservers/%s'%(name)
101 lxc_log = '%s/lxc.log'%(dir)
103 conn = Sliver_LV.getConnection()
106 command = ['/usr/sbin/userdel', '-r', name]
107 logger.log_call(command, timeout=15*60)
109 # Destroy libvirt domain
110 dom = conn.lookupByName(name)
114 # Remove rootfs of destroyed domain
115 shutil.rmtree("/vservers/%s"%name)
117 logger.verbose('sliver_libvirt: Unexpected error on %s: %s'%(name, sys.exc_info()[0]))
119 def __init__(self, rec):
120 self.name = rec['name']
121 logger.verbose ('sliver_libvirt: %s init'%(self.name))
123 self.dir = '/vservers/%s'%(self.name)
125 # Assume the directory with the image and config files
130 self.slice_id = rec['slice_id']
131 self.disk_usage_initialized = False
134 conn = Sliver_LV.getConnection()
136 self.container = conn.lookupByName(self.name)
138 logger.verbose('sliver_libvirt: Unexpected error on %s: %s'%(self.name, sys.exc_info()[0]))
140 def configure(self, rec):
141 ''' Allocate resources and fancy configuration stuff '''
142 logger.verbose('sliver_libvirt: %s configure'%(self.name))
143 accounts.Account.configure(self, rec)
145 def start(self, delay=0):
146 ''' Just start the sliver '''
147 print "LIBVIRT %s start"%(self.name)
149 # Check if it's running to avoid throwing an exception if the
150 # domain was already running, create actually means start
151 if not self.is_running():
152 self.container.create()
154 logger.verbose('sliver_libvirt: sliver %s already started'%(self.name))
157 logger.verbose('sliver_libvirt: %s stop'%(self.name))
160 self.container.destroy()
162 print "Unexpected error:", sys.exc_info()[0]
164 def is_running(self):
165 ''' Return True if the domain is running '''
166 logger.verbose('sliver_libvirt: %s is_running'%(self.name))
168 [state, _, _, _, _] = self.container.info()
169 if state == libvirt.VIR_DOMAIN_RUNNING:
170 logger.verbose('sliver_libvirt: %s is RUNNING'%(self.name))
173 info = Sliver_LV.info(self.container)
174 logger.verbose('sliver_libvirt: %s is NOT RUNNING...\n%s'%(self.name, info))
177 print "Unexpected error:", sys.exc_info()
179 ''' PRIVATE/HELPER/STATIC METHODS '''
182 ''' Helper method to get a connection to the LXC driver of Libvirt '''
183 conn = libvirt.open('lxc:///')
185 print 'Failed to open connection to LXC hypervisor'
191 ''' Helper method to get a "nice" output of the info struct for debug'''
192 [state, maxmem, mem, ncpu, cputime] = dom.info()
193 return '%s is %s, maxmem = %s, mem = %s, ncpu = %s, cputime = %s' % (dom.name(), states.get(state, state), maxmem, mem, ncpu, cputime)