Setting tag lxc-userspace-2.0-0
[lxc-userspace.git] / slicesu
1 #!/usr/bin/python3
2
3 # pylint: disable=c0111, w0703
4
5 import sys
6 import os
7 import re
8
9 from argparse import ArgumentParser
10
11 import setns
12
13 # can set to True here, but also use the -d option
14 DEBUG = False
15
16
17 def getarch(file):
18     output = os.popen('readelf -h %s 2>&1' % file).readlines()
19     classlines = [x for x in output if 'Class' in x.split(':')[0]]
20     line = classlines[0]
21     token = line.split(':')[1]
22     if 'ELF64' in token:
23         return 'x86_64'
24     if 'ELF32' in token:
25         return 'i686'
26     raise Exception('Could not determine architecture')
27
28
29 def get_cgroup_subdirs_for_pid(pid):
30     cgroup_info_file = '/proc/%s/cgroup' % pid
31     cgroup_lines = open(cgroup_info_file).read().splitlines()
32
33     subdirs = {}
34     for line in cgroup_lines:
35         try:
36             _, cgroup_name, subdir = line.split(':')
37             subdirs[cgroup_name] = subdir
38         except Exception as exc:
39             print("Error reading cgroup info: %s" % str(exc))
40
41     return subdirs
42
43
44 def umount(fs_dir, opts=''):
45     output = os.popen('/bin/umount %s %s 2>&1' % (opts, fs_dir)).read()
46     return 'device is busy' not in output
47
48
49 def kvmsu(slice_name, args):
50     mac_addresses = []
51
52     # Find MAC addresses of virt interfaces
53     process = os.popen("virsh domiflist %s" % slice_name)
54     for line in process:
55         match = re.search(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})', line, re.I)
56         if match:
57             mac_addresses.append(match.group())
58
59     # Find IP address of a reachable virt interface
60     # Here we're taking the one attached to br-nat, but this is specific to OpenCloud
61     ip_addr = None
62     try:
63         with open('/var/lib/dnsmasq/br-nat.hosts', 'r') as feed:
64             for line in feed:
65                 for mac in mac_addresses:
66                     match = re.search("^%s,[0-9.]+$" % mac, line, re.I)
67                     if match:
68                         ip_addr = match.group().split(',')[1]
69                         break
70     except Exception:
71         pass
72
73     if ip_addr:
74         # Need to login to a Ubuntu Cloud image as 'ubuntu' user
75         # Not sure how to make this more general
76         os.execv('/usr/bin/ssh',
77                  ['/usr/bin/ssh', '-o', 'StrictHostKeyChecking=no',
78                   'ubuntu@%s' % ip_addr]
79                  + args.command_to_run)
80     else:
81         # What should happen here?
82         print("Cannot map instance to IP address")
83         exit(1)
84
85
86 def lxcsu(slice_name, args):
87         # plain lxcsu
88     if not args.internal:
89                 # no command given: enter interactive shell
90         if not args.command_to_run:
91             args.command_to_run = ['/bin/sh']
92         args.command_to_run = ['-c'] + [" ".join(args.command_to_run)]
93
94     # support for either setting debug at the top of this file, or on the command-line
95     if args.debug:
96         global DEBUG
97         DEBUG = True
98
99     try:
100         cmd = '/usr/bin/virsh --connect lxc:/// domid %s' % slice_name
101         # convert to int as a minimal raincheck
102         driver_pid = int(os.popen(cmd).read().strip())
103         # locate the pid for the - expected - single child, that would be the init for that VM
104         #init_pid = int(open("/proc/%s/task/%s/children"%(driver_pid,driver_pid)).read().strip())
105         init_pid = int(os.popen('pgrep -P %s' %
106                                 driver_pid).readlines()[0].strip())
107         # Thierry: I am changing the code below to use child_pid instead of driver_pid
108         # for the namespace handling features, that I was able to check
109         # I've left the other ones as they were, i.e. using driver_pid, but I suspect
110         # they chould be changed as well
111
112     except Exception:
113         print("Domain %s not found" % slice_name)
114         exit(1)
115
116     if not driver_pid or not init_pid:
117         print("Domain %s not started" % slice_name)
118         exit(1)
119
120     if DEBUG:
121         print("Found driver_pid", driver_pid, 'and init_pid=', init_pid)
122     arch = getarch('/proc/%s/exe' % driver_pid)
123
124     # Set sysctls specific to slice
125     sysctls = []
126     sysctl_dir = '/etc/planetlab/vsys-attributes/%s' % slice_name
127     if os.access(sysctl_dir, 0):
128         entries = os.listdir(sysctl_dir)
129         for entry in entries:
130             prefix = 'vsys_sysctl.'
131             if entry.startswith(prefix):
132                 sysctl_file = '/'.join([sysctl_dir, entry])
133                 sysctl_name = entry[len(prefix):]
134                 with open(sysctl_file) as feed:
135                     sysctl_val = feed.read()
136                 sysctls.append((sysctl_file, sysctl_name, sysctl_val))
137
138     subdirs = get_cgroup_subdirs_for_pid(driver_pid)
139     sysfs_root = '/sys/fs/cgroup'
140
141     # If the slice is frozen, then we'll get an EBUSY when trying to write to the task
142     # list for the freezer cgroup. Since the user couldn't do anything anyway, it's best
143     # in this case to error out the shell. (an alternative would be to un-freeze it,
144     # add the task, and re-freeze it)
145     # Enter cgroups
146     current_cgroup = ''
147     for subsystem in ['cpuset', 'memory', 'blkio', 'cpuacct', 'cpuacct,cpu', 'freezer']:
148         try:
149             current_cgroup = subsystem
150
151             # There seems to be a bug in the cgroup schema: cpuacct,cpu can become cpu,cpuacct
152             # We need to handle both
153             try:
154                 subsystem_comps = subsystem.split(',')
155                 subsystem_comps.reverse()
156                 subsystem_alt = ','.join(subsystem_comps)
157                 tasks_path_alt = [sysfs_root, subsystem_alt,
158                                   subdirs[subsystem], 'tasks']
159             except Exception:
160                 pass
161
162             tasks_path = [sysfs_root, subsystem, subdirs[subsystem], 'tasks']
163             tasks_path_str = '/'.join(tasks_path)
164
165             try:
166                 feed = open(tasks_path_str, 'w')
167             except Exception:
168                 tasks_path_alt_str = '/'.join(tasks_path_alt)
169                 feed = open(tasks_path_alt_str, 'w')
170
171             feed.write(str(os.getpid()))
172             if subsystem == 'freezer':
173                 feed.close()
174
175         except Exception as exc:
176             if subsystem not in subdirs:
177                 pass
178             else:
179                 if DEBUG:
180                     print(exc)
181                 print("Error assigning cgroup %s (pid=%s) for slice %s" %
182                       (current_cgroup, driver_pid, slice_name))
183                 exit(1)
184
185     def chcontext(path):
186         retcod = setns.chcontext(path)
187         if retcod != 0:
188             print('WARNING - setns(%s)=>%s (ignored)' % (path, retcod))
189         return retcod
190
191     # Use init_pid and not driver_pid to locate reference namespaces
192     ref_ns = "/proc/%s/ns/" % init_pid
193
194     if True:
195         chcontext(ref_ns+'uts')
196     if True:
197         chcontext(ref_ns+'ipc')
198
199     if not args.no_pidns:
200         chcontext(ref_ns+'pid')
201     if not args.no_netns:
202         chcontext(ref_ns+'net')
203     if not args.no_mntns:
204         chcontext(ref_ns+'mnt')
205
206     if not os.access('/proc/self', 0):
207         setns.proc_mount()
208
209     for (sysctl_file, sysctl_name, sysctl_val) in sysctls:
210         for binary in ["/sbin/sysctl", "/usr/sbin/sysctl", "/bin/sysctl", "/usr/bin/sysctl"]:
211             if os.path.exists(binary):
212                 os.system('%s -w %s=%s  >/dev/null 2>&1' %
213                           (binary, sysctl_name, sysctl_val))
214                 break
215             else:
216                 print("Error: image does not have a sysctl binary")
217
218     # cgroups is not yet LXC-safe, so we need to use the coarse grained access control
219     # strategy of unmounting the filesystem
220
221     for subsystem in ['cpuset', 'cpu,cpuacct', 'memory', 'devices', 'freezer',
222                       'net_cls', 'blkio', 'perf_event', 'systemd']:
223         fs_path = '/sys/fs/cgroup/%s' % subsystem
224         if not umount(fs_path, '-l'):
225             print('WARNING - umount failed (ignored) with path=', fs_path)
226             # Leaving these comments for historical reference
227             # print "Error disabling cgroup access"
228             # exit(1) - Don't need this because failure here implies failure
229             # in the call to umount /sys/fs/cgroup
230
231     if not umount('/sys/fs/cgroup'):
232         print("Error disabling cgroup access")
233         exit(1)
234
235     fork_pid = os.fork()
236
237     def getuid(slicename):
238         import pwd
239         try:
240             return pwd.getpwnam(slicename).pw_uid
241         except Exception:
242             return
243
244     if fork_pid == 0:
245         if not args.root:
246             setns.drop_caps()
247             if args.nosliceuid:
248                 # we still want to drop capabilities, but don't want to switch UIDs
249                 exec_args = [arch, '/bin/sh', '--login', ] + args.command_to_run
250             else:
251                 # let's keep this check even though we don't use the uid
252                 # as a way of checking the existence of the slice account
253                 uid = getuid(slice_name)
254                 if not uid:
255                     print("lxcsu could not spot %s in /etc/passwd - exiting" %
256                           slice_name)
257                     exit(1)
258                 exec_args = [arch, '/usr/bin/sudo', '-u', slice_name,
259                              '/bin/sh', '--login', ] + args.command_to_run
260 # once we can drop f12, it would be nicer to instead go for
261 # exec_args = [arch,'/usr/sbin/capsh',cap_arg,'--user=%s'%slice_name,'--login',]+args.command_to_run
262         else:
263             exec_args = [arch, '/bin/sh', '--login'] + args.command_to_run
264
265         os.environ['SHELL'] = '/bin/sh'
266         if os.path.exists('/etc/planetlab/lib/bind_public.so'):
267             os.environ['LD_PRELOAD'] = '/etc/planetlab/lib/bind_public.so'
268         if not args.noslicehome:
269             os.environ['HOME'] = '/home/%s' % slice_name
270             os.chdir("/home/%s" % (slice_name))
271         if DEBUG:
272             print('lxcsu:execv:', '/usr/bin/setarch', exec_args)
273         os.execv('/usr/bin/setarch', exec_args)
274     else:
275         setns.proc_umount()
276         _, status = os.waitpid(fork_pid, 0)
277         exit(os.WEXITSTATUS(status))
278
279
280 def main():
281     parser = ArgumentParser()
282     parser.add_argument(
283         "-n", "--nonet",
284         action="store_true", dest="no_netns", default=False,
285         help="Don't enter network namespace")
286     parser.add_argument(
287         "-m", "--nomnt",
288         action="store_true", dest="no_mntns", default=False,
289         help="Don't enter mount namespace")
290     parser.add_argument(
291         "-p", "--nopid",
292         action="store_true", dest="no_pidns", default=False,
293         help="Don't enter pid namespace")
294     parser.add_argument(
295         "-r", "--root",
296         action="store_true", dest="root", default=False,
297         help="Enter as root: be careful")
298     parser.add_argument(
299         "-i", "--internal",
300         action="store_true", dest="internal", default=False,
301         help="does *not* prepend '-- -c' to arguments - or invoke lxcsu-internal")
302     parser.add_argument(
303         "-d", "--debug",
304         action='store_true', dest='debug', default=False,
305         help="debug option")
306     parser.add_argument(
307         "-s", "--nosliceuid",
308         action='store_true', dest="nosliceuid", default=False,
309         help="do not change to slice uid inside of slice")
310     parser.add_argument(
311         "-o", "--noslicehome",
312         action='store_true', dest="noslicehome", default=False,
313         help="do not change to slice home directory inside of slice")
314
315     if os.path.exists("/etc/lxcsu_default"):
316         with open("/etc/lxcsu_default", "r") as feed:
317             defaults = parser.parse_args(feed.read().split())
318         parser.set_defaults(**defaults.__dict__)
319
320     parser.add_argument("slice_name")
321     parser.add_argument("command_to_run", nargs="*")
322
323     args = parser.parse_args()
324     slice_name = args.slice_name
325
326     # unless we run the symlink 'lxcsu-internal', or we specify the -i option, prepend '--' '-c'
327     if sys.argv[0].find('internal') >= 0:
328         args.internal = True
329
330     if args.command_to_run and (args.command_to_run[0] == "/sbin/service"):
331         # A quick hack to support nodemanager interfaces.py when restarting
332         # networking in a slice.
333         args.nosliceuid = True
334
335     try:
336         cmd = '/usr/bin/virsh dominfo %s' % slice_name
337         info = os.popen(cmd).read()
338         useless_hash = {}
339
340         ostype = None
341         for line in info.split('\n'):
342             pair = line.split(':')
343             useless_hash[pair[0].strip()] = pair[1].strip()
344             if pair[0].strip() == 'OS Type':
345                 ostype = pair[1].strip()
346                 break
347     except Exception:
348         print("Domain %s not found" % slice_name)
349
350     is_kvm = ostype == 'hvm'
351
352     if is_kvm:
353         kvmsu(slice_name, args)
354     else:
355         lxcsu(slice_name, args)
356
357
358 if __name__ == '__main__':
359     main()