#!/usr/bin/python3 -I
"""lexivirt-health: keeps the LexiVirt OS web console reachable and tells the console screen the truth.

Every few seconds at boot (every 30 s once the console is up) it:
* finds the management adapter by the MAC address chosen at installation (/etc/lexivirt/mgmt-mac)
  and its IPv4 addresses;
* makes a real HTTPS request to the web console, on 127.0.0.1 and on each management address,
  and checks that the server presents this host's own certificate and answers /api/v1/health;
* checks that the firewall lets port 443 in on the management adapter's zone, that VM storage
  disks from the installation are mounted, and that software RAID arrays are complete;
* every 5 minutes, checks the sign-in, SSH, sudo and console rules (`lexivirtctl access status`,
  controlplane/lexivirt/hostaccess.py); problems are reported, never repaired automatically;
* writes the result to /run/lexivirt/console-status.json and to the console's sign-in screen
  (/etc/issue.d/50-lexivirt.issue). "Web console ready" appears only after the HTTPS check passed.
  The sign-in screen names failed access rules by their id only, never an account name.

Recovery, with reasons logged to the journal and /var/log/lexivirt/health.log:
* lexivirt.service failed  -> reset and start it again, with growing pauses (30 s ... 5 min);
* running but HTTPS fails for 3 minutes -> restart it (at most every 10 minutes).
It never touches libvirt or virtual machines: they keep running whatever the web console
does. Nothing is done while an update holds its maintenance flag, or when an administrator disabled
lexivirt.service.
"""
from __future__ import annotations

import http.client
import ipaddress
import json
import os
import re
import ssl
import subprocess
import sys
import time

CERT = "/etc/lexivirt/tls/server.crt"
MAC_FILE = "/etc/lexivirt/mgmt-mac"
POOLS = "/etc/lexivirt/installer-pools.json"
STATUS = "/run/lexivirt/console-status.json"
ISSUE = "/etc/issue.d/50-lexivirt.issue"
EVENTS = "/var/log/lexivirt/health.log"
MAINTENANCE = "/var/lib/lexivirt/update/maintenance"
UNIT = "lexivirt.service"
PORT = 443
FAST, SLOW = 5, 30
RESTART_AFTER = 180          # seconds of failed HTTPS while the service runs
RESTART_EVERY = 600
ACCESS_EVERY = 300           # seconds between access checks
LEXIVIRTCTL = "/usr/local/sbin/lexivirtctl"


def run(*args: str, timeout: int = 15) -> tuple[int, str]:
    try:
        r = subprocess.run(args, capture_output=True, text=True, timeout=timeout)
        return r.returncode, (r.stdout or "") + (r.stderr if r.returncode else "")
    except (OSError, subprocess.SubprocessError) as e:
        return 127, str(e)


def event(kind: str, **kw) -> None:
    rec = {"time": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "event": kind, **kw}
    print(json.dumps(rec), flush=True)        # journal
    try:
        os.makedirs(os.path.dirname(EVENTS), exist_ok=True)
        with open(EVENTS, "a") as f:
            f.write(json.dumps(rec) + "\n")
    except OSError:
        pass


def mgmt() -> dict:
    mac = ""
    try:
        mac = open(MAC_FILE).read().strip().lower()
    except OSError:
        pass
    out = {"mac": mac, "iface": "", "link": False, "addresses": []}
    for n in sorted(os.listdir("/sys/class/net")):
        try:
            if mac and open(f"/sys/class/net/{n}/address").read().strip().lower() == mac:
                out["iface"] = n
                out["link"] = open(f"/sys/class/net/{n}/carrier").read().strip() == "1"
        except OSError:
            continue
    if out["iface"]:
        rc, txt = run("ip", "-j", "-4", "addr", "show", "dev", out["iface"])
        try:
            for a in (json.loads(txt)[0].get("addr_info") or []) if rc == 0 and txt.strip() else []:
                out["addresses"].append(f"{a['local']}/{a['prefixlen']}")
        except (ValueError, IndexError, KeyError):
            pass
    return out


