#!/usr/bin/env python3
"""Korai Redis slowlog reader.

Reads the SLOWLOG of one or more Redis / Valkey servers (self-hosted, Memorystore, ElastiCache) every INTERVAL
seconds and sends each new entry to an OpenTelemetry collector as a log record (OTLP/HTTP JSON). Korai lists them
under Observability > Infrastructure > Redis > Slow commands.

Only the standard library: run it with any Python 3.9+, next to your collector.

Privacy: argument values are never sent. A record carries the command name and, for commands that take a key,
the key as a pattern (numbers, hex ids and UUIDs become "?"), so "GET cart:91822" is sent as "GET cart:?".

Environment:
  REDIS_ADDRS                  host:port[,host:port...]          (default localhost:6379)
  REDIS_PASSWORD / REDIS_USERNAME                                 (optional; ACL user or requirepass / AUTH string)
  REDIS_TLS=1                  connect with TLS; REDIS_TLS_INSECURE=1 skips certificate checks
  OTEL_EXPORTER_OTLP_ENDPOINT  the collector's OTLP/HTTP endpoint  (default http://localhost:4318)
  OTEL_EXPORTER_OTLP_HEADERS   k=v,k=v headers for the request    (optional)
  OTEL_RESOURCE_ATTRIBUTES     k=v,k=v, e.g. deployment.environment=prod
  INTERVAL                     seconds between reads              (default 30)
  SLOWLOG_COUNT                entries read per server per pass   (default 128)
  SLOWLOG_KEYS=1               also send each key as a pattern (default 0: names only)
"""
from __future__ import annotations

import json
import os
import re
import socket
import ssl
import sys
import time
import urllib.request

VERSION = "1.1.0"

# commands whose first argument is not a key (or whose arguments are scripts or options): only the name is sent
NO_KEY = {"AUTH", "HELLO", "PING", "ECHO", "SELECT", "INFO", "CONFIG", "CLIENT", "CLUSTER", "COMMAND", "DBSIZE", "DEBUG", "FLUSHALL",
          "FLUSHDB", "SLOWLOG", "LATENCY", "MEMORY", "MODULE", "MONITOR", "MULTI", "EXEC", "DISCARD", "WATCH", "UNWATCH", "SCRIPT",
          "EVAL", "EVALSHA", "EVAL_RO", "EVALSHA_RO", "FCALL", "FCALL_RO", "FUNCTION", "KEYS", "SCAN", "PUBLISH", "SUBSCRIBE",
          "PSUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE", "SPUBLISH", "XREAD", "XREADGROUP", "BLPOP", "BRPOP", "BLMPOP", "BZPOPMIN",
          "BZPOPMAX", "BZMPOP", "LMPOP", "ZMPOP", "WAIT", "SAVE", "BGSAVE", "BGREWRITEAOF", "LASTSAVE", "SHUTDOWN", "TIME", "ROLE",
          "REPLICAOF", "SLAVEOF", "SWAPDB", "RANDOMKEY", "OBJECT", "ACL", "RESET", "QUIT"}
# A key keeps only its structure. Its segments (between : / | # { } .) are all '?' except two, and only when they are
# short lowercase words: the first (the namespace: cart, session, user) and the last when the one before it was
# masked (user:42:profile). Names, e-mails, tokens and ids never stay, whatever their shape: a mixed-case or long
# token, a lowercase name in the middle (user:jane:cart) or at the end after the namespace (cart:jane) all become '?'.
_EMAIL = re.compile(r"[^\s:/|#{}]*@[^\s:/|#{}]*")
_SEP = re.compile(r"([:/|#{}.])")
_WORD = re.compile(r"^[a-z][a-z_-]{0,15}$")


