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)
76 with open(os.path.join(containerDir, 'etc/hostname'), 'w') as f:
80 command = ['/usr/sbin/useradd', '-s', '/bin/sh', name]
81 logger.log_call(command, timeout=15*60)
83 # Get a connection and lookup for the sliver before actually
84 # defining it, just in case it was already defined.
85 conn = Sliver_LV.getConnection()
87 dom = conn.lookupByName(name)
89 dom = conn.defineXML(config)
90 logger.verbose('lxc_create: %s -> %s'%(name, Sliver_LV.info(dom)))
94 logger.verbose ('sliver_libvirt: %s destroy'%(name))
96 dir = '/vservers/%s'%(name)
97 lxc_log = '%s/lxc.log'%(dir)
99 conn = Sliver_LV.getConnection()
102 command = ['/usr/sbin/userdel', name]
103 logger.log_call(command, timeout=15*60)
105 # Destroy libvirt domain
106 dom = conn.lookupByName(name)
110 # Remove rootfs of destroyed domain
111 shutil.rmtree("/vservers/%s"%name)
113 logger.verbose('sliver_libvirt: Unexpected error on %s: %s'%(name, sys.exc_info()[0]))
115 def __init__(self, rec):
116 self.name = rec['name']
117 logger.verbose ('sliver_libvirt: %s init'%(self.name))
119 self.dir = '/vservers/%s'%(self.name)
121 # Assume the directory with the image and config files
126 self.slice_id = rec['slice_id']
127 self.disk_usage_initialized = False
130 conn = Sliver_LV.getConnection()
132 self.container = conn.lookupByName(self.name)
134 logger.verbose('sliver_libvirt: Unexpected error on %s: %s'%(self.name, sys.exc_info()[0]))
136 def configure(self, rec):
137 ''' Allocate resources and fancy configuration stuff '''
138 logger.verbose('sliver_libvirt: %s configure'%(self.name))
139 accounts.Account.configure(self, rec)
141 def start(self, delay=0):
142 ''' Just start the sliver '''
143 print "LIBVIRT %s start"%(self.name)
145 # Check if it's running to avoid throwing an exception if the
146 # domain was already running, create actually means start
147 if not self.is_running():
148 self.container.create()
150 logger.verbose('sliver_libvirt: sliver %s already started'%(self.name))
153 logger.verbose('sliver_libvirt: %s stop'%(self.name))
156 self.container.destroy()
158 print "Unexpected error:", sys.exc_info()[0]
160 def is_running(self):
161 ''' Return True if the domain is running '''
162 logger.verbose('sliver_libvirt: %s is_running'%(self.name))
164 [state, _, _, _, _] = self.container.info()
165 if state == libvirt.VIR_DOMAIN_RUNNING:
166 logger.verbose('sliver_libvirt: %s is RUNNING'%(self.name))
169 info = Sliver_LV.info(self.container)
170 logger.verbose('sliver_libvirt: %s is NOT RUNNING...\n%s'%(self.name, info))
173 print "Unexpected error:", sys.exc_info()
175 ''' PRIVATE/HELPER/STATIC METHODS '''
178 ''' Helper method to get a connection to the LXC driver of Libvirt '''
179 conn = libvirt.open('lxc:///')
181 print 'Failed to open connection to LXC hypervisor'
187 ''' Helper method to get a "nice" output of the info struct for debug'''
188 [state, maxmem, mem, ncpu, cputime] = dom.info()
189 return '%s is %s, maxmem = %s, mem = %s, ncpu = %s, cputime = %s' % (dom.name(), states.get(state, state), maxmem, mem, ncpu, cputime)