#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Simafri measured requirements bench: the analysis of a campaign.
#
#   analyse.py <campaign_dir> [--paliers tiers.json] [--sortie results.json]
#
# Reads every run directory of the campaign (evenements.txt, meta.env, echantillons.jsonl, and for
# the profiles under load k6.csv.gz), and computes, over the measurement window of each run:
#   - working set memory (memory.current minus inactive_file), per container, for the whole stack
#     (sum of the containers) and for the whole container seen from the host: median, p95, peak;
#   - CPU in vCPU (usage_usec per second of wall time): mean and p95;
#   - disk reads and writes of the container's filesystem (ZFS dataset counters), per second;
#   - the criteria of a held profile: errors, p95 of the scenario, OOM kills, swap, restarts;
#   - the validity of the run: host CPU, neighbour containers, load generator CPU.
# Then, per profile, the median and the range (min to max) over the independent runs, and the
# candidate tier: the smallest tier where (stack working set peak + system base) x 1.25 fits in
# its memory and where the container's CPU p95 stays under 70 % of its vCPU.
#
# Standard library only.

import argparse
import csv
import gzip
import json
import math
import os
import re
import shlex
import statistics
import sys

MARGE_MEMOIRE = 1.25
PART_CPU = 0.70
SEUIL_ECART = 0.10           # a spread above 10 % of the median is investigated and replayed,
PLANCHERS = {'ws': 2 * 1024 ** 2, 'cpu': 0.01}   # beyond a floor: 2 MiB of memory, 0.01 vCPU
SEUIL_ERREURS = 0.001        # under 0.1 % of errors
SEUIL_P95_MS = 1000          # p95 of the scenario under 1 s
FIN_LIVRAISON_S = 5          # messages published in the last 5 s are not expected yet
# Validity of a run (a run outside them is played again): the host's CPU p95 under 50 % of its
# threads, the public mirrors (neighbour container) under 1 vCPU at p95, the load generator
# under 70 % of its 2 vCPU at p95.
SEUIL_HOTE_CPU = 0.50
SEUIL_VOISIN_VCPU = 1.0
SEUIL_GENERATEUR_VCPU = 1.4


def quantile(values, q):
    values = sorted(v for v in values if v is not None)
    if not values:
        return None
    pos = (len(values) - 1) * q
    lo, hi = math.floor(pos), math.ceil(pos)
    return values[lo] + (values[hi] - values[lo]) * (pos - lo)


def mediane(values):
    return quantile(values, 0.5)


def lire_evenements(path):
    events = {}
    with open(path) as f:
        for line in f:
            t, _, label = line.strip().partition(' ')
            if label and label not in events:
                events[label] = float(t)
    return events


def lire_meta(path):
    meta = {}
    with open(path) as f:
        for line in f:
            key, _, value = line.rstrip('\n').partition('=')
            if key:
                parts = shlex.split(value) if value else ['']
                meta[key] = parts[0] if parts else ''
    for key in ('vcpu', 'memoire_mio', 'swap_mio', 'utilisateurs', 'jeu_de_donnees',
                'taille_installee', 'taille_jeu', 'taille_fin', 'fils_hote'):
        if key in meta and meta[key] not in ('', None):
            meta[key] = int(meta[key])
    return meta


def lire_echantillons(path):
    meta, samples = None, []
    with open(path) as f:
        for line in f:
            d = json.loads(line)
            if 'meta' in d:
                meta = d['meta']
            else:
                samples.append(d)
    return meta, samples


def ws(group):
    if not group or group.get('mem') is None or not group.get('stat'):
        return None
    return group['mem'] - group['stat'].get('inactive_file', 0)


def fenetre(samples, debut, fin):
    return [s for s in samples if debut <= s['t'] <= fin]


def serie_cpu(samples, getter):
    """vCPU used between consecutive samples, from a cumulative usage_usec."""
    out = []
    for a, b in zip(samples, samples[1:]):
        ua, ub = getter(a), getter(b)
        dt = b['t'] - a['t']
        if ua is not None and ub is not None and dt > 0:
            out.append((ub - ua) / (dt * 1e6))
    return out