def key_pattern(key: str) -> str:
    """cart:91822 -> cart:?, cache:jane@example.com -> cache:?, user:jane:profile -> user:?:profile,
    tok:AbCdEfGhIjKl -> tok:?, a key of one segment -> ?"""
    parts = _SEP.split(_EMAIL.sub("?", key))
    segs = [i for i, p in enumerate(parts) if p and not _SEP.fullmatch(p)]
    keep: set[int] = set()
    if len(segs) >= 2 and _WORD.match(parts[segs[0]]):
        keep.add(segs[0])
    if len(segs) >= 2 and segs[-2] not in keep and _WORD.match(parts[segs[-1]]):
        keep.add(segs[-1])
    return "".join("?" if i in segs and i not in keep else p for i, p in enumerate(parts))[:80]


def describe(args: list, keys: bool = False) -> tuple[str, str]:
    """(command name, command as sent to Korai) for one SLOWLOG entry's argument list."""
    words = [a.decode("utf-8", "replace") if isinstance(a, bytes) else str(a) for a in args]
    if not words:
        return "?", "?"
    name = words[0].upper()
    if not keys or name in NO_KEY or len(words) < 2 or words[1].startswith("(") and "more arguments" in words[1]:
        return name, name
    return name, f"{name} {key_pattern(words[1])}"


# ------------------------------------------------------------------ a minimal RESP client


class Redis:
    def __init__(self, host: str, port: int, password: str = "", username: str = "", tls: bool = False, insecure: bool = False, timeout: float = 5.0):
        sock = socket.create_connection((host, port), timeout=timeout)
        if tls:
            cx = ssl.create_default_context()
            if insecure:
                cx.check_hostname, cx.verify_mode = False, ssl.CERT_NONE
            sock = cx.wrap_socket(sock, server_hostname=host)
        self.sock, self.buf = sock, b""
        if password:
            self.call(*(["AUTH", username, password] if username else ["AUTH", password]))

    def close(self) -> None:
        try:
            self.sock.close()
        except OSError:
            pass

    def call(self, *args):
        out = b"*%d\r\n" % len(args) + b"".join(b"$%d\r\n%s\r\n" % (len(a), a) for a in (x.encode() if isinstance(x, str) else x for x in args))
        self.sock.sendall(out)
        return self._read()

    def _line(self) -> bytes:
        while b"\r\n" not in self.buf:
            chunk = self.sock.recv(65536)
            if not chunk:
                raise ConnectionError("connection closed")
            self.buf += chunk
        line, self.buf = self.buf.split(b"\r\n", 1)
        return line

    def _exact(self, n: int) -> bytes:
        while len(self.buf) < n + 2:
            chunk = self.sock.recv(65536)
            if not chunk:
                raise ConnectionError("connection closed")
            self.buf += chunk
        data, self.buf = self.buf[:n], self.buf[n + 2:]
        return data

    def _read(self):
        line = self._line()
        kind, rest = line[:1], line[1:]
        if kind == b"+":
            return rest.decode()
        if kind == b"-":
            raise RuntimeError(rest.decode())
        if kind == b":":
            return int(rest)
        if kind == b"$":
            n = int(rest)
            return None if n < 0 else self._exact(n)
        if kind == b"*":
            n = int(rest)
            return None if n < 0 else [self._read() for _ in range(n)]
        raise RuntimeError(f"unexpected reply {line[:40]!r}")


# ------------------------------------------------------------------ OTLP


def _kv(s: str) -> dict[str, str]:
    out = {}
    for part in (s or "").split(","):
        if "=" in part:
            k, v = part.split("=", 1)
            out[k.strip()] = urllib.request.unquote(v.strip())
    return out


def _attr(k: str, v) -> dict:
    return {"key": k, "value": {"intValue": str(v)} if isinstance(v, int) else {"stringValue": str(v)}}


