d5f26cc225063e26c3f4e13f1da93ea1b131799f
[lxc-userspace.git] / lxcsu
1 #!/usr/bin/python
2
3 import sys
4 import os
5 import setns
6 import pdb
7
8 from argparse import ArgumentParser
9
10 drop_capabilities='cap_sys_admin,cap_sys_boot,cap_sys_module'
11
12 # can set to True here, but also use the -d option
13 debug = False
14
15 def getarch(f):
16     output = os.popen('readelf -h %s 2>&1'%f).readlines()
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 get_cgroup_subdirs_for_pid(pid):
28     cgroup_info_file = '/proc/%s/cgroup'%pid
29     cgroup_lines = open(cgroup_info_file).read().splitlines()
30     
31     subdirs = {}
32     for line in cgroup_lines:
33         try:
34             _, cgroup_name, subdir = line.split(':')
35             subdirs[cgroup_name] = subdir
36         except Exception, e:
37             print "Error reading cgroup info: %s"%str(e)
38             pass
39     
40     return subdirs
41         
42     
43 def umount(fs_dir, opts=''):
44     output = os.popen('/bin/umount %s %s 2>&1'%(opts, fs_dir)).read()
45     return ('device is busy' not in output)
46
47 def main ():
48     parser = ArgumentParser()
49     parser.add_argument("-n", "--nonet",
50                                         action="store_true", dest="no_netns", default=False,
51                                         help="Don't enter network namespace")
52     parser.add_argument("-m", "--nomnt",
53                                         action="store_true", dest="no_mntns", default=False,
54                                         help="Don't enter mount namespace")
55     parser.add_argument("-p", "--nopid",
56                                         action="store_true", dest="no_pidns", default=False,
57                                         help="Don't enter pid namespace")
58     parser.add_argument("-r", "--root",
59                                         action="store_true", dest="root", default=False,
60                                         help="Enter as root: be careful")
61     parser.add_argument("-i","--internal",
62                                         action="store_true", dest="internal", default=False,
63                                         help="does *not* prepend '-- -c' to arguments - or invoke lxcsu-internal")
64     parser.add_argument("-d","--debug",
65                                         action='store_true', dest='debug', default=False,
66                                         help="debug option")
67     parser.add_argument("-s","--nosliceuid",
68                                         action='store_true', dest="nosliceuid", default=False,
69                                         help="do not change to slice uid inside of slice")
70     parser.add_argument("-o","--noslicehome",
71                                         action='store_true', dest="noslicehome", default=False,
72                                         help="do not change to slice home directory inside of slice")
73
74     if os.path.exists("/etc/lxcsu_default"):
75         defaults = parser.parse_args(file("/etc/lxcsu_default","r").read().split())
76         parser.set_defaults(**defaults.__dict__)
77
78     parser.add_argument ("slice_name")
79     parser.add_argument ("command_to_run",nargs="*")
80
81     args = parser.parse_args()
82     slice_name=args.slice_name
83
84     # unless we run the symlink 'lxcsu-internal', or we specify the -i option, prepend '--' '-c'
85     if sys.argv[0].find('internal')>=0: args.internal=True
86
87     if len(args.command_to_run)>0 and (args.command_to_run[0] == "/sbin/service"):
88         # A quick hack to support nodemanager interfaces.py when restarting
89         # networking in a slice.
90         args.nosliceuid = True
91
92     # plain lxcsu
93     if not args.internal:
94         # no command given: enter interactive shell
95         if not args.command_to_run: args.command_to_run=['/bin/sh']
96         args.command_to_run = [ '-c' ] + [" ".join(args.command_to_run)]
97
98     # support for either setting debug at the top of this file, or on the command-line
99     if args.debug:
100         global debug
101         debug=True
102
103     try:
104         cmd = '/usr/bin/virsh --connect lxc:/// domid %s'%slice_name
105         # convert to int as a minimal raincheck
106         driver_pid = int(os.popen(cmd).read().strip())
107         # locate the pid for the - expected - single child, that would be the init for that VM
108         #init_pid = int(open("/proc/%s/task/%s/children"%(driver_pid,driver_pid)).read().strip())
109         init_pid = int(os.popen('pgrep -P %s'%driver_pid).readlines()[0].strip())
110         # Thierry: I am changing the code below to use child_pid instead of driver_pid
111         # for the namespace handling features, that I was able to check
112         # I've left the other ones as they were, i.e. using driver_pid, but I suspect
113         # they chould be changed as well
114
115     except:
116         print "Domain %s not found"%slice_name
117         exit(1)
118
119     if not driver_pid or not init_pid:
120         print "Domain %s not started"%slice_name
121         exit(1)
122
123     if debug: print "Found driver_pid",driver_pid,'and init_pid=',init_pid
124     # xxx probably init_pid here too
125     arch = getarch('/proc/%s/exe'%driver_pid)
126
127     # Set sysctls specific to slice
128     sysctls = []
129     sysctl_dir = '/etc/planetlab/vsys-attributes/%s'%slice_name
130     if (os.access(sysctl_dir,0)):
131         entries = os.listdir(sysctl_dir)
132         for e in entries:
133             prefix = 'vsys_sysctl.'
134             if (e.startswith(prefix)):
135                 sysctl_file = '/'.join([sysctl_dir,e])
136                 sysctl_name = e[len(prefix):]
137                 sysctl_val = open(sysctl_file).read()
138                 sysctls.append((sysctl_file, sysctl_name, sysctl_val))
139
140     # xxx probably init_pid here too
141     subdirs = get_cgroup_subdirs_for_pid(driver_pid) 
142     sysfs_root = '/sys/fs/cgroup'
143
144     # If the slice is frozen, then we'll get an EBUSY when trying to write to the task
145     # list for the freezer cgroup. Since the user couldn't do anything anyway, it's best
146     # in this case to error out the shell. (an alternative would be to un-freeze it,
147     # add the task, and re-freeze it)
148     # Enter cgroups
149     current_cgroup = ''
150     for subsystem in ['cpuset','memory','blkio','cpuacct','cpuacct,cpu','freezer']:
151         try:
152             current_cgroup = subsystem
153
154             # There seems to be a bug in the cgroup schema: cpuacct,cpu can become cpu,cpuacct
155             # We need to handle both
156             task_path_alt = None
157             try:
158                subsystem_comps = subsystem.split(',')
159                subsystem_comps.reverse()
160                subsystem_alt = ','.join(subsystem_comps)
161                tasks_path_alt = [sysfs_root, subsystem_alt, subdirs[subsystem], 'tasks']
162             except Exception,e:
163                 pass
164                
165             tasks_path = [sysfs_root,subsystem,subdirs[subsystem],'tasks']
166             tasks_path_str = '/'.join(tasks_path)
167      
168             try:
169                 f = open(tasks_path_str, 'w')
170             except:
171                 tasks_path_alt_str = '/'.join(tasks_path_alt)
172                 f = open(tasks_path_alt_str, 'w')
173
174             f.write(str(os.getpid()))
175             if (subsystem=='freezer'):
176                 f.close()
177
178         except Exception,e:
179             if (not subdirs.has_key(subsystem)):
180                 pass
181             else:
182                 if debug: print e 
183                 print "Error assigning cgroup %s (pid=%s) for slice %s"%(current_cgroup,driver_pid, slice_name)
184                 exit(1)
185
186
187     def chcontext (path):
188         retcod = setns.chcontext (path)
189         if retcod != 0:
190             print 'WARNING - setns(%s)=>%s (ignored)'%(path,retcod)
191         return retcod
192
193     # Use init_pid and not driver_pid to locate reference namespaces
194     ref_ns = "/proc/%s/ns/"%init_pid
195
196     if True:                    chcontext(ref_ns+'uts')
197     if True:                    chcontext(ref_ns+'ipc')
198         
199     if (not args.no_pidns):     chcontext(ref_ns+'pid')
200     if (not args.no_netns):     chcontext(ref_ns+'net')
201     if (not args.no_mntns):     chcontext(ref_ns+'mnt')
202
203     proc_mounted = False
204     if (not os.access('/proc/self',0)):
205         proc_mounted = True
206         setns.proc_mount()
207
208     for (sysctl_file, sysctl_name, sysctl_val) in sysctls:
209         for fn in ["/sbin/sysctl", "/usr/sbin/sysctl", "/bin/sysctl", "/usr/bin/sysctl"]:
210             if os.path.exists(fn):
211                 os.system('%s -w %s=%s  >/dev/null 2>&1'%(fn, sysctl_name,sysctl_val))
212                 break
213             else:
214                 print "Error: image does not have a sysctl binary"
215
216     # cgroups is not yet LXC-safe, so we need to use the coarse grained access control
217     # strategy of unmounting the filesystem
218
219     umount_result = True
220     for subsystem in ['cpuset','cpu,cpuacct','memory','devices','freezer','net_cls','blkio','perf_event','systemd']:
221         fs_path = '/sys/fs/cgroup/%s'%subsystem
222         if (not umount(fs_path,'-l')):
223             print 'WARNING - umount failed (ignored) with path=',fs_path
224             pass
225             # Leaving these comments for historical reference
226             #print "Error disabling cgroup access"
227             #exit(1) - Don't need this because failure here implies failure in the call to umount /sys/fs/cgroup
228
229     if (not umount('/sys/fs/cgroup')):
230         print "Error disabling cgroup access"
231         exit(1)
232
233     fork_pid = os.fork()
234
235     # capsh has a --user option starting with f14
236     # so if only for f12 we need to fake this one
237     #
238     # capsh.c does essentially the following when invoked with --user:
239     #           pwd = getpwnam(user); ...
240     #           ngroups = MAX_GROUPS; 
241     #           status = getgrouplist(user, pwd->pw_gid, groups, &ngroups); ...
242     #           status = setgroups(ngroups, groups); ...
243     #           status = setgid(pwd->pw_gid); ...
244     #           status = setuid(pwd->pw_uid); ...
245     # however we cannot simulate that ourselves because if we did in this process then
246     # capsh could not be allowed to mess with caps any more
247
248     def getuid (slicename):
249         import pwd
250         try:
251             return pwd.getpwnam(slicename).pw_uid
252         except:
253             return
254
255     if (fork_pid == 0):
256         cap_arg = '--drop='+drop_capabilities
257
258         if (not args.root):
259             if (args.nosliceuid):
260                 # we still want to drop capabilities, but don't want to switch UIDs
261                 exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--','--login',]+args.command_to_run
262             else:
263                 uid = getuid (slice_name)
264                 if not uid:
265                     print "lxcsu could not spot %s in /etc/passwd - exiting"%slice_name
266                     exit(1)
267                 exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--uid=%s'%uid,'--','--login',]+args.command_to_run
268 # once we can drop f12, it would be nicer to instead go for
269 # exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--user=%s'%slice_name,'--','--login',]+args.command_to_run
270         else:
271             exec_args = [arch,'/usr/sbin/capsh','--','--login']+args.command_to_run
272
273         os.environ['SHELL'] = '/bin/sh'
274         if os.path.exists('/etc/planetlab/lib/bind_public.so'):
275             os.environ['LD_PRELOAD'] = '/etc/planetlab/lib/bind_public.so'
276         if not args.noslicehome:
277             os.environ['HOME'] = '/home/%s'%slice_name
278             os.chdir("/home/%s"%(slice_name))
279         if debug: print 'lxcsu:execv:','/usr/bin/setarch',exec_args
280         os.execv('/usr/bin/setarch',exec_args)
281     else:
282         setns.proc_umount()
283         _,status = os.waitpid(fork_pid,0)
284         exit(os.WEXITSTATUS(status))
285
286 if __name__ == '__main__':
287         main()