def serie_taux(samples, getter):
    out = []
    for a, b in zip(samples, samples[1:]):
        va, vb = getter(a), getter(b)
        dt = b['t'] - a['t']
        if va is not None and vb is not None and dt > 0:
            out.append((vb - va) / dt)
    return out


def resume_memoire(values):
    return {'mediane': mediane(values), 'p95': quantile(values, 0.95), 'pic': max(values) if values else None}


def resume_cpu(values):
    return {'moyenne': statistics.fmean(values) if values else None, 'p95': quantile(values, 0.95)}


def noms_conteneurs(samples):
    names = set()
    for s in samples:
        names.update(s.get('containers', {}))
    return sorted(names)


def pile_ws(sample):
    values = [ws(c) for c in sample.get('containers', {}).values()]
    values = [v for v in values if v is not None]
    return sum(values) if values else None


def pile_cpu(sample):
    values = [c['cpu']['usage_usec'] for c in sample.get('containers', {}).values() if c.get('cpu')]
    return sum(values) if values else None


def hote_occupation(samples):
    out = []
    for a, b in zip(samples, samples[1:]):
        ca, cb = a['host']['cpu'], b['host']['cpu']
        total = sum(cb.values()) - sum(ca.values())
        idle = (cb['idle'] + cb['iowait']) - (ca['idle'] + ca['iowait'])
        if total > 0:
            out.append((total - idle) / total)
    return out


def analyser_k6(path, debut, fin):
    """Publish requests, deliveries and WebSocket errors of the measurement window."""
    if not os.path.exists(path):
        return None
    durees, echecs, publies, livraisons, erreurs_ws = [], 0, 0, [], 0
    requetes = 0
    with gzip.open(path, 'rt', newline='') as f:
        for row in csv.DictReader(f):
            name = row['metric_name']
            t = int(row['timestamp']) / 1e6
            value = float(row['metric_value'])
            tags = row.get('extra_tags') or ''
            if name == 'http_req_duration' and 'role=script' in tags and debut <= t <= fin:
                durees.append(value)
            elif name == 'http_req_failed' and 'role=script' in tags and debut <= t <= fin:
                requetes += 1
                echecs += 1 if value >= 1 else 0
            elif name == 'ntfy_publies' and debut <= t <= fin - FIN_LIVRAISON_S:
                publies += int(value)
            elif name == 'ntfy_livraison':
                publie = t - value / 1000
                if debut <= publie <= fin - FIN_LIVRAISON_S:
                    livraisons.append(value)
            elif name == 'ntfy_erreurs_ws' and debut <= t <= fin:
                erreurs_ws += int(value)
    attendues = publies * 3
    return {
        'requetes': requetes,
        'taux_erreur': (echecs / requetes) if requetes else None,
        'publication_ms': {'mediane': mediane(durees), 'p95': quantile(durees, 0.95), 'max': max(durees) if durees else None},
        'livraison_ms': {'mediane': mediane(livraisons), 'p95': quantile(livraisons, 0.95), 'max': max(livraisons) if livraisons else None},
        'messages_publies': publies,
        'livraisons_attendues': attendues,
        'livraisons_recues': len(livraisons),
        'taux_livraison': (len(livraisons) / attendues) if attendues else None,
        'erreurs_ws': erreurs_ws,
    }


def evenements_memoire(samples, key):
    """OOM kills and memory.high or memory.max hits over the samples, for the container and the stack."""
    first, last = samples[0], samples[-1]
    out = {}
    def delta(a, b, k):
        if a and b and a.get('events') and b.get('events'):
            return b['events'].get(k, 0) - a['events'].get(k, 0)
        return None
    out['ct_oom_kill'] = delta(first.get('ct'), last.get('ct'), 'oom_kill')
    out['ct_max'] = delta(first.get('ct'), last.get('ct'), 'max')
    out['conteneurs_oom_kill'] = 0
    for name in noms_conteneurs(samples):
        seq = [s['containers'][name] for s in samples if name in s.get('containers', {})]
        d = delta(seq[0], seq[-1], 'oom_kill') if seq else None
        out['conteneurs_oom_kill'] += d or 0
    return out


