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