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