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