capsh --user is available from f14 only
[lxc-userspace.git] / lxcsu-internal
1 #!/usr/bin/python
2
3
4 import setns
5 import os
6
7 from argparse import ArgumentParser
8
9 drop_capabilities='cap_sys_admin,cap_sys_boot,cap_sys_module'
10
11 debug = False
12
13 def getarch(f):
14     output = os.popen('readelf -h %s 2>&1'%f).readlines()
15     classlines = [x for x in output if ('Class' in x.split(':')[0])]
16     line = classlines[0]
17     c = line.split(':')[1]
18     if ('ELF64' in c):
19         return 'x86_64'
20     elif ('ELF32' in c):
21         return 'i686'
22     else:
23         raise Exception('Could not determine architecture')
24
25 def umount(fs_dir):
26     output = os.popen('/bin/umount %s 2>&1'%fs_dir).read()
27     return ('device is busy' not in output)
28
29 def main ():
30     parser = ArgumentParser()
31     parser.add_argument("-n", "--nonet",
32                         action="store_true", dest="netns", default=False,
33                         help="Don't enter network namespace")
34     parser.add_argument("-m", "--nomnt",
35                         action="store_true", dest="mntns", default=False,
36                         help="Don't enter mount namespace")
37     parser.add_argument("-p", "--nopid",
38                         action="store_true", dest="pidns", default=False,
39                         help="Don't enter pid namespace")
40     parser.add_argument("-r", "--root",
41                         action="store_true", dest="root", default=False,
42                         help="Enter as root: be careful")
43     parser.add_argument("-d","--debug",
44                         action='store_true', dest='debug', default=False,
45                         help="debug option")
46     parser.add_argument ("slice_name")
47     parser.add_argument ("command_to_run",nargs="*")
48
49     args = parser.parse_args()
50     slice_name=args.slice_name
51     # support for either setting debug at the top of this file, or on the command-line
52     if args.debug:
53         global debug
54         debug=True
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') or (cmdline.startswith("init [")):
83                     slice_spec = slice_path
84                     arch = getarch('/proc/%s/exe'%pid)
85                     break
86         except Exception,e:
87             if debug: 
88                 import traceback
89                 print "BEG lxcsu - ignoring exception"
90                 traceback.print_exc()
91                 print "END lxcsu - ignoring exception"
92             pass
93
94     if (not slice_spec or not pid):
95         print "Not started: %s"%slice_name
96         exit(1)
97
98     if arch is None:
99         arch = 'x86_64'
100
101     # Set sysctls specific to slice
102     sysctl_dir = '/etc/planetlab/vsys-attributes/%s'%slice_name
103     if (os.access(sysctl_dir,0)):
104         entries = os.listdir(sysctl_dir)
105         for e in entries:
106             prefix = 'vsys_sysctl.'
107             if (e.startswith(prefix)):
108                 sysctl_file = '/'.join([sysctl_dir,e])
109                 sysctl_name = e[len(prefix):]
110                 sysctl_val = open(sysctl_file).read()
111                 os.system('sysctl -w %s=%s'%(sysctl_name,sysctl_val)) 
112         
113     # Enter cgroups
114     try:
115         for subsystem in ['cpuset','memory','blkio']:
116             open('/sys/fs/cgroup/%s/libvirt/lxc/%s/tasks'%(subsystem,slice_name),'w').write(str(os.getpid()))
117
118     except:
119         print "Error assigning resources: %s"%slice_name
120         exit(1)
121
122     try:
123         open('/sys/fs/cgroup/cpuacct/system/libvirtd.service/libvirt/lxc/%s/tasks'%slice_name,'w').write(str(os.getpid()))
124     except:
125         print "Error assigning cpuacct: %s" % slice_name
126         exit(1)
127
128     # If the slice is frozen, then we'll get an EBUSY when trying to write to the task
129     # list for the freezer cgroup. Since the user couldn't do anything anyway, it's best
130     # in this case to error out the shell. (an alternative would be to un-freeze it,
131     # add the task, and re-freeze it)
132     try:
133         f=open('/sys/fs/cgroup/freezer/libvirt/lxc/%s/tasks'%(slice_name),'w')
134         f.write(str(os.getpid()))
135         # note: we need to call f.close() explicitly, or we'll get an exception in
136         # the object destructor, which will not be caught
137         f.close()
138     except:
139         print "Error adding task to freezer cgroup. Slice is probably frozen: %s" % slice_name
140         exit(1)
141
142     setns.chcontext('/proc/%s/ns/uts'%pid)
143     setns.chcontext('/proc/%s/ns/ipc'%pid)
144     
145     if (not args.pidns):
146         setns.chcontext('/proc/%s/ns/pid'%pid)
147
148     if (not args.netns):
149         setns.chcontext('/proc/%s/ns/net'%pid)
150
151     if (not args.mntns):
152         setns.chcontext('/proc/%s/ns/mnt'%pid)
153
154     
155
156     proc_mounted = False
157     if (not os.access('/proc/self',0)):
158         proc_mounted = True
159         setns.proc_mount()
160
161     
162
163     # cgroups is not yet LXC-safe, so we need to use the course grained access control
164     # strategy of unmounting the filesystem
165
166     umount_result = True
167     for subsystem in ['cpuset','cpu,cpuacct','memory','devices','freezer','net_cls','blkio','perf_event']:
168         fs_path = '/sys/fs/cgroup/%s'%subsystem
169         if (not umount(fs_path)):
170             print "Error disabling cgroup access"
171             exit(1)
172
173     if (not umount('/sys/fs/cgroup')):
174         print "Error disabling cgroup access"
175         exit(1)
176
177     pid = os.fork()
178
179     # capsh has a --user option starting with f14
180     # so if only for f12 we need to fake this one
181     #
182     # capsh.c does essentially the following when invoked with --user:
183     #       pwd = getpwnam(user); ...
184     #       ngroups = MAX_GROUPS; 
185     #       status = getgrouplist(user, pwd->pw_gid, groups, &ngroups); ...
186     #       status = setgroups(ngroups, groups); ...
187     #       status = setgid(pwd->pw_gid); ...
188     #       status = setuid(pwd->pw_uid); ...
189     # however we cannot simulate that ourselves because if we did in this process then
190     # capsh could not be allowed to mess with caps any more
191
192     def getuid (slicename):
193         import pwd
194         try:
195             return pwd.getpwnam(slicename).pw_uid
196         except:
197             return
198
199     if (pid == 0):
200         cap_arg = '--drop='+drop_capabilities
201
202         if (not args.root):
203             uid = getuid (slice_name)
204             if not uid:
205                 print "lxcsu-internal could not spot %s in /etc/passwd - exiting"%slice_name
206                 exit(1)
207             exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--uid=%s'%uid,'--','--login',]+args.command_to_run
208 # once we can drop f12, it would be nicer to instead go for
209 #            exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--user=%s'%slice_name,'--','--login',]+args.command_to_run
210         else:
211             exec_args = [arch,'/usr/sbin/capsh','--','--login']+args.command_to_run
212
213         os.environ['SHELL'] = '/bin/sh'
214         os.environ['HOME'] = '/home/%s'%slice_name
215         os.environ['LD_PRELOAD'] = '/etc/planetlab/lib/bind_public.so'
216         os.chdir("/home/%s"%(slice_name))
217         if debug: print 'lxcsu-internal:execv:','/usr/bin/setarch',exec_args
218         os.execv('/usr/bin/setarch',exec_args)
219     else:
220         setns.proc_umount()
221         _,status = os.waitpid(pid,0)
222         exit(os.WEXITSTATUS(status))
223
224 if __name__ == '__main__':
225     main()