added a main function
[lxc-userspace.git] / lxcsu
1 #!/usr/bin/python
2
3
4 import setns
5 import os
6 import sys
7
8 from optparse import OptionParser
9
10 drop_capabilities='cap_sys_admin,cap_sys_boot,cap_sys_module'
11
12 def getarch(f):
13     output = os.popen('readelf -h %s 2>&1'%f).readlines()
14     classlines = [x for x in output if ('Class' in x.split(':')[0])]
15     line = classlines[0]
16     c = line.split(':')[1]
17     if ('ELF64' in c):
18         return 'x86_64'
19     elif ('ELF32' in c):
20         return 'i686'
21     else:
22         raise Exception('Could not determine architecture')
23
24 def umount(fs_dir):
25     output = os.popen('/bin/umount %s 2>&1'%fs_dir).read()
26     return ('device is busy' not in fs_dir)
27
28 def main ():
29     parser = OptionParser()
30     parser.add_option("-n", "--nonet",
31                       action="store_true", dest="netns", default=False,
32                       help="Don't enter network namespace")
33     parser.add_option("-m", "--nomnt",
34                       action="store_true", dest="mntns", default=False,
35                       help="Don't enter mount namespace")
36     parser.add_option("-p", "--nopid",
37                       action="store_true", dest="pidns", default=False,
38                       help="Don't enter pid namespace")
39     parser.add_option("-r", "--root",
40                       action="store_true", dest="root", default=False,
41                       help="Enter as root: be careful")
42
43     (options, args) = parser.parse_args()
44
45     try:
46         slice_name = args[0]
47     except IndexError:
48         print "You must specify a vm name"
49         exit(1)
50
51     try:
52         cmd = 'grep %s /proc/*/cgroup | grep freezer'%slice_name
53         output = os.popen(cmd).readlines()
54     except:
55         print "Error finding slice %s"%slice_name
56         exit(1)
57
58     slice_spec = None
59
60     # xxx fixme xxx - provide a default as this is not always properly computed
61     arch = 'x86_64'
62
63     for e in output:
64         try:
65             l = e.rstrip()
66             path = l.split(':')[0]  
67             comp = l.rsplit(':')[-1]
68             slice_name_check = comp.rsplit('/')[-1]
69             
70             if (slice_name_check == slice_name):
71                 slice_path = path
72                 pid = slice_path.split('/')[2]
73                 cmdline = open('/proc/%s/cmdline'%pid).read().rstrip('\n\x00')
74                 if (cmdline == '/sbin/init'):
75                     slice_spec = slice_path
76                     arch = getarch('/proc/%s/exe'%pid)
77                     break
78         except:
79             break
80
81     if (not slice_spec or not pid):
82         print "Not started: %s"%slice_name
83         exit(1)
84
85     # Enter cgroups
86     try:
87         for subsystem in ['cpuset','memory','blkio']:
88             open('/sys/fs/cgroup/%s/libvirt/lxc/%s/tasks'%(subsystem,slice_name),'w').write(str(os.getpid()))
89
90     except:
91         print "Error assigning resources: %s"%slice_name
92         exit(1)
93
94     try:
95         open('/sys/fs/cgroup/cpuacct/system/libvirtd.service/libvirt/lxc/%s/tasks'%slice_name,'w').write(str(os.getpid()))
96     except:
97         print "Error assigning cpuacct: %s" % slice_name
98         exit(1)
99
100     # If the slice is frozen, then we'll get an EBUSY when trying to write to the task
101     # list for the freezer cgroup. Since the user couldn't do anything anyway, it's best
102     # in this case to error out the shell. (an alternative would be to un-freeze it,
103     # add the task, and re-freeze it)
104     try:
105         f=open('/sys/fs/cgroup/freezer/libvirt/lxc/%s/tasks'%(slice_name),'w')
106         f.write(str(os.getpid()))
107         # note: we need to call f.close() explicitly, or we'll get an exception in
108         # the object destructor, which will not be caught
109         f.close()
110     except:
111         print "Error adding task to freezer cgroup. Slice is probably frozen: %s" % slice_name
112         exit(1)
113
114     setns.chcontext('/proc/%s/ns/uts'%pid)
115     setns.chcontext('/proc/%s/ns/ipc'%pid)
116
117     if (not options.netns):
118         setns.chcontext('/proc/%s/ns/net'%pid)
119
120     if (not options.mntns):
121         open('/proc/lxcsu','w').write(pid)
122
123     if (not options.pidns):
124         open('/proc/pidsu','w').write(pid)
125
126     # cgroups is not yet LXC-safe, so we need to use the course grained access control
127     # strategy of unmounting the filesystem
128
129     umount_result = True
130     for subsystem in ['cpuset','cpu,cpuacct','memory','devices','freezer','net_cls','blkio','perf_event']:
131         fs_path = '/sys/fs/cgroup/%s'%subsystem
132         if (not umount(fs_path)):
133             print "Error disabling cgroup access"
134             exit(1)
135
136     if (not umount('/sys/fs/cgroup')):
137         print "Error disabling cgroup access"
138         exit(1)
139
140     pid = os.fork()
141
142     if (pid == 0):
143         cap_arg = '--drop='+drop_capabilities
144
145         if (not options.root):
146             exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--','--login']+args[1:]
147         else:
148             exec_args = [arch,'/usr/sbin/capsh','--','--login']+args[1:]
149
150         os.environ['SHELL'] = '/bin/sh'
151         os.execv('/usr/bin/setarch',exec_args)
152     else:
153         _,status = os.waitpid(pid,0)
154         exit(os.WEXITSTATUS(status))
155
156 if __name__ == '__main__':
157     main()