Refactor of code to allow several virt techs. Minor bugs. Closes #8.
[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 os.path
10 import libvirt
11 import sys
12 import shutil
13
14 from string import Template
15
16 STATES = {
17     libvirt.VIR_DOMAIN_NOSTATE: 'no state',
18     libvirt.VIR_DOMAIN_RUNNING: 'running',
19     libvirt.VIR_DOMAIN_BLOCKED: 'blocked on resource',
20     libvirt.VIR_DOMAIN_PAUSED: 'paused by user',
21     libvirt.VIR_DOMAIN_SHUTDOWN: 'being shut down',
22     libvirt.VIR_DOMAIN_SHUTOFF: 'shut off',
23     libvirt.VIR_DOMAIN_CRASHED: 'crashed',
24 }
25
26 REF_IMG_BASE_DIR = '/vservers/.lvref'
27 CON_BASE_DIR     = '/vservers'
28
29 connections = dict()
30
31 def getConnection(uri):
32     # TODO: error checking
33     return connections.setdefault(uri, libvirt.open(uri))
34
35 def create(name, xml, rec, conn):
36     ''' Create dirs, copy fs image, lxc_create '''
37     logger.verbose ('sliver_libvirt: %s create'%(name))
38     
39     # Get the type of image from vref myplc tags specified as:
40     # pldistro = lxc
41     # fcdistro = squeeze
42     # arch x86_64
43     vref = rec['vref']
44     if vref is None:
45         logger.log('sliver_libvirt: %s: WARNING - no vref attached defaults to lxc-debian' % (name))
46         vref = "lxc-squeeze-x86_64"
47
48     refImgDir    = os.path.join(REF_IMG_BASE_DIR, vref)
49     containerDir = os.path.join(CON_BASE_DIR, name)
50
51     # check the template exists -- there's probably a better way..
52     if not os.path.isdir(refImgDir):
53         logger.log('sliver_libvirt: %s: ERROR Could not create sliver - reference image %s not found' % (name,vref))
54         return
55
56     # Copy the reference image fs
57     # shutil.copytree("/vservers/.lvref/%s"%vref, "/vservers/%s"%name, symlinks=True)
58     command = ['cp', '-r', refImgDir, containerDir]
59     logger.log_call(command, timeout=15*60)
60
61     # Set hostname. A valid hostname cannot have '_'
62     with open(os.path.join(containerDir, 'etc/hostname'), 'w') as f:
63         print >>f, name.replace('_', '-')
64
65     # Add slices group if not already present
66     command = ['/usr/sbin/groupadd', 'slices']
67     logger.log_call(command, timeout=15*60)
68     
69     # Add unix account (TYPE is specified in the subclass)
70     command = ['/usr/sbin/useradd', '-g', 'slices', '-s', '/bin/sshsh', name, '-p', '*']
71     logger.log_call(command, timeout=15*60)
72     command = ['mkdir', '/home/%s/.ssh'%name]
73     logger.log_call(command, timeout=15*60)
74
75     # Create PK pair keys to connect from the host to the guest without
76     # password... maybe remove the need for authentication inside the
77     # guest?
78     command = ['su', '-s', '/bin/bash', '-c', 'ssh-keygen -t rsa -N "" -f /home/%s/.ssh/id_rsa'%(name)]
79     logger.log_call(command, timeout=15*60)
80     
81     command = ['chown', '-R', '%s.slices'%name, '/home/%s/.ssh'%name]
82     logger.log_call(command, timeout=15*60)
83
84     command = ['cp', '/home/%s/.ssh/id_rsa.pub'%name, '%s/root/.ssh/authorized_keys'%containerDir]
85     logger.log_call(command, timeout=15*60)
86
87     # Get a connection and lookup for the sliver before actually
88     # defining it, just in case it was already defined.
89     try:
90         dom = conn.lookupByName(name)
91     except:
92         dom = conn.defineXML(xml)
93     logger.verbose('lxc_create: %s -> %s'%(name, debuginfo(dom)))
94
95
96 def destroy(name, conn):
97     logger.verbose ('sliver_libvirt: %s destroy'%(name))
98     
99     dir = '/vservers/%s'%(name)
100     lxc_log = '%s/lxc.log'%(dir)
101
102     try:
103         
104         # Destroy libvirt domain
105         dom = conn.lookupByName(name)
106         dom.destroy()
107         dom.undefine()
108
109         # Remove user after destroy domain to force logout
110         command = ['/usr/sbin/userdel', '-f', '-r', name]
111         logger.log_call(command, timeout=15*60)
112         
113         # Remove rootfs of destroyed domain
114         shutil.rmtree("/vservers/%s"%name)
115     except:
116         logger.verbose('sliver_libvirt: Unexpected error on %s: %s'%(name, sys.exc_info()[0]))
117
118
119 def start(dom):
120     ''' Just start the sliver '''
121     print "LIBVIRT %s start"%(dom.name())
122
123     # Check if it's running to avoid throwing an exception if the
124     # domain was already running, create actually means start
125     if not is_running(dom):
126         dom.create()
127     else:
128         logger.verbose('sliver_libvirt: sliver %s already started'%(dom.name()))
129        
130
131 def stop(dom):
132     logger.verbose('sliver_libvirt: %s stop'%(dom.name()))
133     
134     try:
135         dom.destroy()
136     except:
137         print "Unexpected error:", sys.exc_info()[0]
138     
139 def is_running(dom):
140     ''' Return True if the domain is running '''
141     logger.verbose('sliver_libvirt: %s is_running'%dom.name())
142     try:
143         [state, _, _, _, _] = dom.info()
144         if state == libvirt.VIR_DOMAIN_RUNNING:
145             logger.verbose('sliver_libvirt: %s is RUNNING'%(dom.name()))
146             return True
147         else:
148             info = debuginfo(dom)
149             logger.verbose('sliver_libvirt: %s is NOT RUNNING...\n%s'%(dom.name(), info))
150             return False
151     except:
152         print "Unexpected error:", sys.exc_info()
153
154 def debuginfo(dom):
155     ''' Helper method to get a "nice" output of the info struct for debug'''
156     [state, maxmem, mem, ncpu, cputime] = dom.info()
157     return '%s is %s, maxmem = %s, mem = %s, ncpu = %s, cputime = %s' % (dom.name(), STATES.get(state, state), maxmem, mem, ncpu, cputime)
158
159