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