Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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=<chemin>` 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

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
71 changes: 40 additions & 31 deletions src/pystashtemplate/dnslookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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."""


Expand Down Expand Up @@ -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), []))
Expand All @@ -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"]
Expand All @@ -181,15 +187,15 @@ 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, "")
).strip().lower() == "off":
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
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -401,22 +410,22 @@ 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)
return None
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:
Expand All @@ -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)
Expand All @@ -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

Expand Down
29 changes: 17 additions & 12 deletions src/pystashtemplate/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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é).
Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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.
Expand All @@ -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:
Expand Down
Loading
Loading