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