define a default for 'arch' as I find it sometimes undefined
[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 getarch(f):
13     output = os.popen('readelf -h %s 2>&1'%f).readlines()
14     classlines = [x for x in output if ('Class' in x.split(':')[0])]
15     line = classlines[0]
16     c = line.split(':')[1]
17     if ('ELF64' in c):
18         return 'x86_64'
19     elif ('ELF32' in c):
20         return 'i686'
21     else:
22         raise Exception('Could not determine architecture')
23
24 def umount(fs_dir):
25     output = os.popen('/bin/umount %s 2>&1'%fs_dir).read()
26     return ('device is busy' not in fs_dir)
27
28 parser = OptionParser()
29 parser.add_option("-n", "--nonet",
30                   action="store_true", dest="netns", default=False,
31                   help="Don't enter network namespace")
32 parser.add_option("-m", "--nomnt",
33                   action="store_true", dest="mntns", default=False,
34                   help="Don't enter mount namespace")
35 parser.add_option("-p", "--nopid",
36                   action="store_true", dest="pidns", default=False,
37                   help="Don't enter pid namespace")
38 parser.add_option("-r", "--root",
39                   action="store_true", dest="root", default=False,
40                   help="Enter as root: be careful")
41
42 (options, args) = parser.parse_args()
43
44 try:
45     slice_name = args[0]
46 except IndexError:
47     print "You must specify a vm name"
48     exit(1)
49
50 try:
51     cmd = 'grep %s /proc/*/cgroup | grep freezer'%slice_name
52     output = os.popen(cmd).readlines()
53 except:
54     print "Error finding slice %s"%slice_name
55     exit(1)
56
57 slice_spec = None
58
59 # xxx fixme xxx - provide a default as this is not always properly computed
60 arch = 'x86_64'
61
62 for e in output:
63     try:
64         l = e.rstrip()
65         path = l.split(':')[0]  
66         comp = l.rsplit(':')[-1]
67         slice_name_check = comp.rsplit('/')[-1]
68
69         if (slice_name_check == slice_name):
70             slice_path = path
71             pid = slice_path.split('/')[2]
72             cmdline = open('/proc/%s/cmdline'%pid).read().rstrip('\n\x00')
73             if (cmdline == '/sbin/init'):
74                 slice_spec = slice_path
75                 arch = getarch('/proc/%s/exe'%pid)
76                 break
77     except:
78         break
79
80 if (not slice_spec or not pid):
81     print "Not started: %s"%slice_name
82     exit(1)
83
84 # Enter cgroups
85 try:
86     for subsystem in ['cpuset','memory','blkio']:
87         open('/sys/fs/cgroup/%s/libvirt/lxc/%s/tasks'%(subsystem,slice_name),'w').write(str(os.getpid()))
88
89 except:
90     print "Error assigning resources: %s"%slice_name
91     exit(1)
92
93 try:
94     open('/sys/fs/cgroup/cpuacct/system/libvirtd.service/libvirt/lxc/%s/tasks'%slice_name,'w').write(str(os.getpid()))
95 except:
96     print "Error assigning cpuacct: %s" % slice_name
97     exit(1)
98
99 # If the slice is frozen, then we'll get an EBUSY when trying to write to the task
100 # list for the freezer cgroup. Since the user couldn't do anything anyway, it's best
101 # in this case to error out the shell. (an alternative would be to un-freeze it,
102 # add the task, and re-freeze it)
103 try:
104     f=open('/sys/fs/cgroup/freezer/libvirt/lxc/%s/tasks'%(slice_name),'w')
105     f.write(str(os.getpid()))
106     # note: we need to call f.close() explicitly, or we'll get an exception in
107     # the object destructor, which will not be caught
108     f.close()
109 except:
110     print "Error adding task to freezer cgroup. Slice is probably frozen: %s" % slice_name
111     exit(1)
112
113 setns.chcontext('/proc/%s/ns/uts'%pid)
114 setns.chcontext('/proc/%s/ns/ipc'%pid)
115
116 if (not options.netns):
117   setns.chcontext('/proc/%s/ns/net'%pid)
118
119 if (not options.mntns):
120   open('/proc/lxcsu','w').write(pid)
121
122 if (not options.pidns):
123   open('/proc/pidsu','w').write(pid)
124
125 # cgroups is not yet LXC-safe, so we need to use the course grained access control
126 # strategy of unmounting the filesystem
127
128 umount_result = True
129 for subsystem in ['cpuset','cpu,cpuacct','memory','devices','freezer','net_cls','blkio','perf_event']:
130     fs_path = '/sys/fs/cgroup/%s'%subsystem
131     if (not umount(fs_path)):
132         print "Error disabling cgroup access"
133         exit(1)
134
135 if (not umount('/sys/fs/cgroup')):
136     print "Error disabling cgroup access"
137     exit(1)
138
139 pid = os.fork()
140
141 if (pid == 0):
142     cap_arg = '--drop='+drop_capabilities
143
144     if (not options.root):
145       exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--','--login']+args[1:]
146     else:
147       exec_args = [arch,'/usr/sbin/capsh','--','--login']+args[1:]
148
149     os.environ['SHELL'] = '/bin/sh'
150     os.execv('/usr/bin/setarch',exec_args)
151 else:
152     _,status = os.waitpid(pid,0)
153     exit(os.WEXITSTATUS(status))