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