Merge branch 'lxc_devel' of github.com:planetlab/NodeManager into lxc_devel
[nodemanager.git] / sliver_libvirt.py
1 #
2
3 """LibVirt slivers"""
4
5 import accounts
6 import logger
7 import subprocess
8 import os
9 import os.path
10 import libvirt
11 import sys
12 import shutil
13
14 from string import Template
15
16 states = {
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',
24 }
25
26 REF_IMG_BASE_DIR = '/vservers/.lvref'
27 CON_BASE_DIR     = '/vservers'
28
29 class Sliver_LV(accounts.Account):
30     """This class wraps LibVirt commands"""
31    
32     SHELL = '/bin/sh' 
33
34     # Need to add a tag at myplc to actually use this account
35     # type = 'sliver.LIBVIRT'
36     TYPE = 'sliver.LIBVIRT'
37     
38
39     @staticmethod
40     def create(name, rec = None):
41         ''' Create dirs, copy fs image, lxc_create '''
42         logger.verbose ('sliver_libvirt: %s create'%(name))
43
44         # Template for libvirt sliver configuration
45         try:
46             with open('/vservers/.lvref/config_template.xml') as f:
47                 template = Template(f.read())
48                 config   = template.substitute(name=name)
49         except IOError:
50             logger.log('Cannot find XML template file')
51             return
52         
53         # Get the type of image from vref myplc tags specified as:
54         # pldistro = lxc
55         # fcdistro = squeeze
56         # arch x86_64
57         vref = rec['vref']
58         if vref is None:
59             logger.log('sliver_libvirt: %s: WARNING - no vref attached defaults to lxc-debian' % (name))
60             vref = "lxc-squeeze-x86_64"
61
62         refImgDir    = os.path.join(REF_IMG_BASE_DIR, vref)
63         containerDir = os.path.join(CON_BASE_DIR, name)
64
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))
68             return
69
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)
74
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('_', '-')
78
79         # Add slices group if not already present
80         command = ['/usr/sbin/groupadd slices']
81         logger.log_call(command, timeout=15*60)
82         
83         # Add unix account
84         command = ['/usr/sbin/useradd', '-g', 'slices', '-s', '/bin/sh', name, '-p', '*']
85         logger.log_call(command, timeout=15*60)
86
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()
90         try:
91             dom = conn.lookupByName(name)
92         except:
93             dom = conn.defineXML(config)
94         logger.verbose('lxc_create: %s -> %s'%(name, Sliver_LV.info(dom)))
95
96     @staticmethod
97     def destroy(name):
98         logger.verbose ('sliver_libvirt: %s destroy'%(name))
99         
100         dir = '/vservers/%s'%(name)
101         lxc_log = '%s/lxc.log'%(dir)
102
103         conn = Sliver_LV.getConnection()
104
105         try:
106             command = ['/usr/sbin/userdel', '-r', name]
107             logger.log_call(command, timeout=15*60)
108             
109             # Destroy libvirt domain
110             dom = conn.lookupByName(name)
111             dom.destroy()
112             dom.undefine()
113
114             # Remove rootfs of destroyed domain
115             shutil.rmtree("/vservers/%s"%name)
116         except:
117             logger.verbose('sliver_libvirt: Unexpected error on %s: %s'%(name, sys.exc_info()[0]))
118     
119     def __init__(self, rec):
120         self.name = rec['name']
121         logger.verbose ('sliver_libvirt: %s init'%(self.name))
122          
123         self.dir = '/vservers/%s'%(self.name)
124         
125         # Assume the directory with the image and config files
126         # are in place
127         
128         self.keys = ''
129         self.rspec = {}
130         self.slice_id = rec['slice_id']
131         self.disk_usage_initialized = False
132         self.initscript = ''
133         self.enabled = True
134         conn = Sliver_LV.getConnection()
135         try:
136             self.container = conn.lookupByName(self.name)
137         except:
138             logger.verbose('sliver_libvirt: Unexpected error on %s: %s'%(self.name, sys.exc_info()[0]))
139
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)  
144     
145     def start(self, delay=0):
146         ''' Just start the sliver '''
147         print "LIBVIRT %s start"%(self.name)
148
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()
153         else:
154             logger.verbose('sliver_libvirt: sliver %s already started'%(self.name))
155             
156     def stop(self):
157         logger.verbose('sliver_libvirt: %s stop'%(self.name))
158         
159         try:
160             self.container.destroy()
161         except:
162             print "Unexpected error:", sys.exc_info()[0]
163     
164     def is_running(self):
165         ''' Return True if the domain is running '''
166         logger.verbose('sliver_libvirt: %s is_running'%(self.name))
167         try:
168             [state, _, _, _, _] = self.container.info()
169             if state == libvirt.VIR_DOMAIN_RUNNING:
170                 logger.verbose('sliver_libvirt: %s is RUNNING'%(self.name))
171                 return True
172             else:
173                 info = Sliver_LV.info(self.container)
174                 logger.verbose('sliver_libvirt: %s is NOT RUNNING...\n%s'%(self.name, info))
175                 return False
176         except:
177             print "Unexpected error:", sys.exc_info()
178
179     ''' PRIVATE/HELPER/STATIC METHODS '''
180     @staticmethod
181     def getConnection():
182         ''' Helper method to get a connection to the LXC driver of Libvirt '''
183         conn = libvirt.open('lxc:///')
184         if conn == None:
185             print 'Failed to open connection to LXC hypervisor'
186             sys.exit(1)
187         else: return conn
188
189     @staticmethod
190     def info(dom):
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)
194
195