#!/usr/bin/python3
# SPDX-License-Identifier: MIT
# Stileex measured requirements bench (method 1.2): the OCI runtime of Docker on the measured server,
# runc with one addition. The measured server's own views of its processor and memory (/proc/cpuinfo,
# /proc/stat, /proc/meminfo, /sys/devices/system/cpu...) are those of its size; a container that
# mounts a fresh /proc would read the processor and memory of the whole Proxmox host instead (16
# threads, 128 GiB), and size its worker pools and heaps on them. This wrapper binds the server's
# views into every container Docker starts, so that the software sees the vCPU and the memory of the
# server, as on a virtual server. Then it runs runc, unchanged.
#
# Installed by passage.sh in the measured server at each run, in place of /usr/bin/runc (the real one
# becomes /usr/bin/runc.real), so that every container goes through it, those Docker starts and the
# steps of an image build alike. runc mounts only files under /proc: the directories lxcfs serves
# there (/proc/pressure) are left out.
import json
import os
import sys

args = sys.argv[1:]
if 'create' in args or 'run' in args:
    bundle = '.'
    for flag in ('--bundle', '-b'):
        if flag in args and args.index(flag) + 1 < len(args):
            bundle = args[args.index(flag) + 1]
    path = os.path.join(bundle, 'config.json')
    if os.path.exists(path):
        vues = []
        with open('/proc/self/mountinfo') as f:
            for line in f:
                parts = line.split()
                sep = parts.index('-')
                point = parts[4]
                if parts[sep + 1] == 'fuse.lxcfs' and (os.path.isfile(point) or not point.startswith('/proc/')):
                    vues.append(point)
        with open(path) as f:
            config = json.load(f)
        mounts = config.setdefault('mounts', [])
        deja = {m.get('destination') for m in mounts}
        for vue in vues:
            if vue not in deja:
                mounts.append({'destination': vue, 'type': 'bind', 'source': vue, 'options': ['rbind', 'nosuid', 'nodev']})
        with open(path, 'w') as f:
            json.dump(config, f)
os.execv('/usr/bin/runc.real', ['runc'] + args)
