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