mirror of
https://gitlab.sarex.io/infra/terraform-contour-mirror.git
synced 2026-08-05 18:31:00 +03:00
79 lines
2.7 KiB
Python
79 lines
2.7 KiB
Python
"""Secrets-contract acceptance probe.
|
|
|
|
Connects to RabbitMQ using credentials read from a Kubernetes Secret produced
|
|
by the v2 secrets contract (schema=rabbitmq.v1) and, every PROBE_INTERVAL_SECONDS,
|
|
publishes a message to PROBE_QUEUE and immediately consumes it back. Success
|
|
or failure is logged; message bodies never contain secret values.
|
|
"""
|
|
import json
|
|
import logging
|
|
import os
|
|
import time
|
|
|
|
import pika
|
|
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
|
log = logging.getLogger("secrets-contract-probe")
|
|
|
|
QUEUE = os.environ.get("PROBE_QUEUE", "test-terraform-probe")
|
|
INTERVAL = int(os.environ.get("PROBE_INTERVAL_SECONDS", "15"))
|
|
|
|
|
|
def env(name: str) -> str:
|
|
value = os.environ.get(name, "")
|
|
if not value:
|
|
raise RuntimeError(f"missing required env var {name}")
|
|
return value
|
|
|
|
|
|
def connect() -> pika.BlockingConnection:
|
|
params = pika.ConnectionParameters(
|
|
host=env("RABBITMQ_HOST"),
|
|
port=int(env("RABBITMQ_PORT")),
|
|
virtual_host=env("RABBITMQ_VHOST"),
|
|
credentials=pika.PlainCredentials(env("RABBITMQ_USERNAME"), env("RABBITMQ_PASSWORD")),
|
|
heartbeat=30,
|
|
blocked_connection_timeout=10,
|
|
)
|
|
return pika.BlockingConnection(params)
|
|
|
|
|
|
def main() -> None:
|
|
log.info("starting probe: host=%s vhost=%s queue=%s interval=%ss",
|
|
os.environ.get("RABBITMQ_HOST"), os.environ.get("RABBITMQ_VHOST"), QUEUE, INTERVAL)
|
|
|
|
conn = connect()
|
|
channel = conn.channel()
|
|
channel.queue_declare(queue=QUEUE, durable=True)
|
|
log.info("connected to rabbitmq, entering probe loop")
|
|
|
|
seq = 0
|
|
while True:
|
|
seq += 1
|
|
try:
|
|
payload = json.dumps({"seq": seq, "ts": time.time()})
|
|
channel.basic_publish(exchange="", routing_key=QUEUE, body=payload)
|
|
log.info("published probe seq=%d", seq)
|
|
|
|
method, _props, _body = channel.basic_get(queue=QUEUE, auto_ack=False)
|
|
if method is None:
|
|
log.error("probe seq=%d FAILED: nothing to consume right after publish", seq)
|
|
else:
|
|
channel.basic_ack(method.delivery_tag)
|
|
log.info("consumed+acked probe seq=%d OK", seq)
|
|
except Exception: # noqa: BLE001 - keep the loop alive, log and retry
|
|
log.exception("probe seq=%d FAILED", seq)
|
|
try:
|
|
conn = connect()
|
|
channel = conn.channel()
|
|
channel.queue_declare(queue=QUEUE, durable=True)
|
|
log.info("reconnected to rabbitmq")
|
|
except Exception: # noqa: BLE001
|
|
log.exception("reconnect failed, will retry next cycle")
|
|
|
|
time.sleep(INTERVAL)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|