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