Mostly aesthetic changes and fix a bug in codemux.
[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             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         # TODO: set quotas...
57
58         # Set hostname. A valid hostname cannot have '_'
59         #with open(os.path.join(containerDir, 'etc/hostname'), 'w') as f:
60         #    print >>f, name.replace('_', '-')
61
62         # Add slices group if not already present
63         command = ['/usr/sbin/groupadd', 'slices']
64         logger.log_call(command, timeout=15*60)
65
66         # Add unix account (TYPE is specified in the subclass)
67         command = ['/usr/sbin/useradd', '-g', 'slices', '-s', Sliver_LXC.SHELL, name, '-p', '*']
68         logger.log_call(command, timeout=15*60)
69         command = ['mkdir', '/home/%s/.ssh'%name]
70         logger.log_call(command, timeout=15*60)
71
72         # Create PK pair keys to connect from the host to the guest without
73         # password... maybe remove the need for authentication inside the
74         # guest?
75         command = ['su', '-s', '/bin/bash', '-c', 'ssh-keygen -t rsa -N "" -f /home/%s/.ssh/id_rsa'%(name)]
76         logger.log_call(command, timeout=15*60)
77
78         command = ['chown', '-R', '%s.slices'%name, '/home/%s/.ssh'%name]
79         logger.log_call(command, timeout=15*60)
80
81         command = ['mkdir', '%s/root/.ssh'%containerDir]
82         logger.log_call(command, timeout=15*60)
83
84         command = ['cp', '/home/%s/.ssh/id_rsa.pub'%name, '%s/root/.ssh/authorized_keys'%containerDir]
85         logger.log_call(command, timeout=15*60)
86
87         # Lookup for xid and create template after the user is created so we
88         # can get the correct xid based on the name of the slice
89         xid = bwlimit.get_xid(name)
90
91         # Template for libvirt sliver configuration
92         try:
93             with open(Sliver_LXC.REF_IMG_BASE_DIR + '/config_template.xml') as f:
94                 template = Template(f.read())
95                 xml  = template.substitute(name=name, xid=xid)
96         except IOError:
97             logger.log('Cannot find XML template file')
98             return
99
100         # Lookup for the sliver before actually
101         # defining it, just in case it was already defined.
102         try:
103             dom = conn.lookupByName(name)
104         except:
105             dom = conn.defineXML(xml)
106         logger.verbose('lxc_create: %s -> %s'%(name, lv.debuginfo(dom)))
107
108
109     @staticmethod
110     def destroy(name):
111         logger.verbose ('sliver_lxc: %s destroy'%(name))
112         conn = lv.getConnection(Sliver_LXC.TYPE)
113
114         containerDir = Sliver_LXC.CON_BASE_DIR + '/%s'%(name)
115
116         try:
117             # Destroy libvirt domain
118             dom = conn.lookupByName(name)
119         except:
120             logger.verbose('sliver_lxc: Domain %s does not exist! UNEXPECTED'%name)
121             return
122
123         try:
124             dom.destroy()
125         except:
126             logger.verbose('sliver_lxc: Domain %s not running... continuing.'%name)
127
128         dom.undefine()
129
130         # Remove user after destroy domain to force logout
131         command = ['/usr/sbin/userdel', '-f', '-r', name]
132         logger.log_call(command, timeout=15*60)
133
134         # Remove rootfs of destroyed domain
135         command = ['btrfs', 'subvolume', 'delete', containerDir]
136         logger.log_call(command, timeout=15*60)
137
138         logger.verbose('sliver_libvirt: %s destroyed.'%name)
139