75 lines
4.0 KiB
Python
75 lines
4.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Оператор: ротация/отзыв leaf-сертификатов локального PKI БЕЗ пересборки образов.
|
|
|
|
python3 scripts/rotate_cert.py lb # новый ключ+сертификат LB, старый — в CRL, seamless reload
|
|
python3 scripts/rotate_cert.py worker --restart # клиентские identity: + поочерёдный рестарт реплик
|
|
python3 scripts/rotate_cert.py --revoke <serial|identity> # только отзыв (компрометация)
|
|
python3 scripts/rotate_cert.py --renew 7 # перевыпуск всех, у кого осталось < 7 дней, + reload
|
|
|
|
Что происходит: pki (одноразовый контейнер, CA-ключ доступен только ему) выпускает новый ключ/сертификат в
|
|
secrets/tls/<id>/ и вносит старые серийные номера в CRL (secrets/tls/trust/crl.pem), пересчитывает
|
|
pinned_certs NATS. Затем потребители перечитывают: HAProxy (LB и шлюзы) — SIGUSR2 (без обрыва, новые
|
|
соединения — новый сертификат/CRL), NATS — SIGHUP (соединения с неразрешённым сертификатом закрываются),
|
|
PostgreSQL — pg_reload_conf, OpenBao — SIGHUP; реплики API сами перечитывают сертификат и CRL каждые 2 с
|
|
и закрывают живые соединения с отозванным сертификатом. --restart нужен для клиентских сертификатов
|
|
приложения (они читаются при установлении соединения с зависимостями).
|
|
"""
|
|
import argparse
|
|
import os
|
|
import json
|
|
import time
|
|
|
|
from opslib import dc, now, out, reload_trust
|
|
|
|
RESTARTABLE = {"api": ["api"], "worker": ["worker"], "otel-collector": ["otel-collector"], "grafana": ["grafana"],
|
|
"prometheus": ["prometheus"], "tempo": ["tempo"], "redis": ["redis"]}
|
|
|
|
|
|
def pki(*args):
|
|
owner = ["-e", "PKI_OWNER=%d:%d" % (os.getuid(), os.getgid())] if hasattr(os, "getuid") else []
|
|
r = dc("--profile", "tools", "run", "--rm", "--no-deps", "-T", *owner, "pki", *args)
|
|
return json.loads(r.stdout)
|
|
|
|
|
|
def rolling_restart(service):
|
|
ids = [x for x in dc("ps", "-q", service).stdout.split() if x]
|
|
for cid in ids: # по одной реплике: остальные обслуживают трафик
|
|
import subprocess
|
|
subprocess.run(["docker", "restart", "-t", "15", cid], check=True, capture_output=True)
|
|
deadline = time.time() + 120
|
|
while time.time() < deadline:
|
|
st = subprocess.run(["docker", "inspect", "-f", "{{if .State.Health}}{{.State.Health.Status}}{{else}}"
|
|
"{{.State.Status}}{{end}}", cid], capture_output=True, text=True).stdout.strip()
|
|
if st in ("healthy", "running"):
|
|
break
|
|
time.sleep(1)
|
|
return len(ids)
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
ap.add_argument("identity", nargs="?")
|
|
ap.add_argument("--restart", action="store_true")
|
|
ap.add_argument("--revoke")
|
|
ap.add_argument("--renew", type=float)
|
|
a = ap.parse_args()
|
|
t0 = time.monotonic()
|
|
res = {"at": now()}
|
|
if a.revoke:
|
|
res["pki"] = pki("revoke", a.revoke)
|
|
elif a.renew is not None:
|
|
res["pki"] = pki("renew", "--within-days", str(a.renew))
|
|
elif a.identity:
|
|
res["pki"] = pki("rotate", a.identity)
|
|
else:
|
|
ap.error("identity, --revoke or --renew required")
|
|
res["reloaded"] = reload_trust()
|
|
if a.restart and a.identity in RESTARTABLE:
|
|
res["restarted"] = {s: rolling_restart(s) for s in RESTARTABLE[a.identity]}
|
|
res["total_s"] = round(time.monotonic() - t0, 1)
|
|
out(res)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|