def analyser_passage(dossier):
    ev = lire_evenements(os.path.join(dossier, 'evenements.txt'))
    meta = lire_meta(os.path.join(dossier, 'meta.env'))
    _, samples = lire_echantillons(os.path.join(dossier, 'echantillons.jsonl'))
    if 'mesure_fin' not in ev or not samples:
        return {'dossier': os.path.basename(dossier), 'complet': False}
    m0, m1 = ev['mesure_debut'], ev['mesure_fin']
    mesure = fenetre(samples, m0, m1)
    socle = fenetre(samples, ev['socle_debut'], ev['socle_fin'])
    install = fenetre(samples, ev['installation_debut'], ev['installation_fin'])

    r = {'dossier': os.path.basename(dossier), 'complet': True, 'meta': meta,
         'fenetre_mesure_s': m1 - m0, 'echantillons_mesure': len(mesure)}

    # The base of the operating system: the whole container at rest, before any installation.
    r['socle'] = {'ws': resume_memoire([ws(s['ct']) for s in socle]),
                  'cpu': resume_cpu(serie_cpu(socle, lambda s: s['ct']['cpu']['usage_usec']))}

    # Installation: time to the first healthy response, and the peak of the first start.
    r['installation'] = {
        'premiere_reponse_saine_s': (ev['sain'] - ev['installation_debut']) if 'sain' in ev else None,
        'pile_ws_pic': max((v for v in (pile_ws(s) for s in install) if v is not None), default=None),
        'ct_ws_pic': max((v for v in (ws(s['ct']) for s in install) if v is not None), default=None),
        'pile_memory_peak': sum((c.get('peak') or 0) for c in install[-1]['containers'].values()) if install else None,
    }

    # The measurement window.
    conteneurs = {}
    for name in noms_conteneurs(mesure):
        seq = [s for s in mesure if name in s.get('containers', {})]
        conteneurs[name] = {
            'ws': resume_memoire([ws(s['containers'][name]) for s in seq]),
            'cpu': resume_cpu(serie_cpu(seq, lambda s, n=name: s['containers'][n]['cpu']['usage_usec'])),
            'pids_max': max((s['containers'][name].get('pids') or 0) for s in seq),
        }
    r['conteneurs'] = conteneurs
    r['pile'] = {'ws': resume_memoire([pile_ws(s) for s in mesure]), 'cpu': resume_cpu(serie_cpu(mesure, pile_cpu))}
    r['ct'] = {'ws': resume_memoire([ws(s['ct']) for s in mesure]),
               'cpu': resume_cpu(serie_cpu(mesure, lambda s: s['ct']['cpu']['usage_usec'])),
               'swap_max': max((s['ct'].get('swap') or 0) for s in mesure),
               'memory_max': mesure[0]['ct'].get('max')}
    lect = serie_taux(mesure, lambda s: (s.get('disk') or {}).get('nread'))
    ecr = serie_taux(mesure, lambda s: (s.get('disk') or {}).get('nwritten'))
    r['disque'] = {'lecture_octets_s': resume_cpu(lect), 'ecriture_octets_s': resume_cpu(ecr)}

    # Validity of the run: the host, the neighbours, the load generator.
    voisins = {}
    for vmid in sorted({v for s in mesure for v in s.get('voisins', {})}):
        voisins[vmid] = resume_cpu(serie_cpu(mesure, lambda s, v=vmid: (s.get('voisins', {}).get(v) or {}).get('cpu')))
    r['validite'] = {
        'hote_cpu': resume_cpu(hote_occupation(mesure)),
        'hote_psi_cpu_max': max(s['host']['psi']['cpu_some']['avg10'] for s in mesure),
        'hote_psi_io_max': max(s['host']['psi']['io_some']['avg10'] for s in mesure),
        'voisins_cpu': voisins,
        'generateur_cpu': resume_cpu(serie_cpu(mesure, lambda s: (s.get('gen') or {}).get('cpu', {}).get('usage_usec'))),
    }

    v = r['validite']
    invalide = []
    if (v['hote_cpu']['p95'] or 0) > SEUIL_HOTE_CPU:
        invalide.append('hôte occupé')
    if any((x['p95'] or 0) > SEUIL_VOISIN_VCPU for x in v['voisins_cpu'].values()):
        invalide.append('voisin occupé')
    if (v['generateur_cpu']['p95'] or 0) > SEUIL_GENERATEUR_VCPU:
        invalide.append('générateur saturé')
    v['valide'] = not invalide
    v['raisons'] = invalide

    # Criteria of a held profile.
    r['evenements_memoire'] = evenements_memoire(samples, 'events')
    redemarrages, oomkilled = 0, False
    path = os.path.join(dossier, 'conteneurs.txt')
    if os.path.exists(path):
        for line in open(path):
            m = re.search(r'restarts=(\d+) oomkilled=(\w+)', line)
            if m:
                redemarrages += int(m.group(1))
                oomkilled = oomkilled or m.group(2) == 'true'
    r['redemarrages'] = redemarrages
    r['k6'] = analyser_k6(os.path.join(dossier, 'k6.csv.gz'), m0, m1)
    raisons = []
    if r['evenements_memoire']['ct_oom_kill'] or r['evenements_memoire']['conteneurs_oom_kill'] or oomkilled:
        raisons.append('arrêt pour mémoire')
    if r['ct']['swap_max']:
        raisons.append('pages en swap')
    if redemarrages:
        raisons.append('redémarrage')
    k = r['k6']
    if k:
        if k['taux_erreur'] is None or k['taux_erreur'] >= SEUIL_ERREURS:
            raisons.append('erreurs de publication')
        if k['publication_ms']['p95'] is None or k['publication_ms']['p95'] >= SEUIL_P95_MS:
            raisons.append('p95 de publication')
        if k['livraison_ms']['p95'] is None or k['livraison_ms']['p95'] >= SEUIL_P95_MS:
            raisons.append('p95 de livraison')
        if k['taux_livraison'] is None or k['taux_livraison'] < 1 - SEUIL_ERREURS:
            raisons.append('messages non livrés')
        if k['erreurs_ws'] and k['livraisons_attendues'] and k['erreurs_ws'] / k['livraisons_attendues'] >= SEUIL_ERREURS:
            raisons.append('erreurs WebSocket')
    r['tenu'] = not raisons
    r['raisons'] = raisons

    # Disk growth per 1,000 units of data.
    if meta.get('jeu_de_donnees') and meta.get('taille_jeu') is not None:
        r['croissance_disque_par_1000'] = (meta['taille_jeu'] - meta['taille_installee']) / meta['jeu_de_donnees'] * 1000
    images = []
    path = os.path.join(dossier, 'images.txt')
    if os.path.exists(path):
        for line in open(path):
            parts = line.split()
            if len(parts) == 3:
                images.append({'digest': parts[0], 'id': parts[1], 'taille': int(parts[2])})
    r['images'] = images
    return r


