Ordonnanceur commun
Tick toutes les 5 min : ROMMA puis Infoclimat (chaque source decide), purge 14 jours, publication. Une source en erreur n empeche pas l autre. Test de journee simulee : environ 144 requetes Infoclimat au lieu de 288. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cette révision appartient à :
1 Parent
b3c8d0a929
révision
d40d44f4ea
2 fichiers modifiés
+152
Aucun fichier ne correspond à votre recherche
@@ -0,0 +1,66 @@
|
||||
"""Ordonnanceur : lancé par le minuteur systemd toutes les 5 min (hh:x4 et hh:x9).
|
||||
|
||||
Chaque source décide seule si elle appelle :
|
||||
* ROMMA : au plus une requête global=1 toutes les 10 min ;
|
||||
* Infoclimat : passage principal à hh:x4 si une station est due, rattrapage ciblé à hh:x9.
|
||||
Puis publication des fichiers statiques et purge de la base (14 jours). Une source en erreur n'empêche
|
||||
ni l'autre source ni la publication.
|
||||
|
||||
python3 -m meteo_collecte.ordonnanceur # un tick
|
||||
python3 -m meteo_collecte.ordonnanceur --publier # republie sans aucun appel réseau
|
||||
python3 -m meteo_collecte.ordonnanceur --config # affiche la configuration (sans secret)
|
||||
"""
|
||||
import datetime as dt
|
||||
import sys
|
||||
|
||||
from . import infoclimat, publier, romma
|
||||
from .commun import UTC, Config, Journal, Verrou, lire_json
|
||||
from .stockage import Stockage
|
||||
|
||||
|
||||
def tick(cfg, maintenant=None, fetch_infoclimat=infoclimat.telecharger, fetch_romma=romma.telecharger,
|
||||
appels=True):
|
||||
maintenant = maintenant or dt.datetime.now(UTC)
|
||||
var = cfg.base / "var"
|
||||
journal = Journal(var / "collecte.log")
|
||||
with Verrou(var / ".collecte.lock") as obtenu:
|
||||
if not obtenu:
|
||||
return {"action": "verrou"} # un tick précédent tourne encore
|
||||
stockage = Stockage(var / "mesures.sqlite")
|
||||
resumes = {}
|
||||
try:
|
||||
if appels and cfg.romma_actif:
|
||||
resumes["romma"] = _sans_planter(journal, maintenant, "romma",
|
||||
lambda: romma.passer(cfg, stockage, journal, maintenant, fetch_romma))
|
||||
if appels and cfg.infoclimat_actif:
|
||||
stations = lire_json(cfg.stations, {}).get("infoclimat", {})
|
||||
resumes["infoclimat"] = _sans_planter(journal, maintenant, "infoclimat", lambda: infoclimat.passer(
|
||||
cfg, stockage, journal, maintenant, stations, fetch=fetch_infoclimat))
|
||||
stockage.purger(maintenant, cfg.garder_jours)
|
||||
resumes["publiees"] = publier.publier(cfg, stockage, maintenant, resumes)
|
||||
finally:
|
||||
stockage.fermer()
|
||||
return resumes
|
||||
|
||||
|
||||
def _sans_planter(journal, maintenant, nom, f):
|
||||
try:
|
||||
return f()
|
||||
except Exception as e: # bug local (disque, base…) : journalisé, la suite du tick continue
|
||||
journal("ERREUR interne %s : %s" % (nom, str(e)[:300]), maintenant)
|
||||
return {"source": nom, "action": "erreur_interne"}
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
argv = sys.argv[1:] if argv is None else argv
|
||||
cfg = Config.depuis_env()
|
||||
if "--config" in argv:
|
||||
for k, v in vars(cfg).items():
|
||||
print("%-20s %s" % (k, v)) # chemins seulement, jamais le contenu des secrets
|
||||
return 0
|
||||
tick(cfg, appels="--publier" not in argv)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,86 @@
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from meteo_collecte import ordonnanceur
|
||||
from meteo_collecte.commun import lire_json
|
||||
from tests.aide import FauxReseau, config, fixture, t
|
||||
|
||||
|
||||
class TestTick(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.cfg, _ = config(self.tmp.name)
|
||||
st = Path(self.tmp.name) / "stations.json"
|
||||
st.write_text(json.dumps({"infoclimat": {"000T0": {"nom": "Lans"}, "000IL": {"nom": "Autrans"}}}))
|
||||
self.cfg.stations = st
|
||||
# Garde-fou : tout appel réseau réel ferait échouer le test.
|
||||
p = mock.patch.object(urllib.request, "urlopen", side_effect=AssertionError("appel réseau interdit"))
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_tick_complet(self):
|
||||
ric, rro = FauxReseau(fixture("infoclimat_ok.json")), FauxReseau(fixture("romma_live.json"))
|
||||
r = ordonnanceur.tick(self.cfg, t(11, 54), ric, rro)
|
||||
self.assertEqual((r["infoclimat"]["action"], r["romma"]["action"]), ("appel", "appel"))
|
||||
self.assertEqual(r["publiees"], 6) # 2 Infoclimat + 4 ROMMA
|
||||
idx = lire_json(self.cfg.public / "data" / "stations.json", {})
|
||||
self.assertEqual({s["source"] for s in idx["stations"]}, {"infoclimat", "romma"})
|
||||
|
||||
def test_une_source_en_erreur_n_empeche_pas_l_autre(self):
|
||||
ric, rro = FauxReseau(fixture("infoclimat_ok.json")), FauxReseau(OSError("panne"))
|
||||
r = ordonnanceur.tick(self.cfg, t(11, 54), ric, rro)
|
||||
self.assertEqual((r["infoclimat"]["action"], r["romma"]["action"]), ("appel", "erreur"))
|
||||
etat = lire_json(self.cfg.public / "data" / "etat.json", {})
|
||||
self.assertTrue(etat["sources"]["romma"]["en_pause"])
|
||||
|
||||
def test_bug_local_journalise(self):
|
||||
def casse(url):
|
||||
raise RuntimeError("bug")
|
||||
with mock.patch("meteo_collecte.infoclimat.passer", side_effect=RuntimeError("disque plein")):
|
||||
r = ordonnanceur.tick(self.cfg, t(11, 54), casse, FauxReseau(fixture("romma_live.json")))
|
||||
self.assertEqual(r["infoclimat"]["action"], "erreur_interne")
|
||||
self.assertIn("publiees", r)
|
||||
|
||||
def test_publier_sans_appel(self):
|
||||
ric, rro = FauxReseau(b""), FauxReseau(b"")
|
||||
ordonnanceur.tick(self.cfg, t(11, 54), ric, rro, appels=False)
|
||||
self.assertEqual((ric.urls, rro.urls), ([], []))
|
||||
self.assertTrue((self.cfg.public / "data" / "etat.json").exists())
|
||||
|
||||
def test_journee_simulee_economie(self):
|
||||
"""24 h de ticks toutes les 5 min avec un faux serveur qui publie à 10 min : ~144 requêtes, pas 288."""
|
||||
import datetime as dt
|
||||
from meteo_collecte.commun import fmt_utc
|
||||
|
||||
class Serveur:
|
||||
def __init__(s):
|
||||
s.n = 0
|
||||
s.maintenant = None
|
||||
|
||||
def __call__(s, url):
|
||||
s.n += 1
|
||||
fin = s.maintenant - dt.timedelta(minutes=2)
|
||||
dh = fin.replace(minute=fin.minute - fin.minute % 10, second=0)
|
||||
lignes = [{"dh_utc": fmt_utc(dh - dt.timedelta(minutes=10 * i)), "temperature": "5"} for i in range(3)]
|
||||
return json.dumps({"status": "OK", "hourly": {"000T0": lignes, "000IL": lignes}}).encode()
|
||||
|
||||
srv = Serveur()
|
||||
debut = t(0, 4)
|
||||
for i in range(288):
|
||||
srv.maintenant = debut + dt.timedelta(minutes=5 * i)
|
||||
ordonnanceur.tick(self.cfg, srv.maintenant, srv, FauxReseau(fixture("romma_live.json")))
|
||||
print("
|
||||
[simulation 24 h] requetes Infoclimat :", srv.n)
|
||||
self.assertLessEqual(srv.n, 150)
|
||||
self.assertGreaterEqual(srv.n, 140)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Référencer dans un nouveau ticket
Bloquer un utilisateur