#!/usr/bin/python3
# Nagios/Icinga plugin for the power draw of CPU packages and memory from the RAPL energy counters.
#
# Copyright (c) 2026 Thomas Wagner
# SPDX-License-Identifier: GPL-2.0-or-later

import argparse
import errno
import json
import os
import re
import sys
import tempfile
import time

OK = 0
WARNING = 1
CRITICAL = 2
UNKNOWN = 3

STATE_TEXT = {OK: "OK", WARNING: "WARNING", CRITICAL: "CRITICAL", UNKNOWN: "UNKNOWN"}

VERSION = "0.1"
POWERCAP = "sys/class/powercap"
ZONE_DIR = re.compile(r"^intel-rapl(:\d+)+$")   # also used for AMD; intel-rapl-mmio duplicates package-N
DEFAULT_INTERVAL = 1.0      # seconds between two readings when there is no usable saved reading
DEFAULT_MAX_AGE = 300       # seconds; an older saved reading may hide a counter wrap
MIN_AGE = 0.5               # seconds; a younger saved reading gives too noisy a value
SAFETY = 0.8                # use at most this share of the time a counter needs to wrap at full power


class PluginError(Exception):
    def __init__(self, state, message):
        super().__init__(message)
        self.state = state
        self.message = message


class ArgumentParser(argparse.ArgumentParser):
    """argparse exits 2 on a usage error, which Nagios reads as CRITICAL; exit UNKNOWN instead."""

    def error(self, message):
        self.print_usage(sys.stderr)
        sys.stderr.write("%s: error: %s\n" % (self.prog, message))
        sys.exit(UNKNOWN)


class Zone:
    """One RAPL power zone, e.g. intel-rapl:0 (package-0) or intel-rapl:0:0 (dram below package-0)."""

    def __init__(self, path, zone_id, name, max_range, max_power):
        self.path = path
        self.id = zone_id             # "0" or "0:0"
        self.name = name              # package-0, dram, core, uncore, psys, ...
        self.max_range = max_range    # microjoules after which energy_uj starts again at 0
        self.max_power = max_power    # microwatts, highest power limit of the zone, 0 if unknown
        self.parent = None
        self.label = name

    @property
    def top_level(self):
        return ":" not in self.id

    def counted(self, zones):
        """Whether the zone is added to the total.

        A package contains its core, uncore and graphics sub-zones, but not its memory (dram). psys
        (platform) measures the whole SoC and replaces the sum when the machine has it."""
        if any(z.name == "psys" for z in zones):
            return self.name == "psys"
        if self.top_level:
            return True
        return self.name == "dram"


def read_text(path):
    with open(path) as handle:
        return handle.read().strip()


def read_int(path):
    try:
        return int(read_text(path))
    except OSError as err:
        if err.errno in (errno.EACCES, errno.EPERM):
            raise PluginError(UNKNOWN, "no permission to read %s; the RAPL counters are readable by root "
                                       "only since Linux 5.10, run the plugin with sudo" % path)
        raise PluginError(UNKNOWN, "cannot read %s: %s" % (path, err.strerror))
    except ValueError:
        raise PluginError(UNKNOWN, "unexpected content in %s" % path)


def find_zones(root):
    base = os.path.join(root, POWERCAP)
    try:
        names = sorted(os.listdir(base))
    except OSError:
        names = []
    zones = {}
    for entry in names:
        if not ZONE_DIR.match(entry):
            continue
        path = os.path.join(base, entry)
        if not os.path.exists(os.path.join(path, "energy_uj")):
            continue
        max_power = 0
        for limit in sorted(os.listdir(path)):
            if re.match(r"^constraint_\d+_max_power_uw$", limit):
                try:
                    max_power = max(max_power, int(read_text(os.path.join(path, limit))))
                except (OSError, ValueError):
                    pass
        zone_id = entry.split(":", 1)[1]
        zones[zone_id] = Zone(path, zone_id, read_text(os.path.join(path, "name")),
                              read_int(os.path.join(path, "max_energy_range_uj")), max_power)
    if not zones:
        raise PluginError(UNKNOWN, "no RAPL zones in /%s (no supported CPU, or the intel_rapl_msr "
                                   "module is not loaded)" % POWERCAP)
    for zone in zones.values():
        if not zone.top_level:
            zone.parent = zones.get(zone.id.rsplit(":", 1)[0])
    for zone in zones.values():
        if zone.parent is not None:
            # dram below package-1 -> dram-1; without a number in the parent name use the zone id
            number = re.search(r"-(\d+)$", zone.parent.name)
            zone.label = "%s-%s" % (zone.name, number.group(1) if number else zone.parent.id)
    return sorted(zones.values(), key=lambda z: [int(x) for x in z.id.split(":")])


