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