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