Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

1.7 KB
Raw Blame
#!/usr/bin/env python3
import os
import sys
import logging
from collections.abc import Callable
from urllib.request import ProxyHandler, Request, build_opener

from prometheus_client import CollectorRegistry, Gauge, push_to_gateway


def _direct_handler(
    url: str, method: str, timeout: float | None, headers: list[tuple[str, str]], data: bytes
) -> Callable[[], None]:
    def send() -> None:
        request = Request(url, data=data, method=method)
        for name, value in headers:
            request.add_header(name, value)
        # Only this Pushgateway request bypasses the egress proxy.
        with build_opener(ProxyHandler({})).open(request, timeout=timeout):
            pass

    return send


def main() -> None:
    address = os.environ.get("PROM_PUSHGATEWAY_ADDRESS")
    job_name = os.environ.get("MIGRATION_JOB_NAME")
    namespace = os.environ.get("MIGRATION_NAMESPACE")
    if not address or not job_name or not namespace:
        return

    phase = sys.argv[1]
    registry = CollectorRegistry()
    outcome = Gauge(
        "django_migration_outcome",
        "Latest migration job outcome (1 = failed)",
        ["phase", "job_name", "namespace"],
        registry=registry,
    )
    outcome.labels(phase=phase, job_name=job_name, namespace=namespace).set(int(phase != "none"))

    try:
        push_to_gateway(
            address,
            job="django_migrate_outcome",
            grouping_key={"instance": "posthog"},
            registry=registry,
            timeout=5,
            handler=_direct_handler,
        )
    except Exception as exc:
        logging.exception("Failed to push migration outcome: %s", exc)


if __name__ == "__main__":
    main()