def https(host: str) -> tuple[bool, str]:
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    try:
        ctx.load_verify_locations(CERT)       # the server must present this host's own certificate
    except (OSError, ssl.SSLError) as e:
        return False, f"no TLS certificate at {CERT} ({e})"
    ctx.check_hostname = False
    c = http.client.HTTPSConnection(host, PORT, timeout=8, context=ctx)
    try:
        c.request("GET", "/api/v1/health", headers={"User-Agent": "lexivirt-health"})
        r = c.getresponse()
        body = r.read(4096)
        if r.status != 200:
            return False, f"HTTP {r.status}"
        data = json.loads(body)
        if not isinstance(data, dict):
            return False, "invalid health response"
        return (data.get("status") == "ok"), f"status {data.get('status')}, version {data.get('version')}"
    except ssl.SSLCertVerificationError as e:
        return False, f"TLS: the server's certificate is not this host's ({e.verify_message})"
    except (OSError, ssl.SSLError, http.client.HTTPException, ValueError) as e:
        return False, type(e).__name__ + (f": {e}" if str(e) else "")
    finally:
        c.close()


def unit_state() -> dict:
    rc, txt = run("systemctl", "show", UNIT, "-p", "ActiveState,SubState,Result,NRestarts,ExecMainStatus,"
                  "UnitFileState,ActiveEnterTimestampMonotonic,Job")
    st = dict(line.split("=", 1) for line in txt.splitlines() if "=" in line)
    try:
        since = int(st.get("ActiveEnterTimestampMonotonic", "0")) / 1e6
    except ValueError:
        since = 0.0
    st["running_for"] = max(0.0, time.monotonic() - since) if since else 0.0
    return st


def firewall(iface: str) -> str:
    """'port 443 open (zone Z)', 'BLOCKED: ...' only when firewalld answered that it is closed, or
    'unknown: ...' when it did not answer (a busy host): an unanswered question never blocks READY."""
    rc, _ = run("systemctl", "is-active", "--quiet", "firewalld")
    if rc != 0:
        return "firewall not running (port 443 not filtered)"
    zone = ""
    if iface:
        rc, out = run("firewall-cmd", f"--get-zone-of-interface={iface}", timeout=30)
        if rc == 0 and out.strip():
            zone = out.strip()
        elif rc not in (0, 2):                 # 2: "no zone" (the default zone applies)
            return f"unknown: firewalld did not answer ({out.strip()[:80]})"
    if not zone:
        rc, out = run("firewall-cmd", "--get-default-zone", timeout=30)
        if rc != 0 or not out.strip():
            return f"unknown: firewalld did not answer ({out.strip()[:80]})"
        zone = out.strip()
    answers = [run("firewall-cmd", f"--zone={zone}", q, timeout=30)[0]
               for q in ("--query-port=443/tcp", "--query-service=https")]
    if 0 in answers:
        return f"port 443 open (zone {zone})"
    if all(a == 1 for a in answers):           # firewall-cmd --query-*: 0 yes, 1 no
        return f"BLOCKED: port 443 is not open in firewall zone {zone}"
    return "unknown: firewalld did not answer the port query"


def storage_notes() -> list[str]:
    notes = []
    try:
        pools = json.load(open(POOLS))
    except (OSError, ValueError):
        pools = []
    for p in pools:
        if not os.path.ismount(p["mount"]):
            notes.append(f"VM storage {p['pool']} ({p['label']}) is NOT mounted at {p['mount']}")
    try:
        md = open("/proc/mdstat").read()
    except OSError:
        md = ""
    for name, state in re.findall(r"^(md\S+) : .*?\n.*?\[([U_]+)\]", md, re.M | re.S):
        if "_" in state:
            notes.append(f"RAID {name} is DEGRADED [{state}]: replace the failed disk")
    if re.search(r"(resync|recovery)\s*=\s*[\d.]+%", md):
        notes.append("RAID synchronisation in progress (the host is usable meanwhile)")
    return notes


def version() -> str:
    try:
        return open("/etc/lexivirt-release").read().strip()
    except OSError:
        return "LexiVirt OS"


def plain(s: str) -> str:
    """agetty expands backslash escapes in issue files; dynamic text must not contain any."""
    return s.replace("\\", "/")


def uptime() -> float:
    try:
        return float(open("/proc/uptime").read().split()[0])
    except (OSError, ValueError, IndexError):
        return 0.0


AGETTY_RELOAD = "/run/agetty.reload"