def record(entry: list, host: str, port: int, keys: bool = False) -> dict:
    """One OTLP log record from one SLOWLOG entry: [id, unix time, microseconds, args, (client addr, client name)]."""
    eid, ts, us, args = int(entry[0]), int(entry[1]), int(entry[2]), entry[3] or []
    name, cmd = describe(args, keys)
    attrs = [_attr("db.system", "redis"), _attr("server.address", host), _attr("server.port", port), _attr("redis.slowlog.id", eid),
             _attr("redis.slowlog.duration_us", us), _attr("redis.slowlog.command", cmd), _attr("redis.slowlog.command_name", name),
             _attr("redis.slowlog.args", max(0, len(args) - 1))]
    return {"timeUnixNano": str(ts * 1_000_000_000), "observedTimeUnixNano": str(int(time.time() * 1e9)), "severityNumber": 13, "severityText": "WARN",
            "body": {"stringValue": f"Redis slow command {cmd} took {us / 1000:.1f} ms on {host}:{port}"}, "attributes": attrs}


def payload(records: list[dict], resource: dict[str, str]) -> dict:
    res = {"service.name": "redis-slowlog", **resource}
    return {"resourceLogs": [{"resource": {"attributes": [_attr(k, v) for k, v in res.items()]},
                              "scopeLogs": [{"scope": {"name": "korai-redis-slowlog", "version": VERSION}, "logRecords": records}]}]}


def send(endpoint: str, headers: dict[str, str], body: dict) -> None:
    url = endpoint.rstrip("/") + ("" if endpoint.rstrip("/").endswith("/v1/logs") else "/v1/logs")
    req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST", headers={"Content-Type": "application/json", **headers})
    with urllib.request.urlopen(req, timeout=10) as r:
        r.read()


# ------------------------------------------------------------------ the loop


def new_entries(entries: list, last_id: int | None, since: int) -> tuple[list, int | None]:
    """Entries after last_id (or, on the first read, newer than since). A server restart resets ids: start over."""
    if not entries:
        return [], last_id
    top = max(int(e[0]) for e in entries)
    if last_id is not None and top < last_id:
        last_id = None
    fresh = [e for e in entries if (int(e[0]) > last_id if last_id is not None else int(e[1]) >= since)]
    return sorted(fresh, key=lambda e: int(e[0])), top


def main() -> int:
    addrs = [a.strip() for a in os.environ.get("REDIS_ADDRS", "localhost:6379").split(",") if a.strip()]
    pw, user = os.environ.get("REDIS_PASSWORD", ""), os.environ.get("REDIS_USERNAME", "")
    tls, insecure = os.environ.get("REDIS_TLS") == "1", os.environ.get("REDIS_TLS_INSECURE") == "1"
    endpoint = os.environ.get("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT") or os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318")
    headers, resource = _kv(os.environ.get("OTEL_EXPORTER_OTLP_HEADERS", "")), _kv(os.environ.get("OTEL_RESOURCE_ATTRIBUTES", ""))
    interval, count = max(5, int(os.environ.get("INTERVAL", "30"))), int(os.environ.get("SLOWLOG_COUNT", "128"))
    keys = os.environ.get("SLOWLOG_KEYS", "0") == "1"
    last: dict[str, int | None] = {a: None for a in addrs}
    since = int(time.time()) - interval
    print(f"korai-redis-slowlog {VERSION}: {', '.join(addrs)} -> {endpoint} every {interval}s", flush=True)
    while True:
        records = []
        for a in addrs:
            host, _, port = a.rpartition(":")
            host, port = (host or a), int(port) if port.isdigit() else 6379
            r = None
            try:
                r = Redis(host, port, pw, user, tls, insecure)
                fresh, last[a] = new_entries(r.call("SLOWLOG", "GET", str(count)) or [], last[a], since)
                records += [record(e, host, port, keys) for e in fresh]
            except (OSError, RuntimeError, ConnectionError, ValueError) as e:
                print(f"{a}: {e}", file=sys.stderr, flush=True)
            finally:
                if r:
                    r.close()
        if records:
            try:
                send(endpoint, headers, payload(records, resource))
            except OSError as e:
                print(f"OTLP {endpoint}: {e}", file=sys.stderr, flush=True)
        time.sleep(interval)


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