9 from pwd import getpwnam
10 from string import Template
15 import plnode.bwlimit as bwlimit
16 from initscript import Initscript
17 from sliver_libvirt import Sliver_Libvirt
19 class Sliver_LXC(Sliver_Libvirt, Initscript):
20 """This class wraps LXC commands"""
22 SHELL = '/usr/sbin/vsh'
24 # Need to add a tag at myplc to actually use this account
27 REF_IMG_BASE_DIR = '/vservers/.lvref'
28 CON_BASE_DIR = '/vservers'
30 def __init__ (self, rec):
32 Sliver_Libvirt.__init__ (self,rec)
33 Initscript.__init__ (self,name)
35 def configure (self, rec):
36 Sliver_Libvirt.configure (self,rec)
38 # in case we update nodemanager..
39 self.install_and_enable_vinit()
40 # do the configure part from Initscript
41 Initscript.configure(self,rec)
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)
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()
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")
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)
67 # Get the type of image from vref myplc tags specified as:
73 logger.log('sliver_libvirt: %s: WARNING - no vref attached defaults to lxc-f14' % (name))
74 vref = "lxc-f14-x86_64"
76 refImgDir = os.path.join(Sliver_LXC.REF_IMG_BASE_DIR, vref)
77 containerDir = os.path.join(Sliver_LXC.CON_BASE_DIR, name)
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))
85 # Snapshot the reference image fs (assume the reference image is in its own
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)
91 command = ['chmod', '755', containerDir]
92 logger.log_call(command, timeout=15*60)
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")
104 # TODO: set quotas...
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('_', '-')
110 # Add slices group if not already present
112 group = grp.getgrnam('slices')
114 command = ['/usr/sbin/groupadd', 'slices']
115 logger.log_call(command, timeout=15*60)
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)
123 # Create PK pair keys to connect from the host to the guest without
124 # password... maybe remove the need for authentication inside the
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)
129 command = ['chown', '-R', '%s.slices'%name, '/home/%s/.ssh'%name]
130 logger.log_call(command, timeout=30)
132 command = ['mkdir', '%s/root/.ssh'%containerDir]
133 logger.log_call(command, timeout=10)
135 command = ['cp', '/home/%s/.ssh/id_rsa.pub'%name, '%s/root/.ssh/authorized_keys'%containerDir]
136 logger.log_call(command, timeout=30)
138 logger.log("creating /etc/slicename file in %s" % os.path.join(containerDir,'etc/slicename'))
140 file(os.path.join(containerDir,'etc/slicename'), 'w').write(name)
142 logger.log_exc("exception while creating /etc/slicename")
145 file(os.path.join(containerDir,'etc/slicefamily'), 'w').write(vref)
147 logger.log_exc("exception while creating /etc/slicefamily")
151 uid = getpwnam(name).pw_uid
153 # keyerror will happen if user id was not created successfully
154 logger.log_exc("exception while getting user id")
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))
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)
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
175 logger.log("Cannot find XML template %s"%template_filename_sliceimage)
178 interfaces = Sliver_Libvirt.get_interfaces_xml(rec)
181 with open(template_filename) as f:
182 template = Template(f.read())
183 xml = template.substitute(name=name, interfaces=interfaces)
185 logger.log('Failed to parse or use XML template file %s'%template_filename)
188 # Lookup for the sliver before actually
189 # defining it, just in case it was already defined.
191 dom = conn.lookupByName(name)
193 dom = conn.defineXML(xml)
194 logger.verbose('lxc_create: %s -> %s'%(name, Sliver_Libvirt.debuginfo(dom)))
199 logger.verbose ('sliver_lxc: %s destroy'%(name))
200 conn = Sliver_Libvirt.getConnection(Sliver_LXC.TYPE)
202 containerDir = Sliver_LXC.CON_BASE_DIR + '/%s'%(name)
205 # Destroy libvirt domain
206 dom = conn.lookupByName(name)
208 logger.verbose('sliver_lxc: Domain %s does not exist!' % name)
213 logger.verbose('sliver_lxc: Domain %s not running... continuing.' % name)
218 logger.verbose('sliver_lxc: Domain %s is not defined... continuing.' % name)
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)
224 # Remove rootfs of destroyed domain
225 command = ['btrfs', 'subvolume', 'delete', containerDir]
226 logger.log_call(command, timeout=60)
228 logger.verbose('sliver_libvirt: %s destroyed.'%name)