9 from string import Template
14 import plnode.bwlimit as bwlimit
15 from initscript import Initscript
16 from sliver_libvirt import Sliver_Libvirt
18 class Sliver_LXC(Sliver_Libvirt, Initscript):
19 """This class wraps LXC commands"""
23 # Need to add a tag at myplc to actually use this account
26 REF_IMG_BASE_DIR = '/vservers/.lvref'
27 CON_BASE_DIR = '/vservers'
29 def __init__ (self, rec):
31 Sliver_Libvirt.__init__ (self,rec)
32 Initscript.__init__ (self,name)
34 def configure (self, rec):
35 Sliver_Libvirt.configure (self,rec)
37 # in case we update nodemanager..
38 self.install_and_enable_vinit()
39 # do the configure part from Initscript
40 Initscript.configure(self,rec)
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)
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()
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")
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)
66 # Get the type of image from vref myplc tags specified as:
72 logger.log('sliver_libvirt: %s: WARNING - no vref attached defaults to lxc-f14' % (name))
73 vref = "lxc-f14-x86_64"
75 refImgDir = os.path.join(Sliver_LXC.REF_IMG_BASE_DIR, vref)
76 containerDir = os.path.join(Sliver_LXC.CON_BASE_DIR, name)
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))
84 # Snapshot the reference image fs (assume the reference image is in its own
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)
90 command = ['chmod', '755', containerDir]
91 logger.log_call(command, timeout=15*60)
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")
103 # TODO: set quotas...
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('_', '-')
109 # Add slices group if not already present
111 group = grp.getgrnam('slices')
113 command = ['/usr/sbin/groupadd', 'slices']
114 logger.log_call(command, timeout=15*60)
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)
122 # Create PK pair keys to connect from the host to the guest without
123 # password... maybe remove the need for authentication inside the
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)
128 command = ['chown', '-R', '%s.slices'%name, '/home/%s/.ssh'%name]
129 logger.log_call(command, timeout=30)
131 command = ['mkdir', '%s/root/.ssh'%containerDir]
132 logger.log_call(command, timeout=10)
134 command = ['cp', '/home/%s/.ssh/id_rsa.pub'%name, '%s/root/.ssh/authorized_keys'%containerDir]
135 logger.log_call(command, timeout=30)
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)
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
147 logger.log("Cannot find XML template %s"%template_filename_sliceimage)
150 with open(template_filename) as f:
151 template = Template(f.read())
152 xml = template.substitute(name=name, xid=xid)
154 logger.log('Failed to parse or use XML template file %s'%template_filename)
157 # Lookup for the sliver before actually
158 # defining it, just in case it was already defined.
160 dom = conn.lookupByName(name)
162 dom = conn.defineXML(xml)
163 logger.verbose('lxc_create: %s -> %s'%(name, Sliver_Libvirt.debuginfo(dom)))
168 logger.verbose ('sliver_lxc: %s destroy'%(name))
169 conn = Sliver_Libvirt.getConnection(Sliver_LXC.TYPE)
171 containerDir = Sliver_LXC.CON_BASE_DIR + '/%s'%(name)
174 # Destroy libvirt domain
175 dom = conn.lookupByName(name)
177 logger.verbose('sliver_lxc: Domain %s does not exist!' % name)
182 logger.verbose('sliver_lxc: Domain %s not running... continuing.' % name)
187 logger.verbose('sliver_lxc: Domain %s is not defined... continuing.' % name)
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)
193 # Remove rootfs of destroyed domain
194 command = ['btrfs', 'subvolume', 'delete', containerDir]
195 logger.log_call(command, timeout=60)
197 logger.verbose('sliver_libvirt: %s destroyed.'%name)