284 lines
12 KiB
Python
284 lines
12 KiB
Python
|
|
#!/usr/bin/env python3
|
||
|
|
"""make etat — l'etat des ecosystemes en une commande. N'ecrit rien.
|
||
|
|
|
||
|
|
Le premier geste d'une session, a la place de la lecture du CHANGELOG :
|
||
|
|
1. le poste : chaque depot, propre ou non, en avance ou en retard sur son amont ;
|
||
|
|
2. chaque site, et chaque locataire qu'il declare (`underlay.tenants`) : les depots du
|
||
|
|
runner face a sa forge et au poste, puis les sondes d'Icinga qui ne sont pas vertes,
|
||
|
|
lues dans le Redis d'IcingaDB de la machine de supervision.
|
||
|
|
|
||
|
|
Une vue sur l'existant (AGENTS.md section 12) : rien n'est calcule ici que les machines ne
|
||
|
|
sachent deja. Les ecosystemes sont interroges en parallele.
|
||
|
|
|
||
|
|
Usage :
|
||
|
|
python3 scripts/etat.py # tout
|
||
|
|
python3 scripts/etat.py --sans-fetch # le poste sans `git fetch` (amont tel que connu)
|
||
|
|
python3 scripts/etat.py --poste # le poste seul, sans rien joindre
|
||
|
|
"""
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import argparse
|
||
|
|
import json
|
||
|
|
import os
|
||
|
|
import subprocess
|
||
|
|
import sys
|
||
|
|
import time
|
||
|
|
from concurrent.futures import ThreadPoolExecutor
|
||
|
|
from dataclasses import dataclass, field
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
import yaml
|
||
|
|
|
||
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||
|
|
|
||
|
|
import reprise # noqa: E402
|
||
|
|
import voutes # noqa: E402
|
||
|
|
from inventory_rules import dossier_inventaire # noqa: E402
|
||
|
|
|
||
|
|
RACINE = Path(__file__).resolve().parent.parent
|
||
|
|
DEPOTS = RACINE.parent
|
||
|
|
SONDE = RACINE / "scripts" / "etat_sonde.sh"
|
||
|
|
ETATS_SERVICE = {0: "OK", 1: "WARNING", 2: "CRITICAL", 3: "UNKNOWN"}
|
||
|
|
ETATS_HOTE = {0: "UP", 1: "DOWN"}
|
||
|
|
# Une sonde passive qui n'a rien depose depuis ce delai apres l'echeance attendue : perimee.
|
||
|
|
GRACE_MS = 15 * 60 * 1000
|
||
|
|
|
||
|
|
|
||
|
|
# --- le poste -------------------------------------------------------------------------
|
||
|
|
|
||
|
|
def git(depot: Path, *args: str, timeout: int = 30) -> str:
|
||
|
|
r = subprocess.run(["git", "-C", str(depot), *args], capture_output=True, text=True,
|
||
|
|
timeout=timeout)
|
||
|
|
return r.stdout.strip() if r.returncode == 0 else ""
|
||
|
|
|
||
|
|
|
||
|
|
def sites() -> list[Path]:
|
||
|
|
return sorted(d for d in DEPOTS.iterdir() if (d / "underlay.yml").is_file()
|
||
|
|
and d.name.startswith("SITE-"))
|
||
|
|
|
||
|
|
|
||
|
|
def tenants_du_site(site: Path) -> dict[str, int]:
|
||
|
|
u = yaml.safe_load((site / "underlay.yml").read_text()) or {}
|
||
|
|
return dict((u.get("underlay") or {}).get("tenants") or {})
|
||
|
|
|
||
|
|
|
||
|
|
def copie_du_locataire(site: Path, tenant: str) -> tuple[Path, str]:
|
||
|
|
"""La copie qui decrit ce locataire A CE SITE : sa relève, sinon sa production."""
|
||
|
|
rel = reprise.copie(site.name, tenant)
|
||
|
|
if (rel / "inventories").is_dir():
|
||
|
|
return rel, "releve"
|
||
|
|
return DEPOTS / tenant, "production"
|
||
|
|
|
||
|
|
|
||
|
|
def depots_du_poste() -> list[Path]:
|
||
|
|
noms = {RACINE.name, "Set-OPS-Modeles"}
|
||
|
|
for s in sites():
|
||
|
|
noms.add(s.name)
|
||
|
|
noms.update(tenants_du_site(s))
|
||
|
|
out = [DEPOTS / n for n in sorted(noms) if (DEPOTS / n / ".git").exists()]
|
||
|
|
if reprise.DOSSIER_REPRISES.is_dir():
|
||
|
|
out += sorted(p for p in reprise.DOSSIER_REPRISES.glob("*/*") if (p / ".git").exists())
|
||
|
|
return out
|
||
|
|
|
||
|
|
|
||
|
|
def ligne_depot(d: Path, fetch: bool) -> str:
|
||
|
|
nom = str(d.relative_to(DEPOTS))
|
||
|
|
if fetch and git(d, "rev-parse", "--abbrev-ref", "@{u}"):
|
||
|
|
git(d, "fetch", "--quiet", timeout=30)
|
||
|
|
tete = git(d, "rev-parse", "--short=7", "HEAD")
|
||
|
|
branche = git(d, "rev-parse", "--abbrev-ref", "HEAD")
|
||
|
|
modifs = [l for l in git(d, "status", "--porcelain", "--untracked-files=no").splitlines() if l]
|
||
|
|
notes = []
|
||
|
|
compte = git(d, "rev-list", "--left-right", "--count", "@{u}...HEAD")
|
||
|
|
if compte:
|
||
|
|
retard, avance = (int(x) for x in compte.split())
|
||
|
|
if avance:
|
||
|
|
notes.append(f"{avance} commit(s) non pousse(s)")
|
||
|
|
if retard:
|
||
|
|
notes.append(f"{retard} commit(s) a tirer")
|
||
|
|
elif branche != "HEAD":
|
||
|
|
notes.append("sans amont")
|
||
|
|
if modifs:
|
||
|
|
notes.append(f"{len(modifs)} fichier(s) modifie(s)")
|
||
|
|
marque = "!" if notes and notes != ["sans amont"] else " "
|
||
|
|
return f" {marque} {nom:<42} {branche[:12]:<12} {tete} {', '.join(notes) or 'a jour'}"
|
||
|
|
|
||
|
|
|
||
|
|
# --- les ecosystemes ------------------------------------------------------------------
|
||
|
|
|
||
|
|
@dataclass
|
||
|
|
class Ecosysteme:
|
||
|
|
titre: str
|
||
|
|
inventaire: str
|
||
|
|
env: dict
|
||
|
|
motif: str
|
||
|
|
reponses: dict = field(default_factory=dict)
|
||
|
|
erreur: str = ""
|
||
|
|
|
||
|
|
|
||
|
|
def ecosystemes() -> list[Ecosysteme]:
|
||
|
|
ident = voutes.identites()
|
||
|
|
base = dict(os.environ, ANSIBLE_LOAD_CALLBACK_PLUGINS="1", ANSIBLE_STDOUT_CALLBACK="json",
|
||
|
|
ANSIBLE_DEPRECATION_WARNINGS="False")
|
||
|
|
if ident:
|
||
|
|
base["ANSIBLE_VAULT_IDENTITY_LIST"] = ident
|
||
|
|
out = []
|
||
|
|
for s in sites():
|
||
|
|
env = dict(base, SETOPS_UNDERLAY=str(s / "underlay.yml"))
|
||
|
|
env.pop("ANSIBLE_PRIVATE_KEY_FILE", None) # le site pose sa cle par son inventaire
|
||
|
|
out.append(Ecosysteme(s.name, str(RACINE / "scripts" / "site_inventaire.py"), env,
|
||
|
|
"serveur_ops_site:serveur_icinga"))
|
||
|
|
for tenant, index in sorted(tenants_du_site(s).items(), key=lambda kv: kv[1]):
|
||
|
|
copie, nature = copie_du_locataire(s, tenant)
|
||
|
|
env = dict(base, SETOPS_INSTANCE=str(copie))
|
||
|
|
cle = subprocess.run([sys.executable, str(RACINE / "scripts" / "cle_ssh.py")],
|
||
|
|
capture_output=True, text=True, env=env).stdout.strip()
|
||
|
|
if cle:
|
||
|
|
env["ANSIBLE_PRIVATE_KEY_FILE"] = cle
|
||
|
|
inv = dossier_inventaire(copie) / "hosts.yml"
|
||
|
|
out.append(Ecosysteme(f"{tenant} — {nature} au {s.name} (index {index})", str(inv),
|
||
|
|
env, "serveur_ops:serveur_icinga"))
|
||
|
|
return out
|
||
|
|
|
||
|
|
|
||
|
|
def interroger(e: Ecosysteme) -> Ecosysteme:
|
||
|
|
if not Path(e.inventaire).is_file():
|
||
|
|
e.erreur = f"inventaire absent : {e.inventaire} (make instancier ?)"
|
||
|
|
return e
|
||
|
|
cmd = ["ansible", "-i", e.inventaire, e.motif, "-b", "-m", "ansible.builtin.script",
|
||
|
|
"-a", str(SONDE.relative_to(RACINE))] # le poste a une espace dans son chemin
|
||
|
|
try:
|
||
|
|
r = subprocess.run(cmd, capture_output=True, text=True, env=e.env, cwd=RACINE,
|
||
|
|
timeout=240)
|
||
|
|
except subprocess.TimeoutExpired:
|
||
|
|
e.erreur = "aucune reponse en 240 s"
|
||
|
|
return e
|
||
|
|
try:
|
||
|
|
debut = r.stdout.index("{")
|
||
|
|
doc = json.loads(r.stdout[debut:])
|
||
|
|
except ValueError:
|
||
|
|
e.erreur = (r.stderr.strip().splitlines() or ["sortie illisible"])[-1][:200]
|
||
|
|
return e
|
||
|
|
for play in doc.get("plays", []):
|
||
|
|
for tache in play.get("tasks", []):
|
||
|
|
for hote, res in tache.get("hosts", {}).items():
|
||
|
|
if res.get("unreachable") or res.get("failed"):
|
||
|
|
e.reponses[hote] = {"injoignable": res.get("msg", "")[:160]}
|
||
|
|
else:
|
||
|
|
e.reponses[hote] = {"stdout": res.get("stdout", "")}
|
||
|
|
if not e.reponses:
|
||
|
|
e.erreur = "aucune machine visee (groupes absents de l'inventaire ?)"
|
||
|
|
return e
|
||
|
|
|
||
|
|
|
||
|
|
def lire_sonde(stdout: str) -> tuple[list[tuple[str, str, str]], dict[str, dict]]:
|
||
|
|
"""(depots du runner, tables Redis d'IcingaDB) a partir de la sortie de la sonde."""
|
||
|
|
depots, redis, cle, valeurs = [], {}, None, []
|
||
|
|
for l in stdout.replace("\r", "").splitlines():
|
||
|
|
if l.startswith("DEPOT\t"):
|
||
|
|
_, nom, local, forge = (l.split("\t") + ["", "", ""])[:4]
|
||
|
|
depots.append((nom, local, forge))
|
||
|
|
elif l.startswith("REDIS\t"):
|
||
|
|
cle, valeurs = l.split("\t", 1)[1], []
|
||
|
|
redis[cle] = valeurs
|
||
|
|
elif cle is not None and l:
|
||
|
|
valeurs.append(l)
|
||
|
|
tables = {}
|
||
|
|
for k, v in redis.items():
|
||
|
|
tables[k] = {}
|
||
|
|
for i in range(0, len(v) - 1, 2):
|
||
|
|
try:
|
||
|
|
tables[k][v[i]] = json.loads(v[i + 1])
|
||
|
|
except ValueError:
|
||
|
|
pass
|
||
|
|
return depots, tables
|
||
|
|
|
||
|
|
|
||
|
|
def problemes(tables: dict[str, dict], maintenant_ms: int) -> tuple[int, list[str]]:
|
||
|
|
"""(nombre de sondes, lignes des sondes et machines qui ne sont pas vertes)."""
|
||
|
|
hotes = {i: h.get("name", "?") for i, h in tables.get("host", {}).items()}
|
||
|
|
services = tables.get("service", {})
|
||
|
|
out = []
|
||
|
|
for i, st in sorted(tables.get("host:state", {}).items(), key=lambda kv: hotes.get(kv[0], "")):
|
||
|
|
if st.get("hard_state", 0) != 0:
|
||
|
|
out.append(f" ✗ {hotes.get(i, '?')} — machine {ETATS_HOTE.get(st['hard_state'], '?')}")
|
||
|
|
lignes = []
|
||
|
|
for i, st in tables.get("service:state", {}).items():
|
||
|
|
svc = services.get(i, {})
|
||
|
|
nom = f"{hotes.get(svc.get('host_id'), '?')} / {svc.get('name', '?')}"
|
||
|
|
etat = st.get("hard_state", 0)
|
||
|
|
perimee = st.get("next_update") and st["next_update"] + GRACE_MS < maintenant_ms
|
||
|
|
if etat == 0 and not perimee:
|
||
|
|
continue
|
||
|
|
sortie = (st.get("output") or "").splitlines()
|
||
|
|
sortie = sortie[0][:100] if sortie else ""
|
||
|
|
drap = []
|
||
|
|
if st.get("is_acknowledged"):
|
||
|
|
drap.append("acquittee")
|
||
|
|
if st.get("in_downtime"):
|
||
|
|
drap.append("en maintenance")
|
||
|
|
if perimee:
|
||
|
|
drap.append("aucun resultat recent")
|
||
|
|
libelle = ETATS_SERVICE.get(etat, "?")
|
||
|
|
lignes.append(f" ✗ {nom} — {libelle}{' (' + ', '.join(drap) + ')' if drap else ''}"
|
||
|
|
f"{' : ' + sortie if sortie else ''}")
|
||
|
|
return len(tables.get("service:state", {})), out + sorted(lignes)
|
||
|
|
|
||
|
|
|
||
|
|
def rapport(e: Ecosysteme) -> list[str]:
|
||
|
|
out = [f"\n== {e.titre}"]
|
||
|
|
if e.erreur:
|
||
|
|
return out + [f" ? {e.erreur}"]
|
||
|
|
maintenant = int(time.time() * 1000)
|
||
|
|
for hote, rep in sorted(e.reponses.items()):
|
||
|
|
if "injoignable" in rep:
|
||
|
|
out.append(f" ? {hote} : la sonde n'a pas abouti : {rep['injoignable']}")
|
||
|
|
continue
|
||
|
|
depots, tables = lire_sonde(rep["stdout"])
|
||
|
|
if not depots and not tables:
|
||
|
|
out.append(f" ? {hote} : la sonde n'a rien rendu")
|
||
|
|
for nom, local, forge in depots:
|
||
|
|
poste = git(DEPOTS / nom, "rev-parse", "--short=7", "HEAD") if (DEPOTS / nom / ".git").exists() else ""
|
||
|
|
notes = []
|
||
|
|
if forge in ("", "?"):
|
||
|
|
notes.append("forge muette")
|
||
|
|
elif local != forge:
|
||
|
|
notes.append("runner en retard sur sa forge")
|
||
|
|
if poste and forge not in ("", "?") and poste != forge:
|
||
|
|
notes.append(f"forge ≠ poste ({poste})")
|
||
|
|
marque = "!" if notes else " "
|
||
|
|
out.append(f" {marque} {hote} : {nom:<26} runner {local} forge {forge or '?'}"
|
||
|
|
f" {', '.join(notes) or 'a jour'}")
|
||
|
|
if tables:
|
||
|
|
total, pbs = problemes(tables, maintenant)
|
||
|
|
vertes = total - sum(1 for p in pbs if " / " in p)
|
||
|
|
out.append(f" Icinga ({hote}) : {total} sondes, {vertes} vertes"
|
||
|
|
f"{', ' + str(len(pbs)) + ' a voir' if pbs else ''}")
|
||
|
|
out += pbs
|
||
|
|
return out
|
||
|
|
|
||
|
|
|
||
|
|
def main(argv: list[str] | None = None) -> int:
|
||
|
|
p = argparse.ArgumentParser(description="L'etat des ecosystemes, sans rien ecrire.")
|
||
|
|
p.add_argument("--sans-fetch", action="store_true", help="ne pas interroger les amonts")
|
||
|
|
p.add_argument("--poste", action="store_true", help="le poste seul")
|
||
|
|
a = p.parse_args(argv)
|
||
|
|
|
||
|
|
eco = [] if a.poste else ecosystemes()
|
||
|
|
with ThreadPoolExecutor(max_workers=8) as pool:
|
||
|
|
futurs = [pool.submit(interroger, e) for e in eco]
|
||
|
|
lignes = ["== Le poste"] + [ligne_depot(d, fetch=not a.sans_fetch)
|
||
|
|
for d in depots_du_poste()]
|
||
|
|
print("\n".join(lignes))
|
||
|
|
for f in futurs:
|
||
|
|
r = rapport(f.result())
|
||
|
|
lignes += r
|
||
|
|
print("\n".join(r))
|
||
|
|
a_voir = sum(1 for l in lignes if l[:4].strip()[:1] in ("!", "✗", "?"))
|
||
|
|
print(f"\n{a_voir} point(s) a voir." if a_voir else "\nRien a signaler.")
|
||
|
|
return 0
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
sys.exit(main())
|