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