Fix path for vsh
[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 from string import Template
10
11 import libvirt
12
13 import logger
14 import plnode.bwlimit as bwlimit
15 from initscript import Initscript
16 from sliver_libvirt import Sliver_Libvirt
17
18 class Sliver_LXC(Sliver_Libvirt, Initscript):
19     """This class wraps LXC commands"""
20
21     SHELL = '/usr/sbin/vsh'
22     TYPE = 'sliver.LXC'
23     # Need to add a tag at myplc to actually use this account
24     # type = 'sliver.LXC'
25
26     REF_IMG_BASE_DIR = '/vservers/.lvref'
27     CON_BASE_DIR     = '/vservers'
28
29     def __init__ (self, rec):
30         name=rec['name']
31         Sliver_Libvirt.__init__ (self,rec)
32         Initscript.__init__ (self,name)
33
34     def configure (self, rec):
35         Sliver_Libvirt.configure (self,rec)
36
37         # in case we update nodemanager..
38         self.install_and_enable_vinit()
39         # do the configure part from Initscript
40         Initscript.configure(self,rec)
41
42     def start(self, delay=0):
43         if 'enabled' in self.rspec and self.rspec['enabled'] <= 0:
44             logger.log('sliver_lxc: not starting %s, is not enabled'%self.name)
45             return
46         # the generic /etc/init.d/vinit script is permanently refreshed, and enabled
47         self.install_and_enable_vinit()
48         Sliver_Libvirt.start (self, delay)
49         # if a change has occured in the slice initscript, reflect this in /etc/init.d/vinit.slice
50         self.refresh_slice_vinit()
51
52     def rerun_slice_vinit (self):
53         """This is called whenever the initscript code changes"""
54         # xxx - todo - not sure exactly how to:
55         # (.) invoke something in the guest
56         # (.) which options of systemctl should be used to trigger a restart
57         # should not prevent the first run from going fine hopefully
58         logger.log("WARNING: sliver_lxc.rerun_slice_vinit not implemented yet")
59
60     @staticmethod
61     def create(name, rec=None):
62         ''' Create dirs, copy fs image, lxc_create '''
63         logger.verbose ('sliver_lxc: %s create'%(name))
64         conn = Sliver_Libvirt.getConnection(Sliver_LXC.TYPE)
65
66         # Get the type of image from vref myplc tags specified as:
67         # pldistro = lxc
68         # fcdistro = squeeze
69         # arch x86_64
70         vref = rec['vref']
71         if vref is None:
72             logger.log('sliver_libvirt: %s: WARNING - no vref attached defaults to lxc-f14' % (name))
73             vref = "lxc-f14-x86_64"
74
75         refImgDir    = os.path.join(Sliver_LXC.REF_IMG_BASE_DIR, vref)
76         containerDir = os.path.join(Sliver_LXC.CON_BASE_DIR, name)
77
78         # check the template exists -- there's probably a better way..
79         if not os.path.isdir(refImgDir):
80             logger.log('sliver_lxc: %s: ERROR Could not create sliver - reference image %s not found' % (name,vref))
81             logger.log('sliver_lxc: %s: ERROR Expected reference image in %s'%(name,refImgDir))
82             return
83
84         # Snapshot the reference image fs (assume the reference image is in its own
85         # subvolume)
86         command = ['btrfs', 'subvolume', 'snapshot', refImgDir, containerDir]
87         if not logger.log_call(command, timeout=15*60):
88             logger.log('sliver_lxc: ERROR Could not create BTRFS snapshot at', containDir)
89             return
90         command = ['chmod', '755', containerDir]
91         logger.log_call(command, timeout=15*60)
92
93         # customize prompt for slice owner, + LD_PRELOAD for transparently wrap bind
94         dot_profile=os.path.join(containerDir,"root/.profile")
95         ld_preload_msg="""# by default, we define this setting so that calls to bind(2),
96 # when invoked on 0.0.0.0, get transparently redirected to the public interface of this node
97 # see https://svn.planet-lab.org/wiki/LxcPortForwarding"""
98         with open(dot_profile,'w') as f:
99             f.write("export PS1='%s@\H \$ '\n"%(name))
100             f.write("%s\n"%ld_preload_msg)
101             f.write("export LD_PRELOAD=/etc/planetlab/lib/bind_public.so\n")
102
103         # TODO: set quotas...
104
105         # Set hostname. A valid hostname cannot have '_'
106         #with open(os.path.join(containerDir, 'etc/hostname'), 'w') as f:
107         #    print >>f, name.replace('_', '-')
108
109         # Add slices group if not already present
110         try:
111             group = grp.getgrnam('slices')
112         except:
113             command = ['/usr/sbin/groupadd', 'slices']
114             logger.log_call(command, timeout=15*60)
115
116         # Add unix account (TYPE is specified in the subclass)
117         command = ['/usr/sbin/useradd', '-g', 'slices', '-s', Sliver_LXC.SHELL, name, '-p', '*']
118         logger.log_call(command, timeout=15*60)
119         command = ['mkdir', '/home/%s/.ssh'%name]
120         logger.log_call(command, timeout=15*60)
121
122         # Create PK pair keys to connect from the host to the guest without
123         # password... maybe remove the need for authentication inside the
124         # guest?
125         command = ['su', '-s', '/bin/bash', '-c', 'ssh-keygen -t rsa -N "" -f /home/%s/.ssh/id_rsa'%(name)]
126         logger.log_call(command, timeout=60)
127
128         command = ['chown', '-R', '%s.slices'%name, '/home/%s/.ssh'%name]
129         logger.log_call(command, timeout=30)
130
131         command = ['mkdir', '%s/root/.ssh'%containerDir]
132         logger.log_call(command, timeout=10)
133
134         command = ['cp', '/home/%s/.ssh/id_rsa.pub'%name, '%s/root/.ssh/authorized_keys'%containerDir]
135         logger.log_call(command, timeout=30)
136
137         # Lookup for xid and create template after the user is created so we
138         # can get the correct xid based on the name of the slice
139         xid = bwlimit.get_xid(name)
140
141         # Template for libvirt sliver configuration
142         template_filename_sliceimage = os.path.join(Sliver_LXC.REF_IMG_BASE_DIR,'lxc_template.xml')
143         if os.path.isfile (template_filename_sliceimage):
144             logger.log("WARNING: using compat template %s"%template_filename_sliceimage)
145             template_filename=template_filename_sliceimage
146         else:
147             logger.log("Cannot find XML template %s"%template_filename_sliceimage)
148             return
149         try:
150             with open(template_filename) as f:
151                 template = Template(f.read())
152                 xml  = template.substitute(name=name, xid=xid)
153         except IOError:
154             logger.log('Failed to parse or use XML template file %s'%template_filename)
155             return
156
157         # Lookup for the sliver before actually
158         # defining it, just in case it was already defined.
159         try:
160             dom = conn.lookupByName(name)
161         except:
162             dom = conn.defineXML(xml)
163         logger.verbose('lxc_create: %s -> %s'%(name, Sliver_Libvirt.debuginfo(dom)))
164
165
166     @staticmethod
167     def destroy(name):
168         logger.verbose ('sliver_lxc: %s destroy'%(name))
169         conn = Sliver_Libvirt.getConnection(Sliver_LXC.TYPE)
170
171         containerDir = Sliver_LXC.CON_BASE_DIR + '/%s'%(name)
172
173         try:
174             # Destroy libvirt domain
175             dom = conn.lookupByName(name)
176         except:
177             logger.verbose('sliver_lxc: Domain %s does not exist!' % name)
178
179         try:
180             dom.destroy()
181         except:
182             logger.verbose('sliver_lxc: Domain %s not running... continuing.' % name)
183
184         try:
185             dom.undefine()
186         except:
187             logger.verbose('sliver_lxc: Domain %s is not defined... continuing.' % name)
188
189         # Remove user after destroy domain to force logout
190         command = ['/usr/sbin/userdel', '-f', '-r', name]
191         logger.log_call(command, timeout=15*60)
192
193         # Remove rootfs of destroyed domain
194         command = ['btrfs', 'subvolume', 'delete', containerDir]
195         logger.log_call(command, timeout=60)
196
197         logger.verbose('sliver_libvirt: %s destroyed.'%name)
198