Copy the rootfs from a reference image.
[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 libvirt
10 import sys
11 import shutil
12
13 from string import Template
14
15 states = {
16     libvirt.VIR_DOMAIN_NOSTATE: 'no state',
17     libvirt.VIR_DOMAIN_RUNNING: 'running',
18     libvirt.VIR_DOMAIN_BLOCKED: 'blocked on resource',
19     libvirt.VIR_DOMAIN_PAUSED: 'paused by user',
20     libvirt.VIR_DOMAIN_SHUTDOWN: 'being shut down',
21     libvirt.VIR_DOMAIN_SHUTOFF: 'shut off',
22     libvirt.VIR_DOMAIN_CRASHED: 'crashed',
23 }
24
25 class Sliver_LV(accounts.Account):
26     """This class wraps LibVirt commands"""
27    
28     SHELL = '/bin/sh' 
29
30     # Need to add a tag at myplc to actually use this account
31     # type = 'sliver.LIBVIRT'
32     TYPE = 'sliver.LIBVIRT'
33     
34
35     @staticmethod
36     def create(name, rec = None):
37         ''' Create dirs, copy fs image, lxc_create '''
38         logger.verbose ('sliver_libvirt: %s create'%(name))
39         dir = '/vservers/%s'%(name)
40
41         # Template for libvirt sliver configuration
42         template = Template(open('/vservers/.lvref/config_template.xml').read())
43         config = template.substitute(name=name)
44         
45         lxc_log = '%s/log'%(dir)
46        
47         # Get the type of image from vref myplc tags specified as:
48         # pldistro = lxc
49         # fcdistro = squeeze
50         # arch x86_64
51         vref = rec['vref']
52         if vref is None:
53             logger.log("sliver_libvirt: %s: WARNING - no vref attached defaults to lxc-debian"%(name))
54             vref = "lxc-squeeze-x86_64"
55
56         # check the template exists -- there's probably a better way..
57         if not os.path.isdir ("/vservers/.lvref/%s"%vref):
58             logger.log ("sliver_libvirt: %s: ERROR Could not create sliver - reference image %s not found"%(name,vref))
59             return
60         
61         # Copy the reference image fs
62         # shutil.copytree("/vservers/.lvref/%s"%vref, "/vservers/%s"%name, symlinks=True)
63         command = ['cp', '-r', '/vservers/.lvref/%s'%vref, '/vservers/%s'%name]
64         logger.log_call(command, timeout=15*60)
65
66         # Set hostname
67         file('/vservers/%s/etc/hostname' % name, 'w').write(name)
68         
69         # Add unix account
70         command = ['/usr/sbin/useradd', '-s', '/bin/sh', name]
71         logger.log_call(command, timeout=15*60)
72
73         # Get a connection and lookup for the sliver before actually
74         # defining it, just in case it was already defined.
75         conn = Sliver_LV.getConnection()
76         try:
77             dom = conn.lookupByName(name)
78         except:
79             dom = conn.defineXML(config)
80         logger.verbose('lxc_create: %s -> %s'%(name, Sliver_LV.info(dom)))
81
82     @staticmethod
83     def destroy(name):
84         logger.verbose ('sliver_libvirt: %s destroy'%(name))
85         
86         dir = '/vservers/%s'%(name)
87         lxc_log = '%s/lxc.log'%(dir)
88
89         conn = Sliver_LV.getConnection()
90
91         try:
92             command = ['/usr/sbin/userdel', name]
93             logger.log_call(command, timeout=15*60)
94             
95             # Destroy libvirt domain
96             dom = conn.lookupByName(name)
97             dom.destroy()
98             dom.undefine()
99
100             # Remove rootfs of destroyed domain
101             shutil.rmtree("/vservers/%s"%name)
102         except:
103             logger.verbose('sliver_libvirt: Unexpected error on %s: %s'%(name, sys.exc_info()[0]))
104     
105     def __init__(self, rec):
106         self.name = rec['name']
107         logger.verbose ('sliver_libvirt: %s init'%(self.name))
108          
109         self.dir = '/vservers/%s'%(self.name)
110         
111         # Assume the directory with the image and config files
112         # are in place
113         
114         self.keys = ''
115         self.rspec = {}
116         self.slice_id = rec['slice_id']
117         self.disk_usage_initialized = False
118         self.initscript = ''
119         self.enabled = True
120         conn = Sliver_LV.getConnection()
121         try:
122             self.container = conn.lookupByName(self.name)
123         except:
124             logger.verbose('sliver_libvirt: Unexpected error on %s: %s'%(self.name, sys.exc_info()[0]))
125
126     def configure(self, rec):
127         ''' Allocate resources and fancy configuration stuff '''
128         logger.verbose('sliver_libvirt: %s configure'%(self.name)) 
129         accounts.Account.configure(self, rec)  
130     
131     def start(self, delay=0):
132         ''' Just start the sliver '''
133         print "LIBVIRT %s start"%(self.name)
134
135         # Check if it's running to avoid throwing an exception if the
136         # domain was already running, create actually means start
137         if not self.is_running():
138             self.container.create()
139         else:
140             logger.verbose('sliver_libvirt: sliver %s already started'%(self.name))
141             
142     def stop(self):
143         logger.verbose('sliver_libvirt: %s stop'%(self.name))
144         
145         try:
146             self.container.destroy()
147         except:
148             print "Unexpected error:", sys.exc_info()[0]
149     
150     def is_running(self):
151         ''' Return True if the domain is running '''
152         logger.verbose('sliver_libvirt: %s is_running'%(self.name))
153         try:
154             [state, _, _, _, _] = self.container.info()
155             if state == libvirt.VIR_DOMAIN_RUNNING:
156                 logger.verbose('sliver_libvirt: %s is RUNNING'%(self.name))
157                 return True
158             else:
159                 info = Sliver_LV.info(self.container)
160                 logger.verbose('sliver_libvirt: %s is NOT RUNNING...\n%s'%(self.name, info))
161                 return False
162         except:
163             print "Unexpected error:", sys.exc_info()
164
165     ''' PRIVATE/HELPER/STATIC METHODS '''
166     @staticmethod
167     def getConnection():
168         ''' Helper method to get a connection to the LXC driver of Libvirt '''
169         conn = libvirt.open('lxc:///')
170         if conn == None:
171             print 'Failed to open connection to LXC hypervisor'
172             sys.exit(1)
173         else: return conn
174
175     @staticmethod
176     def info(dom):
177         ''' Helper method to get a "nice" output of the info struct for debug'''
178         [state, maxmem, mem, ncpu, cputime] = dom.info()
179         return '%s is %s, maxmem = %s, mem = %s, ncpu = %s, cputime = %s' % (dom.name(), states.get(state, state), maxmem, mem, ncpu, cputime)
180
181