Some code refactor
[nodemanager.git] / sliver_lxc.py
1 #
2
3 """LXC slivers"""
4
5 import accounts
6 import logger
7 import subprocess
8 import os
9 import libvirt
10 import sys
11
12 def test_template():
13
14     xml_template = """
15     <domain type='lxc'>
16         <name>test_1</name>
17         <memory>32768</memory>
18         <os>
19             <type>exe</type>
20             <init>/bin/sh</init>
21         </os>
22         <vcpu>1</vcpu>
23         <clock offset='utc'/>
24         <on_poweroff>destroy</on_poweroff>
25         <on_reboot>restart</on_reboot>
26         <on_crash>destroy</on_crash>
27         <devices>
28             <emulator>/usr/libexec/libvirt_lxc</emulator>
29             <filesystem type='mount'>
30                 <source dir='/vservers/test_1/rootfs/'/>
31                 <target dir='/'/>
32             </filesystem>
33             <interface type='network'>
34                 <source network='default'/>
35             </interface>
36             <console type='pty' />
37         </devices>
38     </domain>"""
39
40     return xml_template
41
42 def createConnection():
43     conn = libvirt.open('lxc:///')
44     if conn == None:
45         print 'Failed to open connection to LXC hypervisor'
46         sys.exit(1)
47     else: return conn
48
49
50 states = {
51     libvirt.VIR_DOMAIN_NOSTATE: 'no state',
52     libvirt.VIR_DOMAIN_RUNNING: 'running',
53     libvirt.VIR_DOMAIN_BLOCKED: 'blocked on resource',
54     libvirt.VIR_DOMAIN_PAUSED: 'paused by user',
55     libvirt.VIR_DOMAIN_SHUTDOWN: 'being shut down',
56     libvirt.VIR_DOMAIN_SHUTOFF: 'shut off',
57     libvirt.VIR_DOMAIN_CRASHED: 'crashed',
58 }
59
60 def info(dom):
61     [state, maxmem, mem, ncpu, cputime] = dom.info()
62     return '%s is %s,\nmaxmem = %s, mem = %s, ncpu = %s, cputime = %s' % (dom.name(), states.get(state, state), maxmem, mem, ncpu, cputime)
63
64 class Sliver_LXC(accounts.Account):
65     """This class wraps LXC commands"""
66    
67     SHELL = '/bin/sh' 
68     # Using /bin/bash triggers destroy root/site_admin (?!?)
69     TYPE = 'sliver.LXC'
70     # Need to add a tag at myplc to actually use this account
71     # type = 'sliver.LXC'
72
73     def __init__(self, rec):
74         self.name = rec['name']
75         print "LXC __init__ %s"%(self.name)
76         logger.verbose ('sliver_lxc: %s init'%self.name)
77          
78         self.dir = '/vservers/%s'%(self.name)
79         
80         # Assume the directory with the image and config files
81         # are in place
82         
83         self.config = '%s/config'%(self.dir)
84         self.fstab  = '%s/fstab'%(self.dir)
85         self.lxc_log  = '%s/lxc.log'%(self.dir)
86         self.keys = ''
87         self.rspec = {}
88         self.slice_id = rec['slice_id']
89         self.disk_usage_initialized = False
90         self.initscript = ''
91         self.enabled = True
92         self.connection = createConnection()
93
94     @staticmethod
95     def create(name, rec = None):
96         ''' Create dirs, copy fs image, lxc_create '''
97         print "LXC create %s"%(name)
98         logger.verbose ('sliver_lxc: %s create'%name)
99         dir = '/vservers/%s'%(name)
100         config = '%s/config'%(dir)
101         lxc_log = '%s/lxc.log'%(dir)
102         
103         if not (os.path.isdir(dir) and 
104             os.access(dir, os.R_OK | os.W_OK | os.X_OK)):
105             print 'lxc_create: directory %s does not exist or wrong perms'%(dir)
106             return
107         # Assume for now that the directory is there and with a FS
108         command=[]
109         # be verbose
110         command += ['/bin/bash','-x',]
111         command += ['/usr/bin/lxc-create', '-n', name, '-f', config, '&']
112         print command
113         #subprocess.call(command, stdin=open('/dev/null', 'r'), stdout=open('/dev/null', 'w'), stderr=subprocess.STDOUT, shell=False)
114         conn = createConnection()
115         try:
116             dom0 = conn.lookupByName(name)
117         except:
118             dom0 = conn.defineXML(test_template())
119         print info(dom0)
120
121     @staticmethod
122     def destroy(name):
123         ''' lxc_destroy '''
124         print "LXC destroy %s"%(name)
125         dir = '/vservers/%s'%(name)
126         lxc_log = '%s/lxc.log'%(dir)
127         command=[]
128         command += ['/usr/bin/lxc-destroy', '-n', name]
129
130         subprocess.call(command, stdin=open('/dev/null', 'r'), stdout=open('/dev/null', 'w'), stderr=subprocess.STDOUT, shell=False)
131         print "LXC destroy DONE"
132
133     def configure(self, rec):
134         print "LXC configure %s"%(self.name) 
135
136     def start(self, delay=0):
137         ''' Check existence? lxc_start '''
138         print "LXC start %s"%(self.name)
139         command=[]
140         command += ['/usr/bin/lxc-start', '-n', self.name, '-d']
141         print command
142         subprocess.call(command, stdin=open('/dev/null', 'r'), stdout=open('/dev/null', 'w'), stderr=subprocess.STDOUT, shell=False)
143
144     def stop(self):
145         ''' lxc_stop '''
146         print "LXC stop %s"%(self.name)
147     
148     def is_running(self):
149         print "LXC is_running %s"%(self.name)
150         command = []
151         command += ['/usr/bin/lxc-info -n %s'%(self.name)]
152         print command
153         p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
154         state = p.communicate()[0].split(' ')[2]
155         print state
156         if state == 'RUNNING': return True
157         else: return False
158
159