#!/usr/bin/python3 -I
# Wombat-Email: what collectd can't count by itself, for the panel's Stats graphs (installer/88-stats.sh
# installs it as /usr/local/lib/wombat-email/wombat-email-stats; collectd's exec plugin runs it, as the
# unprivileged user wombat-stats, and keeps it running). Once a minute it prints collectd PUTVAL lines:
#   rspamd     what Rspamd decided (its own running counts, from its controller on 127.0.0.1), and viruses
#   queue      messages waiting in Postfix's queue, by queue
#   services   1 for each service that's running, 0 for one that isn't (graphed as availability)
#   files      the root disk's files (inodes) used and free: Maildir keeps every message as a file (collectd's
#              df plugin left "free" unknown here)
# The counts in the logs (mail in and out, logins, bans) are collectd's own tail plugin.
import json, os, subprocess, sys, time, urllib.request

HOST = os.environ.get("COLLECTD_HOSTNAME", "wombat-email")
INTERVAL = int(float(os.environ.get("COLLECTD_INTERVAL", "60")))
SERVICES = ["postfix", "dovecot", "rspamd", "clamav-daemon", "redis-server", "postgresql", "unbound", "apache2", "fail2ban"]
ACTIONS = {"no action": "clean", "add header": "spam_folder", "rewrite subject": "spam_subject", "reject": "rejected",
           "soft reject": "soft_rejected", "greylist": "greylisted"}


def put(ident, value):
    print(f'PUTVAL "{HOST}/{ident}" interval={INTERVAL} N:{value}', flush=True)


def rspamd(path):
    with urllib.request.urlopen(f"http://127.0.0.1:11334/{path}", timeout=10) as r:
        return json.load(r)


def once():
    try:
        st = rspamd("stat")
        for name, ident in ACTIONS.items():
            put(f"rspamd/derive-{ident}", int(st.get("actions", {}).get(name, 0)))
        put("rspamd/derive-scanned", int(st.get("scanned", 0)))
        put("rspamd/derive-learned", int(st.get("learned", 0)))
        hits = {c.get("symbol"): c.get("hits", 0) for c in rspamd("counters")}
        put("rspamd/derive-virus", int(hits.get("CLAM_VIRUS", 0)))
    except Exception:
        pass   # Rspamd restarting: this minute is left out, never made up
    try:
        run = subprocess.run(["/usr/sbin/postqueue", "-j"], capture_output=True, text=True, timeout=20)
        if run.returncode != 0:
            raise RuntimeError(run.stderr)   # an empty answer isn't an empty queue
        out = run.stdout
        queues = {"active": 0, "deferred": 0, "hold": 0, "incoming": 0, "maildrop": 0}
        for line in out.splitlines():
            q = json.loads(line).get("queue_name", "")
            if q in queues:
                queues[q] += 1
        put("postfix/gauge-queue_waiting", queues["deferred"])
        put("postfix/gauge-queue_active", queues["active"] + queues["incoming"] + queues["maildrop"])
        put("postfix/gauge-queue_hold", queues["hold"])
    except Exception:
        pass
    try:
        fs = os.statvfs("/")
        put("files-root/gauge-used", fs.f_files - fs.f_ffree)
        put("files-root/gauge-free", fs.f_favail)
    except Exception:
        pass
    try:
        states = subprocess.run(["systemctl", "is-active", *SERVICES], capture_output=True, text=True, timeout=20).stdout.split()
        if len(states) != len(SERVICES):
            raise RuntimeError("systemctl")
        for unit, state in zip(SERVICES, states):
            put(f"services/gauge-{unit}", 1 if state == "active" else 0)
    except Exception:
        pass


while True:
    start = time.time()
    once()
    time.sleep(max(1, INTERVAL - (time.time() - start)))
