Added support for sysctls
[lxc-userspace.git] / lxcsu-internal
1 #!/usr/bin/python
2
3
4 import setns
5 import os
6 import sys
7
8 from argparse import ArgumentParser
9
10 drop_capabilities='cap_sys_admin,cap_sys_boot,cap_sys_module'
11
12 debug = False
13
14 def getarch(f):
15     output = os.popen('readelf -h %s 2>&1'%f).readlines()
16     if debug: print "readelf output %s lines"%len(output)
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 umount(fs_dir):
28     output = os.popen('/bin/umount %s 2>&1'%fs_dir).read()
29     return ('device is busy' not in fs_dir)
30
31 def main ():
32     parser = ArgumentParser()
33     parser.add_argument("-n", "--nonet",
34                         action="store_true", dest="netns", default=False,
35                         help="Don't enter network namespace")
36     parser.add_argument("-m", "--nomnt",
37                         action="store_true", dest="mntns", default=False,
38                         help="Don't enter mount namespace")
39     parser.add_argument("-p", "--nopid",
40                         action="store_true", dest="pidns", default=False,
41                         help="Don't enter pid namespace")
42     parser.add_argument("-r", "--root",
43                         action="store_true", dest="root", default=False,
44                         help="Enter as root: be careful")
45     parser.add_argument("-d","--debug",
46                         action='store_true', dest='debug', default=False,
47                         help="debug option")
48     parser.add_argument ("slice_name")
49     parser.add_argument ("command_to_run",nargs="*")
50
51     options = parser.parse_args()
52     slice_name=options.slice_name
53     global debug
54     debug=options.debug
55
56     try:
57         cmd = 'grep %s /proc/*/cgroup | grep freezer'%slice_name
58         output = os.popen(cmd).readlines()
59         if debug: print "output of grep freezer has %s lines"%len(output)
60     except:
61         print "Error finding slice %s"%slice_name
62         exit(1)
63
64     slice_spec = None
65
66     # provide a default as this is not always properly computed
67     arch = None
68
69     for e in output:
70         try:
71             l = e.rstrip()
72             path = l.split(':')[0]  
73             comp = l.rsplit(':')[-1]
74             slice_name_check = comp.rsplit('/')[-1]
75             if debug: print "dealing with >%s<"%slice_name_check
76             
77             if (slice_name_check == slice_name):
78                 if debug: print "found %s"%slice_name
79                 slice_path = path
80                 pid = slice_path.split('/')[2]
81                 cmdline = open('/proc/%s/cmdline'%pid).read().rstrip('\n\x00')
82                 if (cmdline == '/sbin/init'):
83                     slice_spec = slice_path
84                     arch = getarch('/proc/%s/exe'%pid)
85                     if debug: print "setting arch",arch
86                     break
87         except Exception,e:
88             if debug: 
89                 import traceback
90                 print "BEG lxcsu - ignoring exception"
91                 traceback.print_exc()
92                 print "END lxcsu - ignoring exception"
93             pass
94
95     if (not slice_spec or not pid):
96         print "Not started: %s"%slice_name
97         exit(1)
98
99     if arch is None:
100         arch = 'x86_64'
101         if debug: print "WARNING: setting arch to default x86_64"
102
103     # Set sysctls specific to slice
104     sysctl_dir = '/etc/planetlab/vsys-attributes/%s'%slice_name
105     if (os.access(sysctl_dir,0)):
106         entries = os.listdir(sysctl_dir)
107         for e in entries:
108             prefix = 'vsys_sysctl.'
109             if (e.startswith(prefix)):
110                 sysctl_file = '/'.join([sysctl_dir,e])
111                 sysctl_name = e[len(prefix):]
112                 sysctl_val = open(sysctl_file).read()
113                 os.system('sysctl -w %s=%s'%(sysctl_name,sysctl_val)) 
114         
115     # Enter cgroups
116     try:
117         for subsystem in ['cpuset','memory','blkio']:
118             open('/sys/fs/cgroup/%s/libvirt/lxc/%s/tasks'%(subsystem,slice_name),'w').write(str(os.getpid()))
119
120     except:
121         print "Error assigning resources: %s"%slice_name
122         exit(1)
123
124     try:
125         open('/sys/fs/cgroup/cpuacct/system/libvirtd.service/libvirt/lxc/%s/tasks'%slice_name,'w').write(str(os.getpid()))
126     except:
127         print "Error assigning cpuacct: %s" % slice_name
128         exit(1)
129
130     # If the slice is frozen, then we'll get an EBUSY when trying to write to the task
131     # list for the freezer cgroup. Since the user couldn't do anything anyway, it's best
132     # in this case to error out the shell. (an alternative would be to un-freeze it,
133     # add the task, and re-freeze it)
134     try:
135         f=open('/sys/fs/cgroup/freezer/libvirt/lxc/%s/tasks'%(slice_name),'w')
136         f.write(str(os.getpid()))
137         # note: we need to call f.close() explicitly, or we'll get an exception in
138         # the object destructor, which will not be caught
139         f.close()
140     except:
141         print "Error adding task to freezer cgroup. Slice is probably frozen: %s" % slice_name
142         exit(1)
143
144     setns.chcontext('/proc/%s/ns/uts'%pid)
145     setns.chcontext('/proc/%s/ns/ipc'%pid)
146
147     if (not options.netns):
148         setns.chcontext('/proc/%s/ns/net'%pid)
149
150     if (not options.mntns):
151         setns.chcontext('/proc/%s/ns/mnt'%pid)
152
153     if (not options.pidns):
154         setns.chcontext('/proc/%s/ns/pid'%pid)
155
156     if (not os.access('/proc/self',0)):
157         setns.proc_mount()
158
159     # cgroups is not yet LXC-safe, so we need to use the course grained access control
160     # strategy of unmounting the filesystem
161
162     umount_result = True
163     for subsystem in ['cpuset','cpu,cpuacct','memory','devices','freezer','net_cls','blkio','perf_event']:
164         fs_path = '/sys/fs/cgroup/%s'%subsystem
165         if (not umount(fs_path)):
166             print "Error disabling cgroup access"
167             exit(1)
168
169     if (not umount('/sys/fs/cgroup')):
170         print "Error disabling cgroup access"
171         exit(1)
172
173     pid = os.fork()
174
175     if (pid == 0):
176         cap_arg = '--drop='+drop_capabilities
177
178         if (not options.root):
179             exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--','--login']+options.command_to_run
180         else:
181             exec_args = [arch,'/usr/sbin/capsh','--','--login']+options.command_to_run
182
183         if debug:
184             print "exec'ing"
185             for arg in exec_args: print ">%s<"%arg
186         os.environ['SHELL'] = '/bin/sh'
187         os.execv('/usr/bin/setarch',exec_args)
188     else:
189         _,status = os.waitpid(pid,0)
190         exit(os.WEXITSTATUS(status))
191
192 if __name__ == '__main__':
193     main()