Needed to define a password for the slice user (e.g. *) to allow ssh access. If not...
[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 slices group if not already present
70         command = ['/usr/sbin/groupadd slices']
71         logger.log_call(command, timeout=15*60)
72         # Add unix account
73         command = ['/usr/sbin/useradd', '-g', 'slices', '-s', '/bin/sh', name, '-p', '*']
74         logger.log_call(command, timeout=15*60)
75
76         # Get a connection and lookup for the sliver before actually
77         # defining it, just in case it was already defined.
78         conn = Sliver_LV.getConnection()
79         try:
80             dom = conn.lookupByName(name)
81         except:
82             dom = conn.defineXML(config)
83         logger.verbose('lxc_create: %s -> %s'%(name, Sliver_LV.info(dom)))
84
85     @staticmethod
86     def destroy(name):
87         logger.verbose ('sliver_libvirt: %s destroy'%(name))
88         
89         dir = '/vservers/%s'%(name)
90         lxc_log = '%s/lxc.log'%(dir)
91
92         conn = Sliver_LV.getConnection()
93
94         try:
95             command = ['/usr/sbin/userdel', '-r', name]
96             logger.log_call(command, timeout=15*60)
97             
98             # Destroy libvirt domain
99             dom = conn.lookupByName(name)
100             dom.destroy()
101             dom.undefine()
102
103             # Remove rootfs of destroyed domain
104             shutil.rmtree("/vservers/%s"%name)
105         except:
106             logger.verbose('sliver_libvirt: Unexpected error on %s: %s'%(name, sys.exc_info()[0]))
107     
108     def __init__(self, rec):
109         self.name = rec['name']
110         logger.verbose ('sliver_libvirt: %s init'%(self.name))
111          
112         self.dir = '/vservers/%s'%(self.name)
113         
114         # Assume the directory with the image and config files
115         # are in place
116         
117         self.keys = ''
118         self.rspec = {}
119         self.slice_id = rec['slice_id']
120         self.disk_usage_initialized = False
121         self.initscript = ''
122         self.enabled = True
123         conn = Sliver_LV.getConnection()
124         try:
125             self.container = conn.lookupByName(self.name)
126         except:
127             logger.verbose('sliver_libvirt: Unexpected error on %s: %s'%(self.name, sys.exc_info()[0]))
128
129     def configure(self, rec):
130         ''' Allocate resources and fancy configuration stuff '''
131         logger.verbose('sliver_libvirt: %s configure'%(self.name)) 
132         accounts.Account.configure(self, rec)  
133     
134     def start(self, delay=0):
135         ''' Just start the sliver '''
136         print "LIBVIRT %s start"%(self.name)
137
138         # Check if it's running to avoid throwing an exception if the
139         # domain was already running, create actually means start
140         if not self.is_running():
141             self.container.create()
142         else:
143             logger.verbose('sliver_libvirt: sliver %s already started'%(self.name))
144             
145     def stop(self):
146         logger.verbose('sliver_libvirt: %s stop'%(self.name))
147         
148         try:
149             self.container.destroy()
150         except:
151             print "Unexpected error:", sys.exc_info()[0]
152     
153     def is_running(self):
154         ''' Return True if the domain is running '''
155         logger.verbose('sliver_libvirt: %s is_running'%(self.name))
156         try:
157             [state, _, _, _, _] = self.container.info()
158             if state == libvirt.VIR_DOMAIN_RUNNING:
159                 logger.verbose('sliver_libvirt: %s is RUNNING'%(self.name))
160                 return True
161             else:
162                 info = Sliver_LV.info(self.container)
163                 logger.verbose('sliver_libvirt: %s is NOT RUNNING...\n%s'%(self.name, info))
164                 return False
165         except:
166             print "Unexpected error:", sys.exc_info()
167
168     ''' PRIVATE/HELPER/STATIC METHODS '''
169     @staticmethod
170     def getConnection():
171         ''' Helper method to get a connection to the LXC driver of Libvirt '''
172         conn = libvirt.open('lxc:///')
173         if conn == None:
174             print 'Failed to open connection to LXC hypervisor'
175             sys.exit(1)
176         else: return conn
177
178     @staticmethod
179     def info(dom):
180         ''' Helper method to get a "nice" output of the info struct for debug'''
181         [state, maxmem, mem, ncpu, cputime] = dom.info()
182         return '%s is %s, maxmem = %s, mem = %s, ncpu = %s, cputime = %s' % (dom.name(), states.get(state, state), maxmem, mem, ncpu, cputime)
183
184