def agreger(passages, chemin):
    """Median and range over the independent runs of a profile, for one metric."""
    values = []
    for p in passages:
        v = p
        for key in chemin:
            v = v.get(key) if isinstance(v, dict) else None
        if v is not None:
            values.append(v)
    if not values:
        return None
    med = mediane(values)
    return {'mediane': med, 'min': min(values), 'max': max(values), 'n': len(values),
            'ecart': ((max(values) - min(values)) / med) if med else None}


METRIQUES = {
    'pile_ws_mediane': ('pile', 'ws', 'mediane'),
    'pile_ws_p95': ('pile', 'ws', 'p95'),
    'pile_ws_pic': ('pile', 'ws', 'pic'),
    'pile_cpu_moyenne': ('pile', 'cpu', 'moyenne'),
    'pile_cpu_p95': ('pile', 'cpu', 'p95'),
    'ct_ws_mediane': ('ct', 'ws', 'mediane'),
    'ct_ws_pic': ('ct', 'ws', 'pic'),
    'ct_cpu_moyenne': ('ct', 'cpu', 'moyenne'),
    'ct_cpu_p95': ('ct', 'cpu', 'p95'),
    'disque_lecture_moyenne': ('disque', 'lecture_octets_s', 'moyenne'),
    'disque_ecriture_moyenne': ('disque', 'ecriture_octets_s', 'moyenne'),
    'disque_ecriture_p95': ('disque', 'ecriture_octets_s', 'p95'),
    'socle_ws_mediane': ('socle', 'ws', 'mediane'),
    'installation_reponse_saine_s': ('installation', 'premiere_reponse_saine_s'),
    'installation_pile_ws_pic': ('installation', 'pile_ws_pic'),
    'publication_p95_ms': ('k6', 'publication_ms', 'p95'),
    'livraison_p95_ms': ('k6', 'livraison_ms', 'p95'),
    'livraison_mediane_ms': ('k6', 'livraison_ms', 'mediane'),
    'taux_erreur': ('k6', 'taux_erreur'),
    'taux_livraison': ('k6', 'taux_livraison'),
    'croissance_disque_par_1000': ('croissance_disque_par_1000',),
    'hote_cpu_p95': ('validite', 'hote_cpu', 'p95'),
    'generateur_cpu_p95': ('validite', 'generateur_cpu', 'p95'),
}


