diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c96f71..9237239 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,18 @@ le projet suit SemVer. ## [Non publié] +### Évolutions + +- `DnsFilter.apply` devient asynchrone (issue #35, chantier full async #1) : + la résolution réseau passe par `dns.asyncresolver` (vraie concurrence + réseau) ; caches, délais, essais et `PYSTASHTEMPLATE_DNS=off` + inchangés. La chaîne `filter{}` de l'interpréteur (`_run_filter_body`, + `_run_filter_plugin`, `_apply_dns`) attend désormais les filtres + asynchrones ; `FilterPipeline` (JSON) reste à convertir (#36). Changement + d'API pour les appelants directs de `DnsFilter.apply` : `await` requis. + +## [0.2.0] - 2026-11-03 + ### Ajouté - Client commun « API _bulk Elasticsearch » (issue #11, chantier @@ -31,8 +43,6 @@ le projet suit SemVer. (`src/pystashtemplate/**/*.py`) ; `test_no_cross_imports` et `test_packaging` étendus en conséquence (le graphe couvre `outputs/`, `dlq` est un module du socle, plus du connecteur). -### Évolutions - - `PipelineInterpreter.apply` et `apply_events` deviennent asynchrones (`async def`, chantier full async #1, issue #34) : sémantique inchangée, mais **changement d'API** — l'appelant doit désormais @@ -46,6 +56,16 @@ le projet suit SemVer. - Socle des sorties agnostiques (`outputs.base`, issue #4) : interface `Output`, capacités déclarées, registre `REGISTRY`, sortie factice `null`. +- Lots et contre-pression (`outputs.lotisseur`, issue #6) : `Lotisseur` + tamporise les documents vers une sortie (taille de lot, délai, + réveil immédiat à l'arrêt — arrêt propre, rien de perdu). + +### Corrigé + +- Sortie `_bulk` : contexte TLS explicite (autorités + paire client) — + httpx avec `verify=` ET `cert=` ne présentait PAS le + certificat client (mTLS refusé par un serveur exigeant, constaté au + banc de conformité RsysLogstach #160). ## [0.1.0] - 2026-11-03 diff --git a/pyproject.toml b/pyproject.toml index 3aec2be..41dea44 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "pystashtemplate" -version = "0.1.0" +version = "0.2.0" description = "Sémantique Logstash partagée : gabarits, filtres, interprétation des .conf (extrait de RsysLogstach, #111)" license = "GPL-3.0-or-later" requires-python = ">=3.11" diff --git a/src/pystashtemplate/dnslookup.py b/src/pystashtemplate/dnslookup.py index 1f5eb73..57ede49 100644 --- a/src/pystashtemplate/dnslookup.py +++ b/src/pystashtemplate/dnslookup.py @@ -36,9 +36,10 @@ import os import time from collections import OrderedDict -from collections.abc import Callable, Iterable, Iterator +from collections.abc import Callable from typing import Any, Protocol +import dns.asyncresolver import dns.exception import dns.name import dns.resolver @@ -60,12 +61,17 @@ class DelaiDepasse(Exception): class Resolveur(Protocol): - """Source de résolution : fichier hosts ou serveur DNS.""" + """Source de résolution : fichier hosts ou serveur DNS. - def adresses(self, nom: str) -> Iterable[str]: + Asynchrone depuis #35 (chantier full async #1) : `dns.asyncresolver` + fournit la vraie concurrence réseau côté serveurs DNS ; les fichiers + hosts (lectures locales rapides) portent la même interface. + """ + + async def adresses(self, nom: str) -> list[str]: """Adresses du nom, dans l'ordre.""" - def noms(self, adresse: str) -> Iterable[str]: + async def noms(self, adresse: str) -> list[str]: """Noms de l'adresse, dans l'ordre.""" @@ -137,12 +143,12 @@ def _charger(self) -> dict[str, list[str]]: return self._noms_vers_adresses @traced - def adresses(self, nom: str) -> list[str]: + async def adresses(self, nom: str) -> list[str]: """Adresses de `nom` dans l'ordre du fichier.""" return list(self._charger().get(nom, [])) @traced - def noms(self, adresse: str) -> list[str]: + async def noms(self, adresse: str) -> list[str]: """Noms de `adresse` (nom canonique d'abord).""" self._charger() return list(self._adresses_vers_noms.get(_normaliser_adresse(adresse), [])) @@ -162,16 +168,16 @@ def __init__(self, timeout: float, serveurs: dict[str, Any] | None = None) -> No """ self._serveurs = serveurs self._timeout = timeout - self._resolveur: dns.resolver.Resolver | None = None + self._resolveur: dns.asyncresolver.Resolver | None = None @traced - def _client(self) -> dns.resolver.Resolver: - """Résolveur dnspython, construit au premier usage.""" + def _client(self) -> dns.asyncresolver.Resolver: + """Résolveur dnspython asynchrone, construit au premier usage.""" if self._resolveur is None: if self._serveurs is None: - resolveur = dns.resolver.Resolver(configure=True) + resolveur = dns.asyncresolver.Resolver(configure=True) else: - resolveur = dns.resolver.Resolver(configure=False) + resolveur = dns.asyncresolver.Resolver(configure=False) resolveur.nameservers = list(self._serveurs["nameserver"]) resolveur.search = [dns.name.from_text(domaine) for domaine in self._serveurs["search"]] resolveur.ndots = self._serveurs["ndots"] @@ -181,7 +187,7 @@ def _client(self) -> dns.resolver.Resolver: return self._resolveur @traced - def _requete(self, nom: str, type_: str) -> list[str]: + async def _requete(self, nom: str, type_: str) -> list[str]: """Réponses d'une requête ; aucune si le nom n'existe pas ou sans réponse.""" if ( os.environ.get(VARIABLE_DESACTIVATION) or os.environ.get(VARIABLE_DESACTIVATION_ANCIENNE, "") @@ -189,7 +195,7 @@ def _requete(self, nom: str, type_: str) -> list[str]: logger.debug("dns : requêtes réseau coupées ({}=off)", VARIABLE_DESACTIVATION) return [] try: - reponse = self._client().resolve(nom, type_, search=True) + reponse = await self._client().resolve(nom, type_, search=True) except dns.exception.Timeout as exc: logger.debug("dns : délai dépassé pour {} {} : {}", nom, type_, exc) raise DelaiDepasse(str(exc)) from exc @@ -201,15 +207,14 @@ def _requete(self, nom: str, type_: str) -> list[str]: return resultats @traced - def adresses(self, nom: str) -> Iterator[str]: + async def adresses(self, nom: str) -> list[str]: """Adresses IPv4 puis IPv6.""" - yield from self._requete(nom, "A") - yield from self._requete(nom, "AAAA") + return [*await self._requete(nom, "A"), *await self._requete(nom, "AAAA")] @traced - def noms(self, adresse: str) -> list[str]: + async def noms(self, adresse: str) -> list[str]: """Noms PTR, sans point final.""" - return [nom.rstrip(".") for nom in self._requete(dns.reversename.from_address(adresse).to_text(), "PTR")] + return [nom.rstrip(".") for nom in await self._requete(dns.reversename.from_address(adresse).to_text(), "PTR")] @traced @@ -371,17 +376,21 @@ def _resolveurs(self, options: dict[str, Any], timeout: float) -> list[Resolveur return resolveurs @traced - def apply(self, doc: dict[str, Any]) -> bool: - """Applique `resolve` puis `reverse` ; True si le filtre est allé au bout.""" + async def apply(self, doc: dict[str, Any]) -> bool: + """Applique `resolve` puis `reverse` ; True si le filtre est allé au bout. + + Asynchrone depuis #35 (chantier full async #1) : la résolution + réseau passe par `dns.asyncresolver`. + """ for champs, inverse in ((self._resolve, False), (self._reverse, True)): - if champs is not None and not self._traiter(doc, champs, inverse=inverse): + if champs is not None and not await self._traiter(doc, champs, inverse=inverse): logger.debug("dns : filtre arrêté") return False logger.debug("dns : terminé") return True @traced - def _traiter(self, doc: dict[str, Any], champs: list[str], *, inverse: bool) -> bool: + async def _traiter(self, doc: dict[str, Any], champs: list[str], *, inverse: bool) -> bool: """`resolve(event)` / `reverse(event)` : False quand Ruby fait `return`.""" for champ in champs: chemin = parse_field_path(champ) @@ -401,14 +410,14 @@ def _traiter(self, doc: dict[str, Any], champs: list[str], *, inverse: bool) -> if inverse and not est_adresse(brut): logger.debug("dns : pas une adresse : {!r}", brut) return False - resultat = self._chercher(doc, brut, inverse=inverse) + resultat = await self._chercher(doc, brut, inverse=inverse) if resultat is None: return False self._ecrire(doc, chemin, resultat, tableau=tableau) return True @traced - def _chercher(self, doc: dict[str, Any], brut: str, *, inverse: bool) -> str | None: + async def _chercher(self, doc: dict[str, Any], brut: str, *, inverse: bool) -> str | None: """Résultat (caches compris) ; None si échec, délai dépassé ou erreur.""" if self._cache_echecs is not None and self._cache_echecs.lire(brut): logger.debug("dns : échec récent en cache : {}", brut) @@ -416,7 +425,7 @@ def _chercher(self, doc: dict[str, Any], brut: str, *, inverse: bool) -> str | N try: resultat = self._cache_succes.lire(brut) if self._cache_succes is not None else None if resultat is None: - resultat = self._avec_essais(brut, inverse=inverse) + resultat = await self._avec_essais(brut, inverse=inverse) if resultat is not None and self._cache_succes is not None: self._cache_succes.ecrire(brut, resultat) except DelaiDepasse: @@ -439,12 +448,12 @@ def _noter_echec(self, brut: str) -> None: self._cache_echecs.ecrire(brut, True) @traced - def _avec_essais(self, brut: str, *, inverse: bool) -> str | None: + async def _avec_essais(self, brut: str, *, inverse: bool) -> str | None: """`retriable_request` : nouveaux essais après un délai dépassé ou une erreur réseau.""" essais = 0 while True: try: - return self._nom(brut) if inverse else self._adresse(brut) + return await (self._nom(brut) if inverse else self._adresse(brut)) except (DelaiDepasse, OSError) as exc: if essais >= self._max_retries: logger.debug("dns : abandon après {} essai(s) : {}", essais + 1, exc) @@ -453,19 +462,19 @@ def _avec_essais(self, brut: str, *, inverse: bool) -> str | None: logger.debug("dns : nouvel essai {} pour {}", essais, brut) @traced - def _adresse(self, nom: str) -> str | None: + async def _adresse(self, nom: str) -> str | None: """Première adresse du premier résolveur qui répond.""" ascii_ = _vers_ascii(nom) for resolveur in self._resolveurs_actifs: - for adresse in resolveur.adresses(ascii_): + for adresse in await resolveur.adresses(ascii_): return adresse return None @traced - def _nom(self, adresse: str) -> str | None: + async def _nom(self, adresse: str) -> str | None: """Premier nom du premier résolveur qui répond, en Unicode.""" for resolveur in self._resolveurs_actifs: - for nom in resolveur.noms(adresse): + for nom in await resolveur.noms(adresse): return _vers_unicode(nom) return None diff --git a/src/pystashtemplate/interpreter.py b/src/pystashtemplate/interpreter.py index d54a478..ef0bea8 100644 --- a/src/pystashtemplate/interpreter.py +++ b/src/pystashtemplate/interpreter.py @@ -624,11 +624,11 @@ async def apply_events( events = [doc] for section in self._ast: if section[0] == "filter": - events = [ - produced - for event in events - for produced in self._run_filter_body(section[1], event, now=now, on_missing=on_missing) - ] + # #35 : _run_filter_body est asynchrone (filtre dns réseau). + produits: list[dict[str, Any]] = [] + for event in events: + produits.extend(await self._run_filter_body(section[1], event, now=now, on_missing=on_missing)) + events = produits # "input" : voir la docstring du module, "Limites assumées" — rien à appliquer. results: list[tuple[dict[str, Any], list[OutputAction]]] = [] for event in events: @@ -645,11 +645,14 @@ async def apply_events( # ------------------------------------------------------------------ @traced - def _run_filter_body( + async def _run_filter_body( self, body: list, doc: dict[str, Any], *, now: datetime | None, on_missing: str ) -> list[dict[str, Any]]: """Exécute séquentiellement les entrées d'un corps `filter{}` (ou d'une branche). + Asynchrone depuis #35 (chantier full async #1) : le plugin `dns` + attend la résolution réseau (`dns.asyncresolver`). + Returns: Les événements qui sortent du corps : `[doc]` en général, plus les copies de `clone`, les morceaux de `split` à la place de @@ -667,12 +670,12 @@ def _run_filter_body( if matched is None: produced.append(event) else: - produced.extend(self._run_filter_body(matched, event, now=now, on_missing=on_missing)) + produced.extend(await self._run_filter_body(matched, event, now=now, on_missing=on_missing)) i = end if events else _skip_chain_tail(body, i + 1) else: for event in events: try: - produced.extend(self._run_filter_plugin(entry, event, now=now, on_missing=on_missing)) + produced.extend(await self._run_filter_plugin(entry, event, now=now, on_missing=on_missing)) except _DocumentDropped as exc: logger.debug("événement écarté par un filtre : {}", exc) i += 1 @@ -681,7 +684,7 @@ def _run_filter_body( return events @traced - def _run_filter_plugin( + async def _run_filter_plugin( self, entry: list, doc: dict[str, Any], *, now: datetime | None, on_missing: str ) -> list[dict[str, Any]]: """Dispatche un plugin `filter{}` vers son comportement (ou l'ignore, tracé). @@ -727,7 +730,7 @@ def _run_filter_plugin( elif name == "xml": reussi = self._apply_xml(doc, options) elif name == "dns": - reussi = self._apply_dns(doc, options) + reussi = await self._apply_dns(doc, options) elif name in PLUGINS_SIMPLES: reussi = PLUGINS_SIMPLES[name](doc, options) elif name == "cidr": @@ -884,9 +887,11 @@ def _apply_xml(self, doc: dict[str, Any], options: dict[str, Any]) -> bool: return filtre.apply(doc) @traced - def _apply_dns(self, doc: dict[str, Any], options: dict[str, Any]) -> bool: + async def _apply_dns(self, doc: dict[str, Any], options: dict[str, Any]) -> bool: """`filter { dns { reverse => [...] resolve => [...] } }` — délègue à `dnslookup.DnsFilter` (#121). + Asynchrone depuis #35 (chantier full async #1). + Construit une fois par jeu d'options (clé JSON triée). Options invalides (par exemple un `${VAR}` non résolu à la place d'un nombre) : bloc ignoré, tracé, sans nouvel essai. @@ -905,7 +910,7 @@ def _apply_dns(self, doc: dict[str, Any], options: dict[str, Any]) -> bool: filtre = self._dns_filters[cle] if filtre is None: return False - return filtre.apply(doc) + return await filtre.apply(doc) @traced def _apply_json(self, doc: dict[str, Any], options: dict[str, Any]) -> bool: diff --git a/tests/test_dnslookup.py b/tests/test_dnslookup.py index d6d00db..75ba963 100644 --- a/tests/test_dnslookup.py +++ b/tests/test_dnslookup.py @@ -11,6 +11,7 @@ import asyncio from types import SimpleNamespace +import dns.asyncresolver import dns.exception import dns.resolver import pytest @@ -49,11 +50,11 @@ def _peut_echouer(self) -> None: if self._erreurs: raise self._erreurs.pop(0) - def adresses(self, nom: str) -> list[str]: + async def adresses(self, nom: str) -> list[str]: self._peut_echouer() return self._adresses.get(nom, []) - def noms(self, adresse: str) -> list[str]: + async def noms(self, adresse: str) -> list[str]: self._peut_echouer() return self._noms.get(adresse, []) @@ -66,7 +67,7 @@ def noms(self, adresse: str) -> list[str]: def _dns(options: dict, doc: dict, *resolveurs: Double) -> bool: """Applique `DnsFilter(options)` avec les résolveurs donnés (un double par défaut).""" - return DnsFilter(options, resolveurs=list(resolveurs) or [Double(**DOUBLE)]).apply(doc) + return _run(DnsFilter(options, resolveurs=list(resolveurs) or [Double(**DOUBLE)]).apply(doc)) class TestResolve: @@ -173,7 +174,7 @@ def test_cache_des_succes(self) -> None: double = Double(adresses={"x": ["1.1.1.1"]}) filtre = DnsFilter({"resolve": ["h"], "hit_cache_size": 10}, resolveurs=[double]) for _ in range(3): - assert filtre.apply({"h": "x"}) + assert _run(filtre.apply({"h": "x"})) assert double.appels == 1 def test_cache_des_echecs_et_expiration(self) -> None: @@ -184,19 +185,19 @@ def test_cache_des_echecs_et_expiration(self) -> None: resolveurs=[double], horloge=lambda: maintenant[0], ) - assert not filtre.apply({"h": "x"}) - assert not filtre.apply({"h": "x"}) + assert not _run(filtre.apply({"h": "x"})) + assert not _run(filtre.apply({"h": "x"})) assert double.appels == 1 maintenant[0] = 6.0 - assert not filtre.apply({"h": "x"}) + assert not _run(filtre.apply({"h": "x"})) assert double.appels == 2 def test_cache_des_echecs_sur_delai(self) -> None: double = Double(erreurs=[DelaiDepasse("t")]) filtre = DnsFilter({"resolve": ["h"], "failed_cache_size": 1, "max_retries": 0}, resolveurs=[double]) - assert not filtre.apply({"h": "x"}) + assert not _run(filtre.apply({"h": "x"})) doc = {"h": "x"} - assert not filtre.apply(doc) + assert not _run(filtre.apply(doc)) assert double.appels == 1 and "tags" not in doc def test_cache_ttl_lru(self) -> None: @@ -217,14 +218,14 @@ def test_lecture(self, tmp_path) -> None: encoding="utf-8", ) fichier = FichierHosts(str(hosts)) - assert fichier.adresses("web.local") == ["10.0.0.1", "10.0.0.2"] - assert fichier.noms("10.0.0.1") == ["web.local", "web"] - assert fichier.noms("::1") == ["six"] - assert fichier.adresses("seul") == [] - assert fichier.noms("bizarre") == ["nom-bizarre"] + assert _run(fichier.adresses("web.local")) == ["10.0.0.1", "10.0.0.2"] + assert _run(fichier.noms("10.0.0.1")) == ["web.local", "web"] + assert _run(fichier.noms("::1")) == ["six"] + assert _run(fichier.adresses("seul")) == [] + assert _run(fichier.noms("bizarre")) == ["nom-bizarre"] def test_absent(self, tmp_path) -> None: - assert FichierHosts(str(tmp_path / "absent")).adresses("x") == [] + assert _run(FichierHosts(str(tmp_path / "absent")).adresses("x")) == [] def test_ordre_des_resolveurs(self, tmp_path, monkeypatch) -> None: a, b, systeme = tmp_path / "a", tmp_path / "b", tmp_path / "systeme" @@ -234,7 +235,7 @@ def test_ordre_des_resolveurs(self, tmp_path, monkeypatch) -> None: monkeypatch.setattr(dnslookup, "HOSTS_SYSTEME", str(systeme)) doc = {"x": "x", "y": "y", "z": "z", "w": "w"} filtre = DnsFilter({"resolve": ["x", "y", "z"], "action": "replace", "hostsfile": [str(a), str(b)]}) - assert filtre.apply(doc) + assert _run(filtre.apply(doc)) assert doc == {"x": "10.0.0.1", "y": "10.0.0.2", "z": "10.0.0.3", "w": "w"} assert len(filtre._resolveurs_actifs) == 3 @@ -245,14 +246,14 @@ def _client(monkeypatch, reponses: dict) -> list: """Remplace `Resolver.resolve` par une table `(nom, type) → réponse ou exception`.""" appels: list = [] - def resolve(self, nom, type_, search=True): + async def resolve(self, nom, type_, search=True): appels.append((nom, type_, self.nameservers, self.lifetime)) reponse = reponses.get((nom, type_), dns.resolver.NoAnswer()) if isinstance(reponse, Exception): raise reponse return [SimpleNamespace(to_text=lambda v=v: v) for v in reponse] - monkeypatch.setattr(dns.resolver.Resolver, "resolve", resolve) + monkeypatch.setattr(dns.asyncresolver.Resolver, "resolve", resolve) monkeypatch.delenv("RSYSLOGSTACH_DNS", raising=False) monkeypatch.delenv("PYSTASHTEMPLATE_DNS", raising=False) return appels @@ -263,17 +264,17 @@ def test_a_puis_aaaa_et_ptr(self, monkeypatch) -> None: {("v6.fr", "AAAA"): ["::1"], ("1.0.0.10.in-addr.arpa.", "PTR"): ["web.local."]}, ) serveur = ServeurDns(0.5, serveurs_normalises({"address": ["192.0.2.53"], "search": "lan", "ndots": "2"})) - assert list(serveur.adresses("v6.fr")) == ["::1"] - assert serveur.noms("10.0.0.1") == ["web.local"] + assert _run(serveur.adresses("v6.fr")) == ["::1"] + assert _run(serveur.noms("10.0.0.1")) == ["web.local"] assert appels[0] == ("v6.fr", "A", ["192.0.2.53"], 0.5) assert serveur._client().ndots == 2 def test_nxdomain_et_delai(self, monkeypatch) -> None: self._client(monkeypatch, {("x", "A"): dns.resolver.NXDOMAIN(), ("t", "A"): dns.exception.Timeout()}) serveur = ServeurDns(0.1, serveurs_normalises("192.0.2.53")) - assert list(serveur.adresses("x")) == [] + assert _run(serveur.adresses("x")) == [] with pytest.raises(DelaiDepasse): - list(serveur.adresses("t")) + _run(serveur.adresses("t")) def test_configuration_systeme(self, monkeypatch) -> None: self._client(monkeypatch, {("x", "A"): ["10.1.1.1"]}) @@ -281,11 +282,11 @@ def test_configuration_systeme(self, monkeypatch) -> None: filtre = DnsFilter({"resolve": ["h"], "action": "replace", "timeout": 1}) assert isinstance(filtre._resolveurs_actifs[-1], ServeurDns) doc = {"h": "x"} - assert filtre.apply(doc) + assert _run(filtre.apply(doc)) assert doc == {"h": "10.1.1.1"} def test_coupe_par_variable(self) -> None: - assert ServeurDns(0.5, serveurs_normalises("192.0.2.53")).noms("10.0.0.1") == [] + assert _run(ServeurDns(0.5, serveurs_normalises("192.0.2.53")).noms("10.0.0.1")) == [] class TestOptions: @@ -328,7 +329,7 @@ def test_invalides(self, options: dict) -> None: def test_resolveurs_par_defaut(self) -> None: assert len(DnsFilter({"nameserver": "192.0.2.53"})._resolveurs_actifs) == 2 assert len(DnsFilter({"nameserver": []})._resolveurs_actifs) == 1 - assert DnsFilter({}).apply({"h": "x"}) + assert _run(DnsFilter({}).apply({"h": "x"})) def test_adresses_et_idn(self) -> None: assert est_adresse("10.0.0.1") and est_adresse("::1") and not est_adresse("010.0.0.1")