Fix hostname.
[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 unix account
80         command = ['/usr/sbin/useradd', '-s', '/bin/sh', name]
81         logger.log_call(command, timeout=15*60)
82
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()
86         try:
87             dom = conn.lookupByName(name)
88         except:
89             dom = conn.defineXML(config)
90         logger.verbose('lxc_create: %s -> %s'%(name, Sliver_LV.info(dom)))
91
92     @staticmethod
93     def destroy(name):
94         logger.verbose ('sliver_libvirt: %s destroy'%(name))
95         
96         dir = '/vservers/%s'%(name)
97         lxc_log = '%s/lxc.log'%(dir)
98
99         conn = Sliver_LV.getConnection()
100
101         try:
102             command = ['/usr/sbin/userdel', name]
103             logger.log_call(command, timeout=15*60)
104             
105             # Destroy libvirt domain
106             dom = conn.lookupByName(name)
107             dom.destroy()
108             dom.undefine()
109
110             # Remove rootfs of destroyed domain
111             shutil.rmtree("/vservers/%s"%name)
112         except:
113             logger.verbose('sliver_libvirt: Unexpected error on %s: %s'%(name, sys.exc_info()[0]))
114     
115     def __init__(self, rec):
116         self.name = rec['name']
117         logger.verbose ('sliver_libvirt: %s init'%(self.name))
118          
119         self.dir = '/vservers/%s'%(self.name)
120         
121         # Assume the directory with the image and config files
122         # are in place
123         
124         self.keys = ''
125         self.rspec = {}
126         self.slice_id = rec['slice_id']
127         self.disk_usage_initialized = False
128         self.initscript = ''
129         self.enabled = True
130         conn = Sliver_LV.getConnection()
131         try:
132             self.container = conn.lookupByName(self.name)
133         except:
134             logger.verbose('sliver_libvirt: Unexpected error on %s: %s'%(self.name, sys.exc_info()[0]))
135
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)  
140     
141     def start(self, delay=0):
142         ''' Just start the sliver '''
143         print "LIBVIRT %s start"%(self.name)
144
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()
149         else:
150             logger.verbose('sliver_libvirt: sliver %s already started'%(self.name))
151             
152     def stop(self):
153         logger.verbose('sliver_libvirt: %s stop'%(self.name))
154         
155         try:
156             self.container.destroy()
157         except:
158             print "Unexpected error:", sys.exc_info()[0]
159     
160     def is_running(self):
161         ''' Return True if the domain is running '''
162         logger.verbose('sliver_libvirt: %s is_running'%(self.name))
163         try:
164             [state, _, _, _, _] = self.container.info()
165             if state == libvirt.VIR_DOMAIN_RUNNING:
166                 logger.verbose('sliver_libvirt: %s is RUNNING'%(self.name))
167                 return True
168             else:
169                 info = Sliver_LV.info(self.container)
170                 logger.verbose('sliver_libvirt: %s is NOT RUNNING...\n%s'%(self.name, info))
171                 return False
172         except:
173             print "Unexpected error:", sys.exc_info()
174
175     ''' PRIVATE/HELPER/STATIC METHODS '''
176     @staticmethod
177     def getConnection():
178         ''' Helper method to get a connection to the LXC driver of Libvirt '''
179         conn = libvirt.open('lxc:///')
180         if conn == None:
181             print 'Failed to open connection to LXC hypervisor'
182             sys.exit(1)
183         else: return conn
184
185     @staticmethod
186     def info(dom):
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)
190
191