Improve robustness of LXC and libvirt plugins.
[nodemanager.git] / sliver_lxc.py
1 #
2
3 """LXC slivers"""
4
5 import subprocess
6 import sys
7 import os, os.path
8 import grp
9 import libvirt
10 from string import Template
11
12 import logger
13 import bwlimit
14 import sliver_libvirt
15
16 class Sliver_LXC(sliver_libvirt.Sliver_Libvirt):
17     """This class wraps LXC commands"""
18
19     SHELL = '/bin/sshsh'
20     TYPE = 'sliver.LXC'
21     # Need to add a tag at myplc to actually use this account
22     # type = 'sliver.LXC'
23
24     REF_IMG_BASE_DIR = '/vservers/.lvref'
25     CON_BASE_DIR     = '/vservers'
26
27     @staticmethod
28     def create(name, rec=None):
29         ''' Create dirs, copy fs image, lxc_create '''
30         logger.verbose ('sliver_lxc: %s create'%(name))
31         conn = sliver_libvirt.getConnection(Sliver_LXC.TYPE)
32
33         # Get the type of image from vref myplc tags specified as:
34         # pldistro = lxc
35         # fcdistro = squeeze
36         # arch x86_64
37         vref = rec['vref']
38         if vref is None:
39             logger.log('sliver_libvirt: %s: WARNING - no vref attached defaults to lxc-f14' % (name))
40             vref = "lxc-f14-x86_64"
41
42         refImgDir    = os.path.join(Sliver_LXC.REF_IMG_BASE_DIR, vref)
43         containerDir = os.path.join(Sliver_LXC.CON_BASE_DIR, name)
44
45         # check the template exists -- there's probably a better way..
46         if not os.path.isdir(refImgDir):
47             logger.log('sliver_lxc: %s: ERROR Could not create sliver - reference image %s not found' % (name,vref))
48             logger.log('sliver_lxc: %s: ERROR Expected reference image in %s'%(name,refImgDir))
49             return
50
51         # Snapshot the reference image fs (assume the reference image is in its own
52         # subvolume)
53         command = ['btrfs', 'subvolume', 'snapshot', refImgDir, containerDir]
54         if not logger.log_call(command, timeout=15*60):
55             logger.log('sliver_lxc: ERROR Could not create BTRFS snapshot at', containDir)
56             return
57         command = ['chmod', '755', containerDir]
58         logger.log_call(command, timeout=15*60)
59
60         # customize prompt for slice owner
61         dot_profile=os.path.join(containerDir,"root/.profile")
62         with open(dot_profile,'w') as f:
63             f.write("export PS1='%s@\H \$ '\n"%(name))
64
65         # TODO: set quotas...
66
67         # Set hostname. A valid hostname cannot have '_'
68         #with open(os.path.join(containerDir, 'etc/hostname'), 'w') as f:
69         #    print >>f, name.replace('_', '-')
70
71         # Add slices group if not already present
72         try:
73             group = grp.getgrnam('slices')
74         except:
75             command = ['/usr/sbin/groupadd', 'slices']
76             logger.log_call(command, timeout=15*60)
77
78         # Add unix account (TYPE is specified in the subclass)
79         command = ['/usr/sbin/useradd', '-g', 'slices', '-s', Sliver_LXC.SHELL, name, '-p', '*']
80         logger.log_call(command, timeout=15*60)
81         command = ['mkdir', '/home/%s/.ssh'%name]
82         logger.log_call(command, timeout=15*60)
83
84         # Create PK pair keys to connect from the host to the guest without
85         # password... maybe remove the need for authentication inside the
86         # guest?
87         command = ['su', '-s', '/bin/bash', '-c', 'ssh-keygen -t rsa -N "" -f /home/%s/.ssh/id_rsa'%(name)]
88         logger.log_call(command, timeout=15*60)
89
90         command = ['chown', '-R', '%s.slices'%name, '/home/%s/.ssh'%name]
91         logger.log_call(command, timeout=15*60)
92
93         command = ['mkdir', '%s/root/.ssh'%containerDir]
94         logger.log_call(command, timeout=15*60)
95
96         command = ['cp', '/home/%s/.ssh/id_rsa.pub'%name, '%s/root/.ssh/authorized_keys'%containerDir]
97         logger.log_call(command, timeout=15*60)
98
99         # Lookup for xid and create template after the user is created so we
100         # can get the correct xid based on the name of the slice
101         xid = bwlimit.get_xid(name)
102
103         # Template for libvirt sliver configuration
104         template_filename_sliceimage = os.path.join(Sliver_LXC.REF_IMG_BASE_DIR,'lxc_template.xml')
105         if os.path.isfile (template_filename_sliceimage):
106             logger.log("WARNING: using compat template %s"%template_filename_sliceimage)
107             template_filename=template_filename_sliceimage
108         else:
109             logger.log("Cannot find XML template %s"%template_filename_sliceimage)
110             return
111         try:
112             with open(template_filename) as f:
113                 template = Template(f.read())
114                 xml  = template.substitute(name=name, xid=xid)
115         except IOError:
116             logger.log('Failed to parse or use XML template file %s'%template_filename)
117             return
118
119         # Lookup for the sliver before actually
120         # defining it, just in case it was already defined.
121         try:
122             dom = conn.lookupByName(name)
123         except:
124             dom = conn.defineXML(xml)
125         logger.verbose('lxc_create: %s -> %s'%(name, sliver_libvirt.debuginfo(dom)))
126
127
128     @staticmethod
129     def destroy(name):
130         logger.verbose ('sliver_lxc: %s destroy'%(name))
131         conn = sliver_libvirt.getConnection(Sliver_LXC.TYPE)
132
133         containerDir = Sliver_LXC.CON_BASE_DIR + '/%s'%(name)
134
135         try:
136             # Destroy libvirt domain
137             dom = conn.lookupByName(name)
138         except:
139             logger.verbose('sliver_lxc: Domain %s does not exist!' % name)
140
141         try:
142             dom.destroy()
143         except:
144             logger.verbose('sliver_lxc: Domain %s not running... continuing.' % name)
145
146         try:
147             dom.undefine()
148         except:
149             logger.verbose('sliver_lxc: Domain %s is not defined... continuing.' % name)
150
151         # Remove user after destroy domain to force logout
152         command = ['/usr/sbin/userdel', '-f', '-r', name]
153         logger.log_call(command, timeout=15*60)
154
155         # Remove rootfs of destroyed domain
156         command = ['btrfs', 'subvolume', 'delete', containerDir]
157         logger.log_call(command, timeout=15*60)
158
159         logger.verbose('sliver_libvirt: %s destroyed.'%name)
160