Files
observability/deploy/monitoring/scripts/local.py
T

192 lines
8.4 KiB
Python

"""Local Docker Desktop monitoring; no credentials are written into the workspace."""
import argparse
import configparser
import json
import os
from pathlib import Path
import secrets
import socket
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
STATE = Path(os.environ.get("LOCALAPPDATA", str(Path.home() / ".local/share"))) / "weiyuan-observability"
SECRET = STATE / "grafana-admin-password.txt"
MYSQL_SECRET = STATE / "mysql-exporter.cnf"
PROJECT = "observability-local"
def validate_mysql_config(path):
if not path.is_file():
raise RuntimeError(f"Create the external mysql-exporter.cnf first: {path}")
config = configparser.ConfigParser(interpolation=None)
try:
config.read_string(path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, configparser.Error):
# Parser exceptions can contain entire lines, including credentials.
raise RuntimeError("Invalid MySQL config; expected UTF-8 INI with a [client] section. Contents hidden.") from None
if not config.has_section("client"):
raise RuntimeError("MySQL config needs a [client] section.")
for key in ("host", "user", "password"):
value = config.get("client", key, fallback="").strip().strip('\"\'')
if not value or value == "REPLACE_WITH_MYSQL_MONITOR_PASSWORD":
raise RuntimeError(f"Set a real {key} in the external MySQL config; value hidden.")
if config.get("client", "user").strip().strip('\"\'').lower() == "root":
raise RuntimeError("Use a dedicated monitoring account instead of root.")
try:
port = config.getint("client", "port")
if not 1 <= port <= 65535:
raise ValueError()
except (ValueError, TypeError, configparser.Error):
raise RuntimeError("MySQL port must be an integer between 1 and 65535.") from None
def mysql_smoke():
from urllib.parse import urlencode
from smoke import request, poll
validate_mysql_config(MYSQL_SECRET)
config = model()
binding = config["services"]["victoriametrics"]["ports"][0]
base = f"http://127.0.0.1:{binding['published']}"
started = time.time()
def has_value(expression, expected):
# Wait for a scrape after this check started, not a cached pre-restart value.
fresh = f"({expression}) and (timestamp({expression}) >= {started})"
data = json.loads(request(base + "/api/v1/query?" + urlencode({"query": fresh, "nocache": "1"})))
rows = data["data"]["result"]
return bool(rows) and all(float(row["value"][1]) == expected for row in rows)
poll("MySQL exporter scrape", lambda: has_value('up{job="mysql"}', 1))
poll("MySQL database connection", lambda: has_value('mysql_up{job="mysql"}', 1))
for collector in ("global_status", "global_variables"):
expression = f'mysql_exporter_collector_success{{job="mysql",collector="collect.{collector}"}}'
poll(f"MySQL {collector} collector", lambda expression=expression: has_value(expression, 1))
def check_port(service, ip, port, target, containers):
owned = False
for container in containers:
labels = container.get("Config", {}).get("Labels") or {}
for container_port, bindings in (container.get("NetworkSettings", {}).get("Ports") or {}).items():
for binding in bindings or []:
address = binding["HostIp"]
overlaps = address == ip or address in ("", "0.0.0.0", "::")
if int(binding["HostPort"]) != port or not overlaps:
continue
if (labels.get("com.docker.compose.project") == PROJECT
and labels.get("com.docker.compose.service") == service
and container_port == f"{target}/tcp" and address == ip):
owned = True
else:
raise RuntimeError(f"PORT CONFLICT: {service} {ip}:{port}, Docker owner {container['Name']}")
if owned:
return
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
try:
sock.bind((ip, port))
except OSError as exc:
raise RuntimeError(f"PORT CONFLICT: {service} {ip}:{port}: {exc}") from exc
def run(args, capture=False, timeout=900):
result = subprocess.run(args, cwd=ROOT, check=True, text=True, encoding="utf-8",
capture_output=capture, timeout=timeout)
return result.stdout if capture else None
def compose(*args, capture=False):
os.environ["LOCAL_GRAFANA_SECRET_FILE"] = SECRET.as_posix()
os.environ["LOCAL_MYSQL_SECRET_FILE"] = MYSQL_SECRET.as_posix()
# Credentials opt in to MySQL; include it on down even if the file was removed.
profiles = ["--profile", "mysql"] if MYSQL_SECRET.is_file() or "down" in args else []
return run(["docker", "compose", "--project-name", PROJECT,
"--env-file", str(ROOT / ".env.example"),
"-f", str(ROOT / "docker-compose.yml"),
"-f", str(ROOT / "docker-compose.local.yml"), *profiles, *args], capture)
def model():
return json.loads(compose("config", "--format", "json", capture=True))
def preflight(config):
run(["docker", "info", "--format", "{{.ServerVersion}}"], capture=True, timeout=30)
ids = run(["docker", "ps", "-q"], capture=True, timeout=30).split()
containers = json.loads(run(["docker", "inspect", *ids], capture=True, timeout=30)) if ids else []
seen = set()
for service, definition in config["services"].items():
if definition.get("profiles"):
continue
for binding in definition.get("ports", []):
ip = binding.get("host_ip", "0.0.0.0")
port, target = int(binding["published"]), int(binding["target"])
if ip != "127.0.0.1":
raise RuntimeError(f"Local stack requires loopback: {service} {ip}:{port}")
if (ip, port) in seen:
raise RuntimeError(f"Duplicate Compose binding: {ip}:{port}")
seen.add((ip, port))
check_port(service, ip, port, target, containers)
print(f"Port OK: {service} {ip}:{port}", flush=True)
print("Port preflight passed; no containers changed.", flush=True)
def ensure_secret():
STATE.mkdir(parents=True, exist_ok=True)
if not SECRET.exists():
fd = os.open(SECRET, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as stream:
stream.write(secrets.token_urlsafe(32))
if os.name == "nt":
identity = run(["whoami"], capture=True, timeout=10).strip()
run(["icacls", str(SECRET), "/inheritance:r", "/grant:r", f"{identity}:(F)"], capture=True, timeout=10)
print(f"Grafana user: admin; password file (outside workspace): {SECRET}", flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["check", "up", "smoke", "mysql-check", "ps", "down", "logs"])
args = parser.parse_args()
if args.action in ("check", "up"):
if MYSQL_SECRET.is_file():
validate_mysql_config(MYSQL_SECRET)
preflight(model())
if args.action == "up":
ensure_secret()
compose("pull")
compose("up", "-d")
compose("ps")
elif args.action == "smoke":
from smoke import smoke, grafana_smoke
config = model()
endpoints = {}
for service, definition in config["services"].items():
if definition.get("profiles"):
continue
for binding in definition.get("ports", []):
endpoints[(service, int(binding["target"]))] = f"http://127.0.0.1:{binding['published']}"
smoke(endpoints, application=True)
grafana_smoke(endpoints[("grafana", 3000)], SECRET.read_text(encoding="utf-8"))
if MYSQL_SECRET.is_file():
mysql_smoke()
print("Local stack, application probe and Grafana checks all passed.", flush=True)
elif args.action == "mysql-check":
mysql_smoke()
elif args.action == "down":
compose("down") # Deliberately preserves named volumes.
elif args.action == "logs":
compose("logs", "--tail", "60")
else:
compose("ps")
if __name__ == "__main__":
try:
main()
except (RuntimeError, subprocess.SubprocessError) as exc:
print(f"ERROR: {exc}", file=sys.stderr)
sys.exit(1)