homek8s/apps/base/osint/analyst-exporter.yaml
Lance Walters 2f613e4f11 fix(osint): run the PR #72 summarizer (fail-loudly + concurrent map phase)
The resilience fix sirius/osint-dashboard@fb5285d (PR #72) was merged but
never deployed: ns osint still ran the 11/19 image amd64-fe2b5df369d0, which
has neither the concurrent map phase nor NousAPIError, so a non-retryable
Nous rejection was swallowed as an empty completion and the analyst idled
for nine days without a single signal.

* pin deploy/osint-news-summarizer to the CI-built amd64-fb5285df7f38
  (build run 1497 / job 2165, manifest sha256:e2387f90...4de52)
* pin osint-analyst-exporter to the same tag — it borrows the summarizer
  image for python3 + psycopg2, and two tags for one image read as drift
* SUMMARY_MAP_CONCURRENCY=16 next to BATCH_SIZE: ~20 s per map call, the
  746-batch recap measured 951 s at 16 (8 projects to ~98 min)
* README: image inventory + a section on the new behaviour and log line
2026-12-05 00:29:11 -05:00

332 lines
11 KiB
YAML

# Freshness exporter for the osint analyst (card t_22334588).
#
# The summarizer (deploy/osint-news-summarizer) wrote no article_summaries rows
# from 2026-11-25 to 2026-12-04 while the scraper kept the articles table fresh
# (61.5k rows, newest within minutes). Nothing paged: the container was Running
# with restarts 0 and only INFO batch lines in the log, so "analyst wedged" and
# "analyst idle" looked identical from every signal the cluster had.
#
# The app has no /metrics endpoint (POST /metrics -> 404 on osint-app), so this
# is a tiny read-only exporter that answers the only question that matters:
# *when* did each side last write a row? It reads two timestamps from
# osint_data and serves them on :9187/metrics:
#
# osint_analyst_last_success_timestamp_seconds max(article_summaries.batch_timestamp)
# osint_ingest_last_article_timestamp_seconds max(articles.timestamp)
# osint_analyst_exporter_up 1 when the last DB read succeeded
#
# PromQL rules live in monitoring/controllers/home/osint-analyst.yaml
# (OsintAnalystStale, OsintIngestAliveButNoBrief).
#
# Why the summarizer image: it is the only image in this namespace that already
# ships psycopg2 and a python3, and it is pinned by tag (no floating base). The
# script uses the stdlib HTTP server, so nothing is installed at runtime and no
# new image build is needed. It tracks the summarizer's own pin (currently
# amd64-fb5285df7f38) — bump BOTH together; two different tags for one image in
# one namespace reads as drift in an audit, and the exporter only needs the
# interpreter + psycopg2, which every summarizer build carries.
---
apiVersion: v1
kind: ConfigMap
metadata:
name: osint-analyst-exporter
namespace: osint
data:
exporter.py: |
#!/usr/bin/env python3
"""Read-only freshness exporter for the osint analyst.
Serves /metrics on :9187. Two timestamps, nothing else:
osint_analyst_last_success_timestamp_seconds
epoch of max(article_summaries.batch_timestamp) -- when the analyst
last wrote a brief. 0 means the table is empty (stale by definition).
osint_ingest_last_article_timestamp_seconds
epoch of max(articles.timestamp) -- when the scraper last ingested.
osint_analyst_exporter_up
1 when the last database read succeeded, 0 otherwise.
On a database error the last good values are kept and `up` drops to 0, so
the timestamps keep ageing and a broken exporter escalates through the same
OsintAnalystStale alert instead of hiding behind missing series.
"""
import logging
import os
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import psycopg2
LOG = logging.getLogger("osint-analyst-exporter")
logging.basicConfig(
level=os.getenv("LOG_LEVEL", "INFO"),
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
PORT = int(os.getenv("EXPORTER_PORT", "9187"))
# One scrape interval (30 s) of cache: Prometheus + probes hitting the
# endpoint together must not each open a database connection.
CACHE_TTL = float(os.getenv("CACHE_TTL_SECONDS", "10"))
DB_CONFIG = {
"host": os.getenv("DB_HOST", "osint-db"),
"port": int(os.getenv("DB_PORT", "5432")),
"dbname": os.getenv("DB_NAME", "osint_data"),
"user": os.getenv("DB_USER", "osint"),
"password": os.getenv("DB_PASSWORD", ""),
"connect_timeout": 5,
}
ANALYST_SQL = (
"SELECT COALESCE(EXTRACT(EPOCH FROM max(batch_timestamp))::bigint, 0) "
"FROM article_summaries"
)
INGEST_SQL = (
"SELECT COALESCE(EXTRACT(EPOCH FROM max(timestamp))::bigint, 0) "
"FROM articles"
)
_lock = threading.Lock()
_state = {"analyst": 0, "ingest": 0, "up": 0, "last_attempt": 0.0}
def collect() -> tuple[int, int]:
conn = psycopg2.connect(**DB_CONFIG)
try:
conn.autocommit = True
with conn.cursor() as cur:
cur.execute("SET statement_timeout = 5000")
cur.execute(ANALYST_SQL)
analyst = int(cur.fetchone()[0] or 0)
cur.execute(INGEST_SQL)
ingest = int(cur.fetchone()[0] or 0)
finally:
conn.close()
return analyst, ingest
def ensure_fresh() -> None:
now = time.time()
with _lock:
if now - _state["last_attempt"] < CACHE_TTL:
return
_state["last_attempt"] = now
try:
analyst, ingest = collect()
except Exception as exc: # noqa: BLE001 - never kill the endpoint
with _lock:
_state["up"] = 0
LOG.warning("collect failed: %s", exc)
return
with _lock:
_state.update(analyst=analyst, ingest=ingest, up=1)
def render() -> str:
with _lock:
analyst = _state["analyst"]
ingest = _state["ingest"]
up = _state["up"]
return (
"# HELP osint_analyst_last_success_timestamp_seconds "
"Epoch of the newest article_summaries.batch_timestamp (last brief "
"written by the analyst); 0 = no row.\n"
"# TYPE osint_analyst_last_success_timestamp_seconds gauge\n"
f"osint_analyst_last_success_timestamp_seconds {analyst}\n"
"# HELP osint_ingest_last_article_timestamp_seconds "
"Epoch of the newest articles.timestamp (last row ingested by the "
"scraper); 0 = no row.\n"
"# TYPE osint_ingest_last_article_timestamp_seconds gauge\n"
f"osint_ingest_last_article_timestamp_seconds {ingest}\n"
"# HELP osint_analyst_exporter_up 1 when the last database read "
"succeeded.\n"
"# TYPE osint_analyst_exporter_up gauge\n"
f"osint_analyst_exporter_up {up}\n"
)
class Handler(BaseHTTPRequestHandler):
server_version = "osint-analyst-exporter/1.0"
def do_GET(self): # noqa: N802 - BaseHTTPRequestHandler API
path = self.path.split("?", 1)[0]
if path not in ("/metrics", "/healthz"):
self.send_error(404)
return
ensure_fresh()
body = render().encode()
self.send_response(200)
self.send_header("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, fmt, *args): # noqa: A003 - stdlib hook
LOG.debug("%s - %s", self.address_string(), fmt % args)
def main() -> None:
# Prime the cache so the first scrape has data, but never refuse to
# start on a database blip.
ensure_fresh()
server = ThreadingHTTPServer(("0.0.0.0", PORT), Handler)
LOG.info("listening on 0.0.0.0:%s (db=%s/%s)", PORT, DB_CONFIG["host"], DB_CONFIG["dbname"])
server.serve_forever()
if __name__ == "__main__":
main()
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: osint-analyst-exporter
namespace: osint
labels:
app: osint-analyst-exporter
spec:
replicas: 1
selector:
matchLabels:
app: osint-analyst-exporter
template:
metadata:
labels:
app: osint-analyst-exporter
spec:
imagePullSecrets:
- name: forgejo-pull
# Same placement policy as the other stateless amd64 loops here: prefer
# linode (where osint-db runs) but do not strand if it is absent.
nodeSelector:
kubernetes.io/arch: amd64
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: kubernetes.io/hostname
operator: In
values:
- linode
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: exporter
# Pinned summarizer image: python3 + psycopg2, see header comment.
# Kept equal to the summarizer pin in news-summarizer-deployment.yaml.
image: forgejo.siriusdevops.com/sirius/osint-news-summarizer:amd64-fb5285df7f38
imagePullPolicy: IfNotPresent
command: ["python", "/opt/exporter/exporter.py"]
env:
- name: PYTHONDONTWRITEBYTECODE
value: "1"
- name: EXPORTER_PORT
value: "9187"
- name: DB_HOST
valueFrom:
configMapKeyRef:
name: osint-env
key: DB_HOST
- name: DB_PORT
valueFrom:
configMapKeyRef:
name: osint-env
key: DB_PORT
- name: DB_NAME
valueFrom:
configMapKeyRef:
name: osint-env
key: DB_NAME
- name: DB_USER
valueFrom:
configMapKeyRef:
name: osint-env
key: DB_USER
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: osint-db
key: password
ports:
- name: metrics
containerPort: 9187
protocol: TCP
readinessProbe:
httpGet:
path: /healthz
port: metrics
periodSeconds: 10
livenessProbe:
httpGet:
path: /healthz
port: metrics
initialDelaySeconds: 10
periodSeconds: 30
resources:
requests:
cpu: 10m
memory: 64Mi
limits:
cpu: 100m
memory: 128Mi
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
volumeMounts:
- name: script
mountPath: /opt/exporter
readOnly: true
volumes:
- name: script
configMap:
name: osint-analyst-exporter
---
apiVersion: v1
kind: Service
metadata:
name: osint-analyst-exporter
namespace: osint
labels:
app: osint-analyst-exporter
spec:
type: ClusterIP
selector:
app: osint-analyst-exporter
ports:
- name: metrics
port: 9187
targetPort: metrics
protocol: TCP
---
# Prometheus (monitoring ns) scrapes this; the ServiceMonitor selector is
# namespace-wide (spec.serviceMonitorNamespaceSelector = {}), so the label is
# what matters. Ingress from monitoring to :9187 is opened in networkpolicy.yaml.
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: osint-analyst-exporter
namespace: osint
labels:
release: kube-prometheus-stack
spec:
namespaceSelector:
matchNames:
- osint
selector:
matchLabels:
app: osint-analyst-exporter
endpoints:
- port: metrics
path: /metrics
interval: 30s
scrapeTimeout: 10s