#!/usr/bin/python3 -IB
"""Serve bounded, read-only turbostat reference samples over standard I/O."""

from datetime import datetime, timezone
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import time

TOOL = Path("/usr/bin/turbostat")
SYSTEM_TOOLS = (TOOL, Path("/usr/sbin/turbostat"))
SETPRIV = Path("/usr/bin/setpriv")
INSTALLED = Path("/usr/libexec/linux-hw-monitor/lhm-turbostat-reference")
OPTIONS = ("--quiet", "--interval", "1", "--num_iterations", "1",
           "--enable", "Time_Of_Day_Seconds,usec",
           "--show", "CPU,Avg_MHz,Bzy_MHz,Busy%,Time_Of_Day_Seconds,usec")


def trusted(path):
    try:
        return path.resolve(strict=True) == path and all(
            (info := part.stat()).st_uid == 0 and not info.st_mode & 0o022
            for part in (path, *path.parents)
        )
    except (OSError, RuntimeError):
        return False


def sample(tool=TOOL):
    attempts = []
    for transport in ("--no-perf", "--no-msr"):
        start = time.monotonic_ns()
        boot_offset = time.clock_gettime_ns(time.CLOCK_BOOTTIME) - start
        utc = datetime.now(timezone.utc).isoformat(timespec="milliseconds")
        arguments = (*OPTIONS, transport)
        status, code, out, err = "unavailable", None, b"", b""
        try:
            # Some versions try to load msr even when asked to use only perf.
            command = (str(SETPRIV), "--bounding-set=-sys_module", "--no-new-privs", "--", str(tool), *arguments)
            result = subprocess.run(command, stdin=subprocess.DEVNULL,
                                    capture_output=True, timeout=3, cwd="/",
                                    env={"LC_ALL": "C", "PATH": "/usr/sbin:/usr/bin"})
            code, out, err = result.returncode, result.stdout, result.stderr
            if code == 0 and b"Bzy_MHz" in out:
                status = "read"
        except subprocess.TimeoutExpired:
            err = b"turbostat sample timed out"
        except OSError as error:
            err = str(error).encode(errors="replace")
        end = time.monotonic_ns()
        if abs(time.clock_gettime_ns(time.CLOCK_BOOTTIME) - end - boot_offset) > 100_000_000:
            status, err = "suspend_boundary", b"turbostat sample crossed suspend"
        attempts.append({"program": str(tool), "arguments": arguments, "authorization": "polkit",
                         "started_utc": utc, "start_monotonic_ns": str(start), "end_monotonic_ns": str(end),
                         "status": status, "exit_code": code, "stdout": out[:256_000].decode(errors="replace"),
                         "stderr": err[:2048].decode(errors="replace")})
        if status in ("read", "suspend_boundary"):
            break
    return attempts


def serve(source, output, tool=TOOL):
    for _ in range(360):
        request = source.readline(8)
        if not request:
            return 0
        if request != b"sample\n":
            return 2
        print(json.dumps(sample(tool), separators=(",", ":")), file=output, flush=True)
    return 0


def main():
    tool = next((path for path in SYSTEM_TOOLS if trusted(path) and os.access(path, os.X_OK)), None)
    if (sys.argv[1:] != ["--read"] or os.geteuid() != 0
            or Path(__file__) != INSTALLED or not tool or not all(trusted(path) for path in (INSTALLED, SETPRIV))):
        print("The installed turbostat reader could not be verified.", file=sys.stderr)
        return 2

    def expire(*_):
        raise SystemExit(0)

    signal.signal(signal.SIGALRM, expire)
    signal.alarm(600)
    return serve(sys.stdin.buffer, sys.stdout, tool)


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