def read_energy(zones):
    return {zone.path: read_int(os.path.join(zone.path, "energy_uj")) for zone in zones}


def boot_id(root):
    try:
        return read_text(os.path.join(root, "proc/sys/kernel/random/boot_id"))
    except OSError:
        return ""


def default_state_file():
    if os.geteuid() == 0:
        return "/run/check_rapl/state.json"
    base = os.environ.get("XDG_RUNTIME_DIR") or os.path.join(os.path.expanduser("~"), ".cache")
    return os.path.join(base, "check_rapl", "state.json")


def load_state(path):
    try:
        fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
        with os.fdopen(fd) as handle:
            return json.load(handle)
    except (OSError, ValueError):
        return None


def save_state(path, state):
    """Write the readings atomically; a failure only costs the next run a fresh measurement."""
    try:
        directory = os.path.dirname(path)
        os.makedirs(directory, mode=0o700, exist_ok=True)
        fd, tmp = tempfile.mkstemp(dir=directory, prefix=".state.")
        with os.fdopen(fd, "w") as handle:
            json.dump(state, handle)
        os.replace(tmp, path)
    except OSError:
        pass


def delta(before, after, max_range):
    """Energy between two readings; the counter starts again at 0 after max_range."""
    if after >= before:
        return after - before
    return after + max_range - before


def safe_age(zones, max_age):
    """Longest gap between two readings in which no counter can wrap twice, at the zones' power limits."""
    limit = max_age
    for zone in zones:
        if zone.max_power > 0 and zone.max_range > 0:
            limit = min(limit, SAFETY * zone.max_range / zone.max_power)
    return limit


def measure(args, zones):
    """Return (seconds, {path: microjoules}) from a saved reading or from two readings now."""
    ident = boot_id(args.root)
    now = time.time()
    energy = read_energy(zones)
    state_file = None if args.no_state else (args.state_file or default_state_file())
    previous = load_state(state_file) if state_file else None
    if state_file:
        save_state(state_file, {"time": now, "boot_id": ident, "energy": energy})
    if previous and previous.get("boot_id") == ident and isinstance(previous.get("energy"), dict):
        age = now - float(previous.get("time", 0))
        old = previous["energy"]
        if MIN_AGE <= age <= safe_age(zones, args.max_age) and all(p in old for p in energy):
            return age, {z.path: delta(int(old[z.path]), energy[z.path], z.max_range) for z in zones}
    time.sleep(args.interval)
    later = read_energy(zones)
    seconds = time.time() - now
    if state_file:
        save_state(state_file, {"time": now + seconds, "boot_id": ident, "energy": later})
    return seconds, {z.path: delta(energy[z.path], later[z.path], z.max_range) for z in zones}


def watts(text):
    try:
        value = float(text)
    except ValueError:
        raise argparse.ArgumentTypeError("not a number: %r" % text)
    if value < 0:
        raise argparse.ArgumentTypeError("must not be negative: %r" % text)
    return value


def seconds(text):
    value = watts(text)
    if value <= 0:
        raise argparse.ArgumentTypeError("must be greater than 0: %r" % text)
    return value


def fmt(value):
    return ("%.1f" % value).rstrip("0").rstrip(".")


def perf_label(label):
    return re.sub(r"[^A-Za-z0-9]+", "_", label)


