c0b2312a3758913201cb92e3a320a6d96cf4932a
[vsys-scripts.git] / root-context / exec / run_with_devices
1 #!/usr/bin/python -u
2 # All vsys scripts should use STDOUT in unbuferred mode, or else sometimes your output will get bufferred and you will not see it till the buffer gets flushed.  
3
4 import sys
5 import os
6
7 vsys_config_dir = "/etc/planetlab/vsys-attributes"
8
9 slicename=sys.argv[1]
10 sliceid = pwd.getpwnam(slicename).pw_uid
11
12 arglines = map(string.strip, sys.stdin.readlines())
13 command_name = arglines[0]
14 device_names = arglines[1:]
15
16 print "Validating interface names... ",
17 # Validate interface names
18
19 for vif in device_names:
20     if len(vif)>16:
21         print "Interface name %s invalid"%(vif)
22         sys.exit(1)
23     if re.match(r'(tun|tap)%d-\d+' % sliceid, vif ) is None:
24         print "Interface name %s does not match slice id %d."%(vif, sliceid)
25         sys.exit(1)
26     print "[OK]"
27
28 # The interfaces have been validated. We don't need to validate the executable
29 # path for escape hatches because we are going to use execve.
30
31 pid = os.fork()
32 if (pid):
33     # Close open fds before execve
34     print "Closing file descriptors."
35     for fd in xrange(3, 1023):
36         try:
37             os.close(fd)
38         except OSError:
39             pass
40     # Execute command
41     vserver_command = "/usr/sbin/vserver"
42     args = [slicename]
43     args += ['exec']
44     args += [command_name]
45
46     os.system('touch /etc/vservers/%s/spaces/net'%slicename)
47
48     try:    
49         os.execve(vserver_command, args)
50     except:
51         pass
52
53     os.system('rm /etc/vservers/%s/spaces/net'%slicename)
54 else:
55     for vif in device_names:
56         os.system('/sbin/ip link set %s netns %d'%(vif, pid))
57