8 from argparse import ArgumentParser
10 drop_capabilities='cap_sys_admin,cap_sys_boot,cap_sys_module'
12 # can set to True here, but also use the -d option
16 output = os.popen('readelf -h %s 2>&1'%f).readlines()
17 classlines = [x for x in output if ('Class' in x.split(':')[0])]
19 c = line.split(':')[1]
25 raise Exception('Could not determine architecture')
27 def get_cgroup_subdirs_for_pid(pid):
28 cgroup_info_file = '/proc/%s/cgroup'%pid
29 cgroup_lines = open(cgroup_info_file).read().splitlines()
32 for line in cgroup_lines:
34 _, cgroup_name, subdir = line.split(':')
35 subdirs[cgroup_name] = subdir
37 print "Error reading cgroup info: %s"%str(e)
43 def umount(fs_dir, opts=''):
44 output = os.popen('/bin/umount %s %s 2>&1'%(opts, fs_dir)).read()
45 return ('device is busy' not in output)
48 parser = ArgumentParser()
49 parser.add_argument("-n", "--nonet",
50 action="store_true", dest="netns", default=False,
51 help="Don't enter network namespace")
52 parser.add_argument("-m", "--nomnt",
53 action="store_true", dest="mntns", default=False,
54 help="Don't enter mount namespace")
55 parser.add_argument("-p", "--nopid",
56 action="store_true", dest="pidns", default=False,
57 help="Don't enter pid namespace")
58 parser.add_argument("-r", "--root",
59 action="store_true", dest="root", default=False,
60 help="Enter as root: be careful")
61 parser.add_argument("-i","--internal",
62 action="store_true", dest="internal", default=False,
63 help="does *not* prepend '-- -c' to arguments - or invoke lxcsu-internal")
64 parser.add_argument("-d","--debug",
65 action='store_true', dest='debug', default=False,
67 parser.add_argument("-s","--nosliceuid",
68 action='store_true', dest="nosliceuid", default=False,
69 help="do not change to slice uid inside of slice")
70 parser.add_argument("-o","--noslicehome",
71 action='store_true', dest="noslicehome", default=False,
72 help="do not change to slice home directory inside of slice")
74 if os.path.exists("/etc/lxcsu_default"):
75 defaults = parser.parse_args(file("/etc/lxcsu_default","r").read().split())
76 parser.set_defaults(**defaults.__dict__)
78 parser.add_argument ("slice_name")
79 parser.add_argument ("command_to_run",nargs="*")
81 args = parser.parse_args()
82 slice_name=args.slice_name
84 # unless we run the symlink 'lxcsu-internal', or we specify the -i option, prepend '--' '-c'
85 if sys.argv[0].find('internal')>=0: args.internal=True
87 if len(args.command_to_run)>0 and (args.command_to_run[0] == "/sbin/service"):
88 # A quick hack to support nodemanager interfaces.py when restarting
89 # networking in a slice.
90 args.nosliceuid = True
94 # no command given: enter interactive shell
95 if not args.command_to_run: args.command_to_run=['/bin/sh']
96 args.command_to_run = [ '-c' ] + [" ".join(args.command_to_run)]
98 # support for either setting debug at the top of this file, or on the command-line
104 cmd = '/usr/bin/virsh --connect lxc:/// domid %s'%slice_name
105 pidnum = int(os.popen(cmd).read().rstrip())
107 print "Domain %s not found"%slice_name
111 if debug: print "Found pidnum",pidnum
112 cmdline = open('/proc/%s/cmdline'%pidnum).read().rstrip('\n\x00')
113 arch = getarch('/proc/%s/exe'%pid)
116 print "Domain %s not started"%slice_name
122 # Set sysctls specific to slice
124 sysctl_dir = '/etc/planetlab/vsys-attributes/%s'%slice_name
125 if (os.access(sysctl_dir,0)):
126 entries = os.listdir(sysctl_dir)
128 prefix = 'vsys_sysctl.'
129 if (e.startswith(prefix)):
130 sysctl_file = '/'.join([sysctl_dir,e])
131 sysctl_name = e[len(prefix):]
132 sysctl_val = open(sysctl_file).read()
133 sysctls.append((sysctl_file, sysctl_name, sysctl_val))
135 subdirs = get_cgroup_subdirs_for_pid(pid)
136 sysfs_root = '/sys/fs/cgroup'
138 # If the slice is frozen, then we'll get an EBUSY when trying to write to the task
139 # list for the freezer cgroup. Since the user couldn't do anything anyway, it's best
140 # in this case to error out the shell. (an alternative would be to un-freeze it,
141 # add the task, and re-freeze it)
144 for subsystem in ['cpuset','memory','blkio','cpuacct','cpuacct,cpu','freezer']:
146 current_cgroup = subsystem
148 # There seems to be a bug in the cgroup schema: cpuacct,cpu can become cpu,cpuacct
149 # We need to handle both
152 subsystem_comps = subsystem.split(',')
153 subsystem_comps.reverse()
154 subsystem_alt = ','.join(subsystem_comps)
155 tasks_path_alt = [sysfs_root, subsystem_alt, subdirs[subsystem], 'tasks']
159 tasks_path = [sysfs_root,subsystem,subdirs[subsystem],'tasks']
160 tasks_path_str = '/'.join(tasks_path)
163 f = open(tasks_path_str, 'w')
165 tasks_path_alt_str = '/'.join(tasks_path_alt)
166 f = open(tasks_path_alt_str, 'w')
168 f.write(str(os.getpid()))
169 if (subsystem=='freezer'):
173 if (not subdirs.has_key(subsystem)):
177 print "Error assigning cgroup %s (%s) for slice %s"%(current_cgroup,pid, slice_name)
181 setns.chcontext('/proc/%s/ns/uts'%pid)
182 setns.chcontext('/proc/%s/ns/ipc'%pid)
185 setns.chcontext('/proc/%s/ns/pid'%pid)
188 setns.chcontext('/proc/%s/ns/net'%pid)
191 setns.chcontext('/proc/%s/ns/mnt'%pid)
194 if (not os.access('/proc/self',0)):
198 for (sysctl_file, sysctl_name, sysctl_val) in sysctls:
199 for fn in ["/sbin/sysctl", "/usr/sbin/sysctl", "/bin/sysctl", "/usr/bin/sysctl"]:
200 if os.path.exists(fn):
201 os.system('%s -w %s=%s >/dev/null 2>&1'%(fn, sysctl_name,sysctl_val))
204 print "Error: image does not have a sysctl binary"
206 # cgroups is not yet LXC-safe, so we need to use the coarse grained access control
207 # strategy of unmounting the filesystem
210 for subsystem in ['cpuset','cpu,cpuacct','memory','devices','freezer','net_cls','blkio','perf_event','systemd']:
211 fs_path = '/sys/fs/cgroup/%s'%subsystem
212 if (not umount(fs_path,'-l')):
214 # Leaving these comments for historical reference
215 #print "Error disabling cgroup access"
216 #exit(1) - Don't need this because failure here implies failure in the call to umount /sys/fs/cgroup
218 if (not umount('/sys/fs/cgroup')):
219 print "Error disabling cgroup access"
224 # capsh has a --user option starting with f14
225 # so if only for f12 we need to fake this one
227 # capsh.c does essentially the following when invoked with --user:
228 # pwd = getpwnam(user); ...
229 # ngroups = MAX_GROUPS;
230 # status = getgrouplist(user, pwd->pw_gid, groups, &ngroups); ...
231 # status = setgroups(ngroups, groups); ...
232 # status = setgid(pwd->pw_gid); ...
233 # status = setuid(pwd->pw_uid); ...
234 # however we cannot simulate that ourselves because if we did in this process then
235 # capsh could not be allowed to mess with caps any more
237 def getuid (slicename):
240 return pwd.getpwnam(slicename).pw_uid
245 cap_arg = '--drop='+drop_capabilities
248 if (args.nosliceuid):
249 # we still want to drop capabilities, but don't want to switch UIDs
250 exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--','--login',]+args.command_to_run
252 uid = getuid (slice_name)
254 print "lxcsu could not spot %s in /etc/passwd - exiting"%slice_name
256 exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--uid=%s'%uid,'--','--login',]+args.command_to_run
257 # once we can drop f12, it would be nicer to instead go for
258 # exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--user=%s'%slice_name,'--','--login',]+args.command_to_run
260 exec_args = [arch,'/usr/sbin/capsh','--','--login']+args.command_to_run
262 os.environ['SHELL'] = '/bin/sh'
263 if os.path.exists('/etc/planetlab/lib/bind_public.so'):
264 os.environ['LD_PRELOAD'] = '/etc/planetlab/lib/bind_public.so'
265 if not args.noslicehome:
266 os.environ['HOME'] = '/home/%s'%slice_name
267 os.chdir("/home/%s"%(slice_name))
268 if debug: print 'lxcsu:execv:','/usr/bin/setarch',exec_args
269 os.execv('/usr/bin/setarch',exec_args)
272 _,status = os.waitpid(pid,0)
273 exit(os.WEXITSTATUS(status))
275 if __name__ == '__main__':