def write_issue(text: str, redraw: bool = True) -> None:
    os.makedirs(os.path.dirname(ISSUE), exist_ok=True)
    try:
        if open(ISSUE).read() == text:
            return
    except OSError:
        pass
    tmp = ISSUE + ".tmp"
    with open(tmp, "w") as f:
        f.write(text)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, ISSUE)
    # Redraw the sign-in prompts. Only when agetty created its trigger file itself: if this service
    # created it first (before any agetty ran), it would carry this service's security context, agetty
    # could not watch it, and the screen would never be redrawn (seen on the 2.3.0-rc3 test hosts).
    if redraw and os.path.exists(AGETTY_RELOAD):
        run("agetty", "--reload")


def fix_old_issue() -> None:
    """2.2.x put 'Web console: https://\\4/' in /etc/issue: \\4 is whichever adapter came first, not
    necessarily the management one. The verified address now comes from this service."""
    try:
        s = open("/etc/issue").read()
    except OSError:
        return
    if "Web console: https://\\4/" in s:
        with open("/etc/issue.tmp", "w") as f:
            f.write(s.replace("Web console: https://\\4/\n", ""))
        os.replace("/etc/issue.tmp", "/etc/issue")


def reset_screen() -> None:
    """At the start of every boot, before the sign-in prompt: the previous boot's state is not shown
    as if it were current (READY appears only after this boot's own HTTPS check)."""
    write_issue(f"{version()}   host \\n\nWeb console: checking (not verified yet since this start-up)\n\n",
                redraw=False)          # runs before any agetty: nothing to redraw yet


def access_status() -> dict:
    """The access rules, from the control plane's own checker. ok: True, False, or None (could not check)."""
    rc, out = run(LEXIVIRTCTL, "access", "status", "--json", timeout=90)
    try:
        st = json.JSONDecoder().raw_decode(out[out.index("{"):])[0]
    except ValueError:
        return {"ok": None, "problems": [], "error": plain(out)[-200:] or f"exit {rc}"}
    problems = [{"id": c["id"], "severity": c["severity"], "text": c["text"]} for c in st.get("checks", []) if not c["ok"]]
    return {"ok": bool(st.get("ok")) and not problems, "problems": problems, "checked_at": st.get("checked_at", "")}


def access_line(acc: dict) -> str:
    if acc.get("ok") is None:
        return f"Access: not checked ({acc.get('error', 'no result')})"
    if acc["ok"]:
        return "Access: sign-in, SSH and sudo checked, no problems"
    ids = ", ".join(p["id"] for p in acc["problems"][:4])
    return (f"Access: {len(acc['problems'])} problem(s): {ids}. Sign in and run sudo lexivirtctl access status, "
            "or open Hosts > Access in the web console.")


def booting() -> bool:
    rc, out = run("systemctl", "is-system-running")
    return out.strip() in ("initializing", "starting")


