#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Simafri measured requirements bench: the sampler.
#
# Runs on the Proxmox host, never inside the measured container, so that sampling adds nothing
# to what is measured. Once per second it reads, from cgroup v2:
#   - every Docker container of the measured LXC container (one cgroup scope per container),
#   - the measured LXC container as a whole, operating system included,
#   - the load generator container (to prove it was never the bottleneck),
# and from the host: CPU time, load, pressure stall information and available memory, plus the
# ZFS dataset counters of the measured container's disk (cgroup I/O accounting does not see ZFS),
# and the CPU of neighbour containers that could disturb a run (the public mirrors, for instance).
#
# Every line of the output is one JSON sample. Counters are written raw (cumulative); the
# analysis derives rates from consecutive samples. SIGUSR1 resets the memory peak of every
# cgroup (memory.peak, per file descriptor, Linux 6.12 and later) at the next sample, so that a
# phase of the run gets its own peak; SIGTERM ends the run.
#
# Usage: collecteur.py --ct 207 --gen 208 --sortie samples.jsonl

import argparse
import glob
import json
import os
import signal
import subprocess
import sys
import time

CG = '/sys/fs/cgroup'
MEMORY_STAT_KEYS = ('anon', 'file', 'kernel', 'sock', 'shmem', 'file_mapped', 'file_dirty',
                    'active_anon', 'inactive_anon', 'active_file', 'inactive_file', 'slab')


def read_text(path):
    try:
        with open(path) as f:
            return f.read()
    except OSError:
        return None


def read_int(path):
    text = read_text(path)
    if text is None:
        return None
    text = text.strip()
    return None if text == 'max' else int(text)


def read_keys(path, keys=None):
    text = read_text(path)
    if text is None:
        return None
    values = {}
    for line in text.splitlines():
        parts = line.split()
        if len(parts) == 2 and (keys is None or parts[0] in keys):
            values[parts[0]] = int(parts[1])
    return values


def read_io(path):
    """Sums io.stat over every device: rbytes, wbytes, rios, wios."""
    text = read_text(path)
    if text is None:
        return None
    total = {'rbytes': 0, 'wbytes': 0, 'rios': 0, 'wios': 0}
    for line in text.splitlines():
        for field in line.split()[1:]:
            key, _, value = field.partition('=')
            if key in total:
                total[key] += int(value)
    return total


class Peak:
    """memory.peak read through one file descriptor, so that a write resets it for that descriptor."""

    def __init__(self, path):
        self.fd = None
        try:
            self.fd = os.open(path, os.O_RDWR)
        except OSError:
            try:
                self.fd = os.open(path, os.O_RDONLY)
            except OSError:
                self.fd = None

    def reset(self):
        if self.fd is None:
            return False
        try:
            os.pwrite(self.fd, b'reset\n', 0)
            return True
        except OSError:
            return False

    def read(self):
        if self.fd is None:
            return None
        try:
            return int(os.pread(self.fd, 64, 0).strip())
        except (OSError, ValueError):
            return None

    def close(self):
        if self.fd is not None:
            os.close(self.fd)


class Cgroup:
    def __init__(self, path):
        self.path = path
        self.peak = Peak(os.path.join(path, 'memory.peak'))

    def sample(self):
        p = self.path
        cpu = read_keys(os.path.join(p, 'cpu.stat'),
                        ('usage_usec', 'user_usec', 'system_usec', 'nr_throttled', 'throttled_usec'))
        if cpu is None:
            return None
        return {
            'mem': read_int(os.path.join(p, 'memory.current')),
            'peak': self.peak.read(),
            'swap': read_int(os.path.join(p, 'memory.swap.current')),
            'max': read_int(os.path.join(p, 'memory.max')),
            'stat': read_keys(os.path.join(p, 'memory.stat'), MEMORY_STAT_KEYS),
            'events': read_keys(os.path.join(p, 'memory.events')),
            'cpu': cpu,
            'io': read_io(os.path.join(p, 'io.stat')),
            'pids': read_int(os.path.join(p, 'pids.current')),
        }


def zfs_objset(dataset):
    """Finds the kstat file of a ZFS dataset (logical reads and writes of the filesystem)."""
    pool = dataset.split('/')[0]
    for path in glob.glob(f'/proc/spl/kstat/zfs/{pool}/objset-*'):
        text = read_text(path) or ''
        for line in text.splitlines():
            parts = line.split()
            if len(parts) == 3 and parts[0] == 'dataset_name' and parts[2] == dataset:
                return path
    return None


def read_objset(path):
    text = read_text(path) if path else None
    if text is None:
        return None
    values = {}
    for line in text.splitlines():
        parts = line.split()
        if len(parts) == 3 and parts[0] in ('writes', 'nwritten', 'reads', 'nread'):
            values[parts[0]] = int(parts[2])
    return values


