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