def main() -> int:
    if "--reset" in sys.argv:
        fix_old_issue()
        reset_screen()
        return 0
    once = "--once" in sys.argv
    fix_old_issue()
    failing_since: float | None = None
    last_restart = -1e9
    backoff, next_start = 30, 0.0
    was_ready = None
    since_text = ""
    access, access_at = {"ok": None, "problems": [], "error": "first check pending"}, -1e9
    while True:
        if time.monotonic() - access_at >= ACCESS_EVERY:
            before = access.get("ok")
            access, access_at = access_status(), time.monotonic()
            if access.get("ok") != before:
                event("access-ok" if access.get("ok") else "access-problems", problems=access.get("problems"),
                      error=access.get("error"))
        m = mgmt()
        u = unit_state()
        targets = ["127.0.0.1"] + [a.split("/")[0] for a in m["addresses"]]
        checks = {t: https(t) for t in targets}
        ready = (u.get("ActiveState") == "active" and m["link"] and len(targets) > 1
                 and all(ok for ok, _ in checks.values()))
        local_ok = checks["127.0.0.1"][0]
        reasons = []
        if not m["iface"]:
            reasons.append(f"management adapter {m['mac'] or '(unknown MAC)'} not found")
        elif not m["link"]:
            reasons.append(f"management adapter {m['iface']} has no link (cable or switch port)")
        elif not m["addresses"]:
            reasons.append(f"management adapter {m['iface']} has no IPv4 address (DHCP or static settings)")
        if u.get("ActiveState") != "active":
            reasons.append(f"web console service is {u.get('ActiveState')}/{u.get('SubState')} "
                           f"(result {u.get('Result')}, exit {u.get('ExecMainStatus')}, restarts {u.get('NRestarts')})")
        for t, (ok, why) in checks.items():
            if not ok:
                reasons.append(f"HTTPS to {t}: {why}")
        fw = firewall(m["iface"])
        notes = storage_notes()
        if fw.startswith("BLOCKED"):
            ready = False
            reasons.append(fw)
        maintenance = os.path.exists(MAINTENANCE)
        now = time.monotonic()
        # ---------------------------------------------------------------- recovery (web console only)
        action = ""
        enabled = u.get("UnitFileState") in ("enabled", "enabled-runtime", "static", "linked")
        if not maintenance and enabled and not once:
            # never second-guess systemd while it is still bringing the system up or has a start queued
            queued = bool(u.get("Job", "").strip())
            stopped = u.get("ActiveState") == "inactive" and not queued and not booting() and \
                (u.get("Result") != "success" or uptime() > 180)
            if (u.get("ActiveState") == "failed" and not queued) or stopped:
                if now >= next_start:
                    _, tail = run("journalctl", "-u", UNIT, "-b", "-n", "15", "-o", "cat", "--no-pager")
                    event("service-failed", state=u, journal=tail.splitlines()[-15:])
                    run("systemctl", "reset-failed", UNIT)
                    run("systemctl", "start", "--no-block", UNIT)
                    action = f"restarted the web console service (next attempt in {backoff} s if it fails again)"
                    event("service-start", reason="unit failed", backoff=backoff)
                    next_start, backoff = now + backoff, min(backoff * 2, 300)
            elif u.get("ActiveState") == "active" and not local_ok:
                failing_since = failing_since or now
                if now - failing_since >= RESTART_AFTER and u["running_for"] >= RESTART_AFTER \
                        and now - last_restart >= RESTART_EVERY:
                    event("service-restart", reason=checks["127.0.0.1"][1], seconds_failing=int(now - failing_since))
                    run("systemctl", "restart", "--no-block", UNIT)
                    action = "restarted the web console service: it ran but did not answer HTTPS for 3 minutes"
                    last_restart, failing_since = now, None
            if local_ok:
                failing_since, backoff = None, 30
        # ---------------------------------------------------------------- report
        addrs = [a.split("/")[0] for a in m["addresses"]]
        url = f"https://{addrs[0]}/" if addrs else "(no management address yet)"
        stamp = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime())
        if maintenance:
            ready = False
        if ready != was_ready or not since_text:
            since_text = stamp                 # the sign-in screen changes only when the state does
        status = {"ready": ready, "checked_at": stamp, "url": url if addrs else "", "management": m,
                  "service": {k: u.get(k) for k in ("ActiveState", "SubState", "Result", "NRestarts")},
                  "https": {t: {"ok": ok, "detail": why} for t, (ok, why) in checks.items()},
                  "firewall": fw, "storage": notes, "reasons": reasons, "action": action,
                  "update_in_progress": maintenance, "access": access}
        os.makedirs(os.path.dirname(STATUS), exist_ok=True)
        with open(STATUS + ".tmp", "w") as f:
            json.dump(status, f, indent=1)
        os.replace(STATUS + ".tmp", STATUS)
        lines = [f"{version()}   host \\n",
                 f"Management adapter: {m['iface'] or '?'} ({m['mac'] or 'MAC unknown'})  "
                 f"{', '.join(m['addresses']) or 'no IPv4 address'}  {'link up' if m['link'] else 'NO LINK'}"]
        if ready:
            lines.append(f"Web console READY: {url}   (HTTPS verified; since {since_text})")
            lines += [f"  also: https://{a}/" for a in addrs[1:]]
        else:
            lines.append(f"Web console NOT READY (since {since_text}); checking every {FAST} s, details in "
                         "/run/lexivirt/console-status.json.")
            lines += [f"  - {plain(r)}" for r in reasons[:5]]
            if maintenance:
                lines.append("  - an update is in progress")
            lines.append("  Sign in locally and run sudo lexivirt-diag for details.")
        if action:
            lines.append(f"  Action: {action}")
        lines.append(f"Firewall: {plain(fw)}")
        lines.append(access_line(access))
        lines += [f"Storage: {plain(n)}" for n in notes]
        write_issue("\n".join(lines) + "\n\n")
        if ready != was_ready:
            event("ready" if ready else "not-ready", url=url, reasons=reasons)
            was_ready = ready
        if once:
            print(json.dumps(status, indent=1))
            return 0 if ready else 1
        time.sleep(SLOW if ready else FAST)


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