7 from argparse import ArgumentParser
9 drop_capabilities='cap_sys_admin,cap_sys_boot,cap_sys_module'
11 # can set to True here, but also use the -d option
14 #################### should go into a separate libvirtsystemd.py
15 # but we want to keep packaging simple for now
17 # reproducing libvirt's systemd-oriented escaping mechanism
18 # http://code.metager.de/source/xref/lib/virt/src/util/virsystemd.c
19 # (see original code at the end of this file)
21 def virSystemdEscapeName (name):
24 # replace hex's output '0x..' into '\x..'
25 return s+hex(ord(c)).replace('0','\\',1)
28 "abcdefghijklmnopqrstuvwxyz" + \
29 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + \
34 elif c in '-\\' or c not in VALID_CHARS:
35 result=ESCAPE(c,result)
40 #35static void virSystemdEscapeName(virBufferPtr buf,
43 #38 static const char hextable[16] = "0123456789abcdef";
45 #40#define ESCAPE(c) \
47 #42 virBufferAddChar(buf, '\\'); \
48 #43 virBufferAddChar(buf, 'x'); \
49 #44 virBufferAddChar(buf, hextable[(c >> 4) & 15]); \
50 #45 virBufferAddChar(buf, hextable[c & 15]); \
53 #48#define VALID_CHARS \
55 #50 "abcdefghijklmnopqrstuvwxyz" \
56 #51 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
59 #54 if (*name == '.') {
66 #61 virBufferAddChar(buf, '-');
67 #62 else if (*name == '-' ||
69 #64 !strchr(VALID_CHARS, *name))
72 #67 virBufferAddChar(buf, *name);
80 def virSystemdMakeScopeName (name, drivername, partition):
82 result += virSystemdEscapeName (partition)
84 result += virSystemdEscapeName (drivername)
86 result += virSystemdEscapeName (name)
90 #76char *virSystemdMakeScopeName(const char *name,
91 #77 const char *drivername,
92 #78 const char *partition)
94 #80 virBuffer buf = VIR_BUFFER_INITIALIZER;
96 #82 if (*partition == '/')
99 #85 virSystemdEscapeName(&buf, partition);
100 #86 virBufferAddChar(&buf, '-');
101 #87 virSystemdEscapeName(&buf, drivername);
102 #88 virBufferAddLit(&buf, "\\x2d");
103 #89 virSystemdEscapeName(&buf, name);
104 #90 virBufferAddLit(&buf, ".scope");
106 #92 if (virBufferError(&buf)) {
107 #93 virReportOOMError();
111 #97 return virBufferContentAndReset(&buf);
114 ### our own additions
116 def find_first_dir (candidates):
117 for candidate in candidates:
118 if os.path.isdir(candidate): return candidate
119 raise Exception,"Cannot find valid dir among %s"%'\n'.join(candidates)
121 def find_sysfs_scope (subsystem, slice_name):
124 if subsystem=='cpuacct':
125 subsystem2='cpu,cpuacct'
127 # for f16 and our locally brewed libvirt 1.0.4
128 "/sys/fs/cgroup/%s/libvirt/lxc/%s"%(subsystem1, slice_name),
129 # f20 and libvirt 1.1.3
130 "/sys/fs/cgroup/%s/machine.slice/%s"%(subsystem2,
131 virSystemdMakeScopeName(slice_name,'lxc','machine')),
133 return find_first_dir (candidates)
135 #################### end of libvirtsystemd.py
138 output = os.popen('readelf -h %s 2>&1'%f).readlines()
139 classlines = [x for x in output if ('Class' in x.split(':')[0])]
141 c = line.split(':')[1]
147 raise Exception('Could not determine architecture')
149 def umount(fs_dir, opts=''):
150 output = os.popen('/bin/umount %s %s 2>&1'%(opts, fs_dir)).read()
151 return ('device is busy' not in output)
154 parser = ArgumentParser()
155 parser.add_argument("-n", "--nonet",
156 action="store_true", dest="netns", default=False,
157 help="Don't enter network namespace")
158 parser.add_argument("-m", "--nomnt",
159 action="store_true", dest="mntns", default=False,
160 help="Don't enter mount namespace")
161 parser.add_argument("-p", "--nopid",
162 action="store_true", dest="pidns", default=False,
163 help="Don't enter pid namespace")
164 parser.add_argument("-r", "--root",
165 action="store_true", dest="root", default=False,
166 help="Enter as root: be careful")
167 parser.add_argument("-i","--internal",
168 action="store_true", dest="internal", default=False,
169 help="does *not* prepend '-- -c' to arguments - or invoke lxcsu-internal")
170 parser.add_argument("-d","--debug",
171 action='store_true', dest='debug', default=False,
173 parser.add_argument("-s","--nosliceuid",
174 action='store_true', dest="nosliceuid", default=False,
175 help="do not change to slice uid inside of slice")
176 parser.add_argument("-o","--noslicehome",
177 action='store_true', dest="noslicehome", default=False,
178 help="do not change to slice home directory inside of slice")
180 if os.path.exists("/etc/lxcsu_default"):
181 defaults = parser.parse_args(file("/etc/lxcsu_default","r").read().split())
182 parser.set_defaults(**defaults.__dict__)
184 parser.add_argument ("slice_name")
185 parser.add_argument ("command_to_run",nargs="*")
187 args = parser.parse_args()
188 slice_name=args.slice_name
190 # unless we run the symlink 'lxcsu-internal', or we specify the -i option, prepend '--' '-c'
191 if sys.argv[0].find('internal')>=0: args.internal=True
193 if len(args.command_to_run)>0 and (args.command_to_run[0] == "/sbin/service"):
194 # A quick hack to support nodemanager interfaces.py when restarting
195 # networking in a slice.
196 args.nosliceuid = True
199 if not args.internal:
200 # no command given: enter interactive shell
201 if not args.command_to_run: args.command_to_run=['/bin/sh']
202 args.command_to_run = [ '-c' ] + [" ".join(args.command_to_run)]
204 # support for either setting debug at the top of this file, or on the command-line
210 cmd = '/usr/bin/virsh --connect lxc:/// domid %s'%slice_name
211 pidnum = int(os.popen(cmd).read().rstrip())
213 print "Error finding slice %s"%slice_name
217 if debug: print "Found pidnum",pidnum
218 cmdline = open('/proc/%s/cmdline'%pidnum).read().rstrip('\n\x00')
219 arch = getarch('/proc/%s/exe'%pid)
222 print "Not started: %s"%slice_name
228 # Set sysctls specific to slice
230 sysctl_dir = '/etc/planetlab/vsys-attributes/%s'%slice_name
231 if (os.access(sysctl_dir,0)):
232 entries = os.listdir(sysctl_dir)
234 prefix = 'vsys_sysctl.'
235 if (e.startswith(prefix)):
236 sysctl_file = '/'.join([sysctl_dir,e])
237 sysctl_name = e[len(prefix):]
238 sysctl_val = open(sysctl_file).read()
239 sysctls.append((sysctl_file, sysctl_name, sysctl_val))
243 for subsystem in ['cpuset','memory','blkio']:
244 open( find_sysfs_scope (subsystem, slice_name)+"/tasks", 'w').write(str(os.getpid()))
248 print "Error assigning resources: %s"%slice_name
252 open ( find_sysfs_scope ('cpuacct', slice_name)+"/tasks", 'w').write(str(os.getpid()))
255 print "Error assigning cpuacct: %s" % slice_name
258 # If the slice is frozen, then we'll get an EBUSY when trying to write to the task
259 # list for the freezer cgroup. Since the user couldn't do anything anyway, it's best
260 # in this case to error out the shell. (an alternative would be to un-freeze it,
261 # add the task, and re-freeze it)
263 f=open( find_sysfs_scope ('freezer', slice_name)+"/tasks", 'w')
264 f.write(str(os.getpid()))
265 # note: we need to call f.close() explicitly, or we'll get an exception in
266 # the object destructor, which will not be caught
270 print "Error adding task to freezer cgroup. Slice is probably frozen: %s" % slice_name
273 setns.chcontext('/proc/%s/ns/uts'%pid)
274 setns.chcontext('/proc/%s/ns/ipc'%pid)
277 setns.chcontext('/proc/%s/ns/pid'%pid)
280 setns.chcontext('/proc/%s/ns/net'%pid)
283 setns.chcontext('/proc/%s/ns/mnt'%pid)
286 if (not os.access('/proc/self',0)):
290 for (sysctl_file, sysctl_name, sysctl_val) in sysctls:
291 for fn in ["/sbin/sysctl", "/usr/sbin/sysctl", "/bin/sysctl", "/usr/bin/sysctl"]:
292 if os.path.exists(fn):
293 os.system('%s -w %s=%s >/dev/null 2>&1'%(fn, sysctl_name,sysctl_val))
296 print "Error: image does not have a sysctl binary"
298 # cgroups is not yet LXC-safe, so we need to use the coarse grained access control
299 # strategy of unmounting the filesystem
302 for subsystem in ['cpuset','cpu,cpuacct','memory','devices','freezer','net_cls','blkio','perf_event','systemd']:
303 fs_path = '/sys/fs/cgroup/%s'%subsystem
304 if (not umount(fs_path,'-l')):
306 # Leaving these comments for historical reference
307 #print "Error disabling cgroup access"
308 #exit(1) - Don't need this because failure here implies failure in the call to umount /sys/fs/cgroup
310 if (not umount('/sys/fs/cgroup')):
311 print "Error disabling cgroup access"
316 # capsh has a --user option starting with f14
317 # so if only for f12 we need to fake this one
319 # capsh.c does essentially the following when invoked with --user:
320 # pwd = getpwnam(user); ...
321 # ngroups = MAX_GROUPS;
322 # status = getgrouplist(user, pwd->pw_gid, groups, &ngroups); ...
323 # status = setgroups(ngroups, groups); ...
324 # status = setgid(pwd->pw_gid); ...
325 # status = setuid(pwd->pw_uid); ...
326 # however we cannot simulate that ourselves because if we did in this process then
327 # capsh could not be allowed to mess with caps any more
329 def getuid (slicename):
332 return pwd.getpwnam(slicename).pw_uid
337 cap_arg = '--drop='+drop_capabilities
340 if (args.nosliceuid):
341 # we still want to drop capabilities, but don't want to switch UIDs
342 exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--','--login',]+args.command_to_run
344 uid = getuid (slice_name)
346 print "lxcsu could not spot %s in /etc/passwd - exiting"%slice_name
348 exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--uid=%s'%uid,'--','--login',]+args.command_to_run
349 # once we can drop f12, it would be nicer to instead go for
350 # exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--user=%s'%slice_name,'--','--login',]+args.command_to_run
352 exec_args = [arch,'/usr/sbin/capsh','--','--login']+args.command_to_run
354 os.environ['SHELL'] = '/bin/sh'
355 if os.path.exists('/etc/planetlab/lib/bind_public.so'):
356 os.environ['LD_PRELOAD'] = '/etc/planetlab/lib/bind_public.so'
357 if not args.noslicehome:
358 os.environ['HOME'] = '/home/%s'%slice_name
359 os.chdir("/home/%s"%(slice_name))
360 if debug: print 'lxcsu:execv:','/usr/bin/setarch',exec_args
361 os.execv('/usr/bin/setarch',exec_args)
364 _,status = os.waitpid(pid,0)
365 exit(os.WEXITSTATUS(status))
367 if __name__ == '__main__':