remove unnecessary proc remounts, prevent setting LD_PRELOAD if the library doesn...
[lxc-userspace.git] / lxcsu
1 #!/usr/bin/python
2
3 import sys
4 import os
5 import setns
6
7 from argparse import ArgumentParser
8
9 drop_capabilities='cap_sys_admin,cap_sys_boot,cap_sys_module'
10
11 # can set to True here, but also use the -d option
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("-i","--internal",
45                         action="store_true", dest="internal", default=False,
46                         help="does *not* prepend '-- -c' to arguments - or invoke lxcsu-internal")
47     parser.add_argument("-d","--debug",
48                         action='store_true', dest='debug', default=False,
49                         help="debug option")
50     parser.add_argument("-s","--nosliceuid", dest="nosliceuid", default=False,
51                         help="do not change to slice uid inside of slice")
52     parser.add_argument ("slice_name")
53     parser.add_argument ("command_to_run",nargs="*")
54
55     args = parser.parse_args()
56     slice_name=args.slice_name
57
58     # unless we run the symlink 'lxcsu-internal', or we specify the -i option, prepend '--' '-c'
59     if sys.argv[0].find('internal')>=0: args.internal=True
60
61     if len(args.command_to_run)>0 and (args.command_to_run[0] == "/sbin/service"):
62         # A quick hack to support nodemanager interfaces.py when restarting
63         # networking in a slice.
64         args.nosliceuid = True
65
66     # plain lxcsu
67     if not args.internal:
68         # no command given: enter interactive shell
69         if not args.command_to_run: args.command_to_run=['/bin/sh']
70         args.command_to_run = [ '-c' ] + [" ".join(args.command_to_run)]
71
72     # support for either setting debug at the top of this file, or on the command-line
73     if args.debug:
74         global debug
75         debug=True
76
77     try:
78         cmd = 'grep %s /proc/*/cgroup | grep freezer'%slice_name
79         output = os.popen(cmd).readlines()
80     except:
81         print "Error finding slice %s"%slice_name
82         exit(1)
83
84     slice_spec = None
85
86     # provide a default as this is not always properly computed
87     arch = None
88
89     for e in output:
90         try:
91             l = e.rstrip()
92             path = l.split(':')[0]  
93             comp = l.rsplit(':')[-1]
94             slice_name_check = comp.rsplit('/')[-1]
95             if debug: print "dealing with >%s<"%slice_name_check
96             
97             if (slice_name_check == slice_name):
98                 if debug: print "found %s"%slice_name
99                 slice_path = path
100                 pid = slice_path.split('/')[2]
101                 cmdline = open('/proc/%s/cmdline'%pid).read().rstrip('\n\x00')
102                 if (cmdline == '/sbin/init') or (cmdline.startswith("init [")):
103                     slice_spec = slice_path
104                     arch = getarch('/proc/%s/exe'%pid)
105                     break
106         except Exception,e:
107             if debug: 
108                 import traceback
109                 print "BEG lxcsu - ignoring exception"
110                 traceback.print_exc()
111                 print "END lxcsu - ignoring exception"
112             pass
113
114     if (not slice_spec or not pid):
115         print "Not started: %s"%slice_name
116         exit(1)
117
118     if arch is None:
119         arch = 'x86_64'
120
121     # Set sysctls specific to slice
122     sysctls = []
123     sysctl_dir = '/etc/planetlab/vsys-attributes/%s'%slice_name
124     if (os.access(sysctl_dir,0)):
125         entries = os.listdir(sysctl_dir)
126         for e in entries:
127             prefix = 'vsys_sysctl.'
128             if (e.startswith(prefix)):
129                 sysctl_file = '/'.join([sysctl_dir,e])
130                 sysctl_name = e[len(prefix):]
131                 sysctl_val = open(sysctl_file).read()
132                 sysctls.append((sysctl_file, sysctl_name, sysctl_val))
133
134     # Enter cgroups
135     try:
136         for subsystem in ['cpuset','memory','blkio']:
137             open('/sys/fs/cgroup/%s/libvirt/lxc/%s/tasks'%(subsystem,slice_name),'w').write(str(os.getpid()))
138
139     except:
140         print "Error assigning resources: %s"%slice_name
141         exit(1)
142
143     try:
144         open('/sys/fs/cgroup/cpuacct/system/libvirtd.service/libvirt/lxc/%s/tasks'%slice_name,'w').write(str(os.getpid()))
145     except:
146         print "Error assigning cpuacct: %s" % slice_name
147         exit(1)
148
149     # If the slice is frozen, then we'll get an EBUSY when trying to write to the task
150     # list for the freezer cgroup. Since the user couldn't do anything anyway, it's best
151     # in this case to error out the shell. (an alternative would be to un-freeze it,
152     # add the task, and re-freeze it)
153     try:
154         f=open('/sys/fs/cgroup/freezer/libvirt/lxc/%s/tasks'%(slice_name),'w')
155         f.write(str(os.getpid()))
156         # note: we need to call f.close() explicitly, or we'll get an exception in
157         # the object destructor, which will not be caught
158         f.close()
159     except:
160         print "Error adding task to freezer cgroup. Slice is probably frozen: %s" % slice_name
161         exit(1)
162
163     setns.chcontext('/proc/%s/ns/uts'%pid)
164     setns.chcontext('/proc/%s/ns/ipc'%pid)
165     
166     if (not args.pidns):
167         setns.chcontext('/proc/%s/ns/pid'%pid)
168
169     if (not args.netns):
170         setns.chcontext('/proc/%s/ns/net'%pid)
171
172     if (not args.mntns):
173         setns.chcontext('/proc/%s/ns/mnt'%pid)
174
175     proc_mounted = False
176     if (not os.access('/proc/self',0)):
177         proc_mounted = True
178         setns.proc_mount()
179
180     for (sysctl_file, sysctl_name, sysctl_val) in sysctls:
181                 for fn in ["/sbin/sysctl", "/usr/sbin/sysctl", "/bin/sysctl", "/usr/bin/sysctl"]:
182                     if os.path.exists(fn):
183                         os.system('%s -w %s=%s'%(fn, sysctl_name,sysctl_val))
184                         break
185                 else:
186                     print "Error: image does not have a sysctl binary"
187
188     # cgroups is not yet LXC-safe, so we need to use the coarse grained access control
189     # strategy of unmounting the filesystem
190
191     umount_result = True
192     for subsystem in ['cpuset','cpu,cpuacct','memory','devices','freezer','net_cls','blkio','perf_event']:
193         fs_path = '/sys/fs/cgroup/%s'%subsystem
194         if (not umount(fs_path)):
195             print "Error disabling cgroup access"
196             exit(1)
197
198     if (not umount('/sys/fs/cgroup')):
199         print "Error disabling cgroup access"
200         exit(1)
201
202     pid = os.fork()
203
204     # capsh has a --user option starting with f14
205     # so if only for f12 we need to fake this one
206     #
207     # capsh.c does essentially the following when invoked with --user:
208     #       pwd = getpwnam(user); ...
209     #       ngroups = MAX_GROUPS; 
210     #       status = getgrouplist(user, pwd->pw_gid, groups, &ngroups); ...
211     #       status = setgroups(ngroups, groups); ...
212     #       status = setgid(pwd->pw_gid); ...
213     #       status = setuid(pwd->pw_uid); ...
214     # however we cannot simulate that ourselves because if we did in this process then
215     # capsh could not be allowed to mess with caps any more
216
217     def getuid (slicename):
218         import pwd
219         try:
220             return pwd.getpwnam(slicename).pw_uid
221         except:
222             return
223
224     if (pid == 0):
225         cap_arg = '--drop='+drop_capabilities
226
227         if (not args.root):
228             if (args.nosliceuid):
229                 # we still want to drop capabilities, but don't want to switch UIDs
230                 exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--','--login',]+args.command_to_run
231             else:
232                 uid = getuid (slice_name)
233                 if not uid:
234                     print "lxcsu could not spot %s in /etc/passwd - exiting"%slice_name
235                     exit(1)
236                 exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--uid=%s'%uid,'--','--login',]+args.command_to_run
237 # once we can drop f12, it would be nicer to instead go for
238 #                exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--user=%s'%slice_name,'--','--login',]+args.command_to_run
239         else:
240             exec_args = [arch,'/usr/sbin/capsh','--','--login']+args.command_to_run
241
242         os.environ['SHELL'] = '/bin/sh'
243         os.environ['HOME'] = '/home/%s'%slice_name
244         if os.path.exists('/etc/planetlab/lib/bind_public.so'):
245             os.environ['LD_PRELOAD'] = '/etc/planetlab/lib/bind_public.so'
246         os.chdir("/home/%s"%(slice_name))
247         if debug: print 'lxcsu:execv:','/usr/bin/setarch',exec_args
248         os.execv('/usr/bin/setarch',exec_args)
249     else:
250         setns.proc_umount()
251         _,status = os.waitpid(pid,0)
252         exit(os.WEXITSTATUS(status))
253
254 if __name__ == '__main__':
255     main()