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