9 from argparse import ArgumentParser
11 # can set to True here, but also use the -d option
15 output = os.popen('readelf -h %s 2>&1'%f).readlines()
16 classlines = [x for x in output if ('Class' in x.split(':')[0])]
18 c = line.split(':')[1]
24 raise Exception('Could not determine architecture')
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()
31 for line in cgroup_lines:
33 _, cgroup_name, subdir = line.split(':')
34 subdirs[cgroup_name] = subdir
36 print "Error reading cgroup info: %s"%str(e)
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)
46 def kvmsu(slice_name, args):
49 # Find MAC addresses of virt interfaces
50 p = os.popen("virsh domiflist %s"%slice_name)
52 m = re.search(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})', line, re.I)
54 mac_addresses.append(m.group())
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
60 f = open('/var/lib/dnsmasq/br-nat.hosts', 'r')
62 for mac in mac_addresses:
63 m = re.search("^%s,[0-9.]+$"%mac, line, re.I)
65 ip_addr = m.group().split(',')[1]
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)
78 # What should happen here?
79 print "Cannot map instance to IP address"
84 def lxcsu(slice_name, args):
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)]
91 # support for either setting debug at the top of this file, or on the command-line
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
109 print "Domain %s not found"%slice_name
112 if not driver_pid or not init_pid:
113 print "Domain %s not started"%slice_name
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)
120 # Set sysctls specific to slice
122 sysctl_dir = '/etc/planetlab/vsys-attributes/%s'%slice_name
123 if (os.access(sysctl_dir,0)):
124 entries = os.listdir(sysctl_dir)
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))
133 # xxx probably init_pid here too
134 subdirs = get_cgroup_subdirs_for_pid(driver_pid)
135 sysfs_root = '/sys/fs/cgroup'
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)
143 for subsystem in ['cpuset','memory','blkio','cpuacct','cpuacct,cpu','freezer']:
145 current_cgroup = subsystem
147 # There seems to be a bug in the cgroup schema: cpuacct,cpu can become cpu,cpuacct
148 # We need to handle both
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']
158 tasks_path = [sysfs_root,subsystem,subdirs[subsystem],'tasks']
159 tasks_path_str = '/'.join(tasks_path)
162 f = open(tasks_path_str, 'w')
164 tasks_path_alt_str = '/'.join(tasks_path_alt)
165 f = open(tasks_path_alt_str, 'w')
167 f.write(str(os.getpid()))
168 if (subsystem=='freezer'):
172 if (not subdirs.has_key(subsystem)):
176 print "Error assigning cgroup %s (pid=%s) for slice %s"%(current_cgroup,driver_pid, slice_name)
180 def chcontext (path):
181 retcod = setns.chcontext (path)
183 print 'WARNING - setns(%s)=>%s (ignored)'%(path,retcod)
186 # Use init_pid and not driver_pid to locate reference namespaces
187 ref_ns = "/proc/%s/ns/"%init_pid
189 if True: chcontext(ref_ns+'uts')
190 if True: chcontext(ref_ns+'ipc')
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')
197 if (not os.access('/proc/self',0)):
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))
207 print "Error: image does not have a sysctl binary"
209 # cgroups is not yet LXC-safe, so we need to use the coarse grained access control
210 # strategy of unmounting the filesystem
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
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
222 if (not umount('/sys/fs/cgroup')):
223 print "Error disabling cgroup access"
228 def getuid (slicename):
231 return pwd.getpwnam(slicename).pw_uid
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
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)
246 print "lxcsu could not spot %s in /etc/passwd - exiting"%slice_name
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
252 exec_args = [arch,'/bin/sh','--login']+args.command_to_run
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)
264 _,status = os.waitpid(fork_pid,0)
265 exit(os.WEXITSTATUS(status))
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,
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")
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__)
298 parser.add_argument ("slice_name")
299 parser.add_argument ("command_to_run",nargs="*")
301 args = parser.parse_args()
302 slice_name=args.slice_name
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
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
313 cmd = '/usr/bin/virsh dominfo %s'%slice_name
314 info = os.popen(cmd).read()
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()
325 print "Domain %s not found"%slice_name
327 is_kvm = ostype=='hvm'
330 kvmsu(slice_name, args)
332 lxcsu(slice_name, args)
334 if __name__ == '__main__':