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