def run(args):
    zones = find_zones(args.root)
    span, energy = measure(args, zones)
    power = {z.path: energy[z.path] / span / 1e6 for z in zones}
    counted = [z for z in zones if z.counted(zones)]
    total = sum(power[z.path] for z in counted)
    what = "platform" if any(z.name == "psys" for z in counted) else \
        ("CPU+DRAM" if any(z.name == "dram" for z in counted) else "CPU")

    state = OK
    if args.critical is not None and total > args.critical:
        state = CRITICAL
    elif args.warning is not None and total > args.warning:
        state = WARNING

    parts = ", ".join("%s %s W" % (z.label, fmt(power[z.path])) for z in counted)
    message = "%s W %s (%s) over %s s" % (fmt(total), what, parts, fmt(span))
    if args.verbose:
        others = [z for z in zones if z not in counted]
        if others:
            message += "; included in the above: " + \
                ", ".join("%s %s W" % (z.label, fmt(power[z.path])) for z in others)

    threshold = "%s;%s" % ("" if args.warning is None else "%g" % args.warning,
                           "" if args.critical is None else "%g" % args.critical)
    perf = ["power=%.2fW;%s;0" % (total, threshold)]
    perf += ["%s=%.2fW;;;0" % (perf_label(z.label), power[z.path]) for z in zones]
    return state, message, perf


def build_parser():
    parser = ArgumentParser(
        prog="check_rapl",
        description="Report the power draw of the CPU packages and memory from the RAPL energy counters "
                    "(/sys/class/powercap/intel-rapl, Intel and AMD). The counters are readable by root "
                    "only, so run the plugin with sudo. Without a saved reading younger than --max-age it "
                    "measures over --interval seconds; otherwise it reports the average since the last run.")
    parser.add_argument("-w", "--warning", type=watts, metavar="WATTS",
                        help="WARNING if the total power is above this many watts")
    parser.add_argument("-c", "--critical", type=watts, metavar="WATTS",
                        help="CRITICAL if the total power is above this many watts")
    parser.add_argument("-i", "--interval", type=seconds, default=DEFAULT_INTERVAL, metavar="SECONDS",
                        help="measuring time without a usable saved reading (default: %s)" % fmt(DEFAULT_INTERVAL))
    parser.add_argument("--max-age", type=seconds, default=DEFAULT_MAX_AGE, metavar="SECONDS",
                        help="use a saved reading only up to this age (default: %d; also limited by the "
                             "time a counter needs to wrap at full power)" % DEFAULT_MAX_AGE)
    parser.add_argument("--state-file", metavar="FILE",
                        help="where to save the reading (default: /run/check_rapl/state.json as root, "
                             "else below $XDG_RUNTIME_DIR or ~/.cache)")
    parser.add_argument("--no-state", action="store_true",
                        help="do not save or use a reading, always measure over --interval")
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="also list the sub-zones that are part of a package (core, uncore, graphics)")
    parser.add_argument("--root", default="/", help=argparse.SUPPRESS)   # for the tests
    parser.add_argument("-V", "--version", action="version", version="check_rapl " + VERSION)
    return parser


def main():
    args = build_parser().parse_args()
    if os.geteuid() == 0 and os.environ.get("SUDO_USER") and (args.state_file or args.root != "/"):
        # a sudo rule for this plugin must not let the caller write or read files as root
        print("RAPL UNKNOWN - --state-file is not allowed when the plugin runs through sudo")
        return UNKNOWN
    if args.warning is not None and args.critical is not None and args.warning > args.critical:
        print("RAPL UNKNOWN - the warning threshold is above the critical threshold")
        return UNKNOWN
    try:
        state, message, perf = run(args)
    except PluginError as err:
        print("RAPL %s - %s" % (STATE_TEXT[err.state], err.message))
        return err.state
    print("RAPL %s - %s | %s" % (STATE_TEXT[state], message, " ".join(perf)))
    return state


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        sys.exit(UNKNOWN)
