#!/usr/bin/python3
"""Collect Open vSwitch datapath statistics in Prometheus text format."""

import os
import re
import subprocess
import sys
import tempfile
from collections import namedtuple

OVS_DPCTL = "/usr/bin/ovs-dpctl"

DATAPATH_RE = re.compile(r"^(\S+):\s*$")
LOOKUPS_RE = re.compile(r"^lookups:\s+hit:(\d+)\s+missed:(\d+)\s+lost:(\d+)\s*$")
FLOWS_RE = re.compile(r"^flows:\s+(\d+)\s*$")
MASKS_RE = re.compile(r"^masks:\s+hit:(\d+)\s+total:(\d+)\b")
CACHE_RE = re.compile(r"^cache:\s+hit:(\d+)\b")

Metric = namedtuple("Metric", ["name", "mtype", "help_text", "key"])
Datapath = namedtuple("Datapath", ["name", "stats"])

DATAPATH_METRICS = (
    Metric(
        "ovs_dp_lookup_hit_total",
        "counter",
        "Packets matched by an existing kernel datapath flow.",
        "hit",
    ),
    Metric(
        "ovs_dp_lookup_missed_total",
        "counter",
        (
            "Packets without a matching kernel flow that required an upcall "
            "to ovs-vswitchd. Misses are not necessarily errors."
        ),
        "missed",
    ),
    Metric(
        "ovs_dp_lookup_lost_total",
        "counter",
        "Failed datapath upcalls, commonly because the upcall queue was full.",
        "lost",
    ),
    Metric("ovs_dp_flows", "gauge", "Current number of datapath flows.", "flows"),
    Metric("ovs_dp_masks", "gauge", "Current number of datapath masks.", "masks"),
    Metric(
        "ovs_dp_masks_hit_total",
        "counter",
        "Cumulative datapath mask lookups.",
        "masks_hit",
    ),
    Metric(
        "ovs_dp_cache_hit_total",
        "counter",
        "Cumulative datapath cache hits.",
        "cache_hit",
    ),
)


def escape_label(value):
    return value.replace("\\", "\\\\").replace("\n", "\\n").replace('"', '\\"')


def parse_show(text):
    """Parse `ovs-dpctl show`. Lines other than datapath stats are ignored."""
    datapaths = []
    current = None

    for raw in text.splitlines():
        line = raw.strip()
        if not line:
            continue

        # A datapath header is the only unindented line we care about:
        # "system@ovs-system:"
        if not raw[0].isspace():
            header = DATAPATH_RE.match(line)
            if header is None:
                continue
            current = Datapath(header.group(1), {})
            datapaths.append(current)
            continue

        if current is None:
            continue

        lookups = LOOKUPS_RE.match(line)
        if lookups:
            current.stats["hit"] = int(lookups.group(1))
            current.stats["missed"] = int(lookups.group(2))
            current.stats["lost"] = int(lookups.group(3))
            continue
        flows = FLOWS_RE.match(line)
        if flows:
            current.stats["flows"] = int(flows.group(1))
            continue
        masks = MASKS_RE.match(line)
        if masks:
            current.stats["masks_hit"] = int(masks.group(1))
            current.stats["masks"] = int(masks.group(2))
            continue
        cache = CACHE_RE.match(line)
        if cache:
            current.stats["cache_hit"] = int(cache.group(1))

    return datapaths


def format_metrics(datapaths):
    """Return Prometheus text for the datapaths `ovs-dpctl show` reported."""
    lines = []
    for metric in DATAPATH_METRICS:
        samples = []
        for dp in datapaths:
            if metric.key not in dp.stats:
                continue
            samples.append((dp.name, dp.stats[metric.key]))
        if not samples:
            continue
        lines.append(f"# HELP {metric.name} {metric.help_text}")
        lines.append(f"# TYPE {metric.name} {metric.mtype}")
        for name, value in samples:
            lines.append(f'{metric.name}{{datapath="{escape_label(name)}"}} {value}')
    if not lines:
        return ""
    return "\n".join(lines) + "\n"


def read_show():
    """Return `ovs-dpctl show` stdout, or None when the command fails."""
    proc = subprocess.run(
        [OVS_DPCTL, "show"], check=False, capture_output=True, text=True
    )
    if proc.returncode != 0:
        sys.stderr.write(proc.stderr or "ovs-dpctl show failed\n")
        return None
    return proc.stdout


def publish(text):
    """Replace OUTFILE with text. Print text when OUTFILE is not set."""
    path = os.environ.get("OUTFILE")
    if not path:
        sys.stdout.write(text)
        return

    directory = os.path.dirname(path) or "."
    fd, tmp = tempfile.mkstemp(dir=directory, prefix=".ovsmon.")
    try:
        with os.fdopen(fd, "w") as handle:
            handle.write(text)
        os.chmod(tmp, 0o644)
        os.rename(tmp, path)
    except OSError:
        if os.path.exists(tmp):
            os.unlink(tmp)
        raise


def main():
    # Hosts without Open vSwitch have nothing to export. Leave any previous
    # file in place so a missing binary does not erase the last good sample.
    if not os.access(OVS_DPCTL, os.X_OK):
        return 0
    show = read_show()
    if show is None:
        return 1
    text = format_metrics(parse_show(show))
    # An empty show means there is no datapath to export. Non-empty output
    # that produced no samples is unrecognized, so keep the previous file.
    if not text and show.strip():
        sys.stderr.write("ovs-dpctl show produced no datapath statistics\n")
        return 1
    publish(text)
    return 0


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