def read_host():
    stat = read_text('/proc/stat').splitlines()[0].split()[1:]
    cpu = dict(zip(('user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq', 'steal'),
                   (int(v) for v in stat[:8])))
    pressure = {}
    for kind in ('cpu', 'io', 'memory'):
        text = read_text(f'/proc/pressure/{kind}') or ''
        for line in text.splitlines():
            parts = line.split()
            fields = dict(p.split('=') for p in parts[1:])
            pressure[f'{kind}_{parts[0]}'] = {'avg10': float(fields['avg10']), 'total': int(fields['total'])}
    mem = {}
    for line in (read_text('/proc/meminfo') or '').splitlines():
        key, _, rest = line.partition(':')
        if key in ('MemTotal', 'MemAvailable', 'SwapTotal', 'SwapFree'):
            mem[key] = int(rest.split()[0]) * 1024
    return {
        'cpu': cpu,
        'load': [float(v) for v in read_text('/proc/loadavg').split()[:3]],
        'psi': pressure,
        'mem': mem,
    }


def container_name(rootfs, container_id):
    text = read_text(os.path.join(rootfs, 'var/lib/docker/containers', container_id, 'config.v2.json'))
    if text is None:
        return None
    try:
        return json.loads(text).get('Name', '').lstrip('/') or None
    except ValueError:
        return None


def main():
    parser = argparse.ArgumentParser(description='cgroup v2 sampler of the measured requirements bench')
    parser.add_argument('--ct', required=True, help='VMID of the measured LXC container')
    parser.add_argument('--gen', required=True, help='VMID of the load generator container')
    parser.add_argument('--sortie', required=True, help='output file, one JSON sample per line')
    parser.add_argument('--voisins', default='', help='VMIDs of neighbour containers to watch (CPU, memory, comma-separated)')
    parser.add_argument('--intervalle', type=float, default=1.0)
    args = parser.parse_args()

    ct_path = f'{CG}/lxc/{args.ct}'
    gen_path = f'{CG}/lxc/{args.gen}'
    dataset = subprocess.run(['pct', 'config', args.ct], capture_output=True, text=True).stdout
    dataset = next((l.split(':', 2)[2].split(',')[0] for l in dataset.splitlines() if l.startswith('rootfs:')), '')
    dataset = 'rpool/data/' + dataset if dataset and '/' not in dataset else dataset
    rootfs = subprocess.run(['zfs', 'get', '-H', '-o', 'value', 'mountpoint', dataset],
                            capture_output=True, text=True).stdout.strip()
    objset = zfs_objset(dataset)
    voisins = [v for v in args.voisins.split(',') if v]

    state = {'reset': False, 'stop': False}
    signal.signal(signal.SIGUSR1, lambda *_: state.update(reset=True))
    signal.signal(signal.SIGTERM, lambda *_: state.update(stop=True))
    signal.signal(signal.SIGINT, lambda *_: state.update(stop=True))

    groups = {}
    names = {}
    out = open(args.sortie, 'a', buffering=1)
    out.write(json.dumps({'meta': {'ct': args.ct, 'gen': args.gen, 'dataset': dataset, 'rootfs': rootfs,
                                   'objset': objset, 'interval': args.intervalle}}) + '\n')

    def group(path):
        if path not in groups:
            groups[path] = Cgroup(path)
        return groups[path]

    next_tick = time.monotonic()
    while not state['stop']:
        reset = state['reset']
        state['reset'] = False
        scopes = glob.glob(f'{ct_path}/ns/system.slice/docker-*.scope')
        sample = {'t': time.time()}
        containers = {}
        for scope in scopes:
            cid = os.path.basename(scope)[len('docker-'):-len('.scope')]
            if cid not in names or names[cid] is None:
                names[cid] = container_name(rootfs, cid)
            g = group(scope)
            if reset:
                g.peak.reset()
            values = g.sample()
            if values is not None:
                values['id'] = cid[:12]
                containers[names[cid] or cid[:12]] = values
        for path in list(groups):
            if path not in scopes and path not in (ct_path, gen_path):
                groups.pop(path).peak.close()
        ct = group(ct_path)
        gen = group(gen_path)
        if reset:
            ok = ct.peak.reset()
            gen.peak.reset()
            sample['peak_reset'] = ok
        sample['containers'] = containers
        sample['ct'] = ct.sample()
        sample['gen'] = gen.sample()
        sample['voisins'] = {}
        for vmid in voisins:
            cpu = read_keys(f'{CG}/lxc/{vmid}/cpu.stat', ('usage_usec',))
            if cpu is not None:
                sample['voisins'][vmid] = {'cpu': cpu.get('usage_usec'), 'mem': read_int(f'{CG}/lxc/{vmid}/memory.current')}
        sample['disk'] = read_objset(objset)
        sample['host'] = read_host()
        out.write(json.dumps(sample, separators=(',', ':')) + '\n')

        next_tick += args.intervalle
        delay = next_tick - time.monotonic()
        if delay > 0:
            time.sleep(delay)
        else:
            next_tick = time.monotonic()
    out.close()


if __name__ == '__main__':
    sys.exit(main())
