New file sliver_libvirt. Basic code to create, start and check if it's running. Destr...
[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 states = {
13     libvirt.VIR_DOMAIN_NOSTATE: 'no state',
14     libvirt.VIR_DOMAIN_RUNNING: 'running',
15     libvirt.VIR_DOMAIN_BLOCKED: 'blocked on resource',
16     libvirt.VIR_DOMAIN_PAUSED: 'paused by user',
17     libvirt.VIR_DOMAIN_SHUTDOWN: 'being shut down',
18     libvirt.VIR_DOMAIN_SHUTOFF: 'shut off',
19     libvirt.VIR_DOMAIN_CRASHED: 'crashed',
20 }
21
22 class Sliver_LV(accounts.Account):
23     """This class wraps LibVirt commands"""
24    
25     SHELL = '/bin/sh' 
26     # Using /bin/bash triggers destroy root/site_admin (?!?)
27     TYPE = 'sliver.LIBVIRT'
28     # Need to add a tag at myplc to actually use this account
29     # type = 'sliver.LIBVIRT'
30
31     def __init__(self, rec):
32         self.name = rec['name']
33         print "LIBVIRT %s __init__"%(self.name)
34         logger.verbose ('sliver_libvirt: %s init'%(self.name))
35          
36         self.dir = '/vservers/%s'%(self.name)
37         
38         # Assume the directory with the image and config files
39         # are in place
40         
41         self.config = '%s/config.xml'%(self.dir)
42         self.lxc_log  = '%s/log'%(self.dir)
43         self.keys = ''
44         self.rspec = {}
45         self.slice_id = rec['slice_id']
46         self.disk_usage_initialized = False
47         self.initscript = ''
48         self.enabled = True
49         conn = Sliver_LV.getConnection()
50         try:
51             self.container = conn.lookupByName(self.name)
52         except:
53             print "Unexpected error:", sys.exc_info()[0]
54
55     @staticmethod
56     def create(name, rec = None):
57         ''' Create dirs, copy fs image, lxc_create '''
58         print "LIBVIRT %s create"%(name)
59         logger.verbose ('sliver_libvirt: %s create'%(name))
60         dir = '/vservers/%s'%(name)
61         config = '%s/config.xml'%(dir)
62         lxc_log = '%s/log'%(dir)
63         
64         if not (os.path.isdir(dir) and 
65             os.access(dir, os.R_OK | os.W_OK | os.X_OK)):
66             logger.verbose('lxc_create: directory %s does not exist or wrong perms'%(dir))
67             return
68        
69         # Get a connection and lookup for the sliver before actually
70         # defining it, just in case it was already defined.
71         conn = Sliver_LV.getConnection()
72         try:
73             dom = conn.lookupByName(name)
74         except:
75             xml = open(config).read()  
76             dom = conn.defineXML(xml)
77         print Sliver_LV.info(dom)
78
79     @staticmethod
80     def destroy(name):
81         ''' NEVER CALLED... Figure out when and what to do... '''
82         
83         print "LIBVIRT %s 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 = conn.Sliver_LV.getConnection()
90
91         try:
92             dom = conn.lookupByName(name)
93             conn.destroy(dom)
94             conn.undefine(dom)
95             print Sliver_LV.info(dom)
96         except:
97             logger.verbose('sliver_libvirt: %s domain does not exists'%(name))
98             print "Unexpected error:", sys.exc_info()[0]
99
100
101     def configure(self, rec):
102         ''' Allocate resources and fancy configuration stuff '''
103         print "LIBVIRT %s configure"%(self.name) 
104         logger.verbose('sliver_libvirt: %s configure'%(self.name)) 
105
106     def start(self, delay=0):
107         ''' Just start the sliver '''
108         print "LIBVIRT %s start"%(self.name)
109         if self.rspec['enabled'] <= 0:
110             logger.log('sliver_libvirt: not starting %s, is not enabled'%(self.name))
111             return
112         else:
113             logger.log('sliver_libvirt: %s starting...' % (self.name))
114
115         # Check if it's running to avoid throwing an exception if the
116         # domain was already running, create actually means start
117         if not self.is_running():
118             self.container.create()
119         else:
120             logger.verbose('sliver_libvirt: sliver %s already started'%(self.name))
121             
122     def stop(self):
123         ''' NEVER CALLED... Figure out when and what to do... '''
124         
125         print "LIBVIRT %s stop"%(self.name)
126         logger.verbose('sliver_libvirt: %s stop'%(self.name))
127         
128         try:
129             self.container.destroy()
130         except:
131             print "Unexpected error:", sys.exc_info()[0]
132     
133     def is_running(self):
134         ''' Return True if the domain is running '''
135         print "LIBVIRT %s is_running"%(self.name)
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