Tweaked return code handling to use the usual Python method
[lxc-userspace.git] / lxcsu
1 #!/usr/bin/python
2
3
4 import setns
5 import os
6 import sys
7
8 #from optparse import OptionParser
9
10 drop_capabilities='cap_sys_admin,cap_sys_boot,cap_sys_module'
11
12 def umount(fs_dir):
13     output = os.popen('/bin/umount %s 2>&1'%fs_dir).read()
14     return ('device is busy' not in fs_dir)
15
16
17 """
18 parser = OptionParser()
19 parser.add_option("-n", "--net",
20                   action="store_true", dest="netns", default=False,
21                   help="Enter network namespace")
22 parser.add_option("-m", "--mnt",
23                   action="store_true", dest="mntns", default=False,
24                   help="Enter mount namespace")
25 parser.add_option("-p", "--pid",
26                   action="store_true", dest="pidns", default=False,
27                   help="Enter pid namespace")
28
29 (options, args) = parser.parse_args()
30 """
31 args = sys.argv[1:]
32
33 try:
34         slice_name = args[0]
35 except IndexError:
36         print "You must specify a vm name"
37         exit(1)
38
39 try:
40         cmd = 'grep %s /proc/*/cgroup | grep freezer'%slice_name
41         output = os.popen(cmd).readlines()
42 except:
43         print "Error finding slice %s"%slice_name
44         exit(1)
45
46 slice_spec = None
47 for e in output:
48         try:
49                 l = e.rstrip()
50                 path = l.split(':')[0]  
51                 comp = l.rsplit(':')[-1]
52                 slice_name_check = comp.rsplit('/')[-1]
53
54                 if (slice_name_check == slice_name):
55                         slice_path = path
56                         pid = slice_path.split('/')[2]
57                         cmdline = open('/proc/%s/cmdline'%pid).read().rstrip('\n\x00')
58                         if (cmdline == '/sbin/init'):
59                                 slice_spec = slice_path
60                                 break
61         except:
62                 break
63
64 if (not slice_spec or not pid):
65     print "Not started: %s"%slice_name
66     exit(1)
67
68 # Enter cgroups
69 try:
70     for subsystem in ['cpuset','memory','blkio']:
71         open('/sys/fs/cgroup/%s/libvirt/lxc/%s/tasks'%(subsystem,slice_name),'w').write(str(os.getpid()))
72
73 except:
74     print "Error assigning resources: %s"%slice_name
75     exit(1)
76
77 try:
78     open('/sys/fs/cgroup/cpuacct/system/libvirtd.service/libvirt/lxc/%s/tasks'%slice_name,'w').write(str(os.getpid()))
79 except:
80     print "Error assigning cpuacct: %s" % slice_name
81     exit(1)
82
83 # If the slice is frozen, then we'll get an EBUSY when trying to write to the task
84 # list for the freezer cgroup. Since the user couldn't do anything anyway, it's best
85 # in this case to error out the shell. (an alternative would be to un-freeze it,
86 # add the task, and re-freeze it)
87 try:
88     f=open('/sys/fs/cgroup/freezer/libvirt/lxc/%s/tasks'%(slice_name),'w')
89     f.write(str(os.getpid()))
90     # note: we need to call f.close() explicitly, or we'll get an exception in
91     # the object destructor, which will not be caught
92     f.close()
93 except:
94     print "Error adding task to freezer cgroup. Slice is probably frozen: %s" % slice_name
95     exit(1)
96
97 r1 = setns.chcontext('/proc/%s/ns/uts'%pid)
98 r2 = setns.chcontext('/proc/%s/ns/ipc'%pid)
99 r3 = setns.chcontext('/proc/%s/ns/net'%pid)
100
101 open('/proc/lxcsu','w').write(pid)
102 open('/proc/pidsu','w').write(pid)
103
104 # cgroups is not yet LXC-safe, so we need to use the course grained access control
105 # strategy of unmounting the filesystem
106
107 umount_result = True
108 for subsystem in ['cpuset','cpu,cpuacct','memory','devices','freezer','net_cls','blkio','perf_event']:
109     fs_path = '/sys/fs/cgroup/%s'%subsystem
110     if (not umount(fs_path)):
111         print "Error disabling cgroup access"
112         exit(1)
113
114 if (not umount('/sys/fs/cgroup')):
115     print "Error disabling cgroup access"
116     exit(1)
117
118 pid = os.fork()
119
120 if (pid == 0):
121     cap_arg = '--drop='+drop_capabilities
122     exec_args = ['/usr/sbin/capsh',cap_arg,'--','--login']+args[1:]
123
124     os.environ['SHELL'] = '/bin/sh'
125     os.execv('/usr/sbin/capsh',exec_args)
126 else:
127     _,status = os.waitpid(pid,0)
128     exit(os.WEXITSTATUS(status))