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