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