def palier_candidat(profil, paliers):
    """The smallest tier that holds the profile's peaks, memory and CPU."""
    passages = profil['passages']
    pic_pile = max(max(p['pile']['ws']['pic'] or 0, p['installation']['pile_ws_pic'] or 0) for p in passages)
    socle = mediane([p['socle']['ws']['mediane'] for p in passages])
    besoin_memoire = (pic_pile + socle) * MARGE_MEMOIRE
    cpu_p95 = max(p['ct']['cpu']['p95'] or 0 for p in passages)
    for palier in sorted(paliers, key=lambda x: (x['ram_gio'], x['vcpu'])):
        if besoin_memoire <= palier['ram_gio'] * 1024 ** 3 and cpu_p95 <= PART_CPU * palier['vcpu']:
            return {'palier': palier, 'besoin_memoire_octets': besoin_memoire, 'pic_pile_octets': pic_pile,
                    'socle_octets': socle, 'cpu_p95_vcpu': cpu_p95}
    return {'palier': None, 'besoin_memoire_octets': besoin_memoire, 'cpu_p95_vcpu': cpu_p95}


def main():
    parser = argparse.ArgumentParser(description='analysis of a measured requirements campaign')
    parser.add_argument('campagne')
    parser.add_argument('--paliers', help='tiers read from the catalogue: [{"nom", "vcpu", "ram_gio"}]')
    parser.add_argument('--sortie')
    args = parser.parse_args()

    runs = []
    for name in sorted(os.listdir(args.campagne)):
        dossier = os.path.join(args.campagne, name)
        if os.path.isdir(dossier) and os.path.exists(os.path.join(dossier, 'evenements.txt')):
            runs.append(analyser_passage(dossier))

    profils = {}
    validations = []
    for r in runs:
        if not r.get('complet'):
            continue
        if '-palier-' in r['dossier']:
            validations.append(r)
            continue
        profils.setdefault(r['meta']['profil'], {'passages': []})['passages'].append(r)
    paliers = json.load(open(args.paliers)) if args.paliers else None
    for nom, profil in profils.items():
        profil['agregats'] = {k: agreger(profil['passages'], c) for k, c in METRIQUES.items()}
        profil['ecarts_a_rejouer'] = sorted(
            k for k, a in profil['agregats'].items()
            if a and a['ecart'] is not None and a['ecart'] > SEUIL_ECART
            # The rule holds the central values: a peak, read once per second, can catch or miss an event
            # shorter than a second (Docker's healthcheck, for instance), so it is published with its range
            # and the highest of the runs sizes the tier.
            and k in ('pile_ws_mediane', 'pile_cpu_moyenne', 'ct_ws_mediane', 'ct_cpu_moyenne')
            and (a['max'] - a['min']) > PLANCHERS['cpu' if 'cpu' in k else 'ws'])
        profil['tenu_partout'] = all(p['tenu'] for p in profil['passages'])
        profil['valide_partout'] = all(p['validite']['valide'] for p in profil['passages'])
        if paliers:
            profil['candidat'] = palier_candidat(profil, paliers)

    resultat = {'passages_incomplets': [r['dossier'] for r in runs if not r.get('complet')],
                'profils': profils, 'validations': validations}
    text = json.dumps(resultat, indent=1, ensure_ascii=False)
    if args.sortie:
        with open(args.sortie, 'w') as f:
            f.write(text)
    else:
        print(text)


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