diff --git a/CHANGELOG.md b/CHANGELOG.md index 3459a44..0b45b42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,17 @@ le projet suit SemVer. ### Évolutions +- Documentation et exemples de la bibliothèque rapatriés de RsysLogstach + (issue #57, suite du découpage RsysLogstach#111) : `PATTERNS.md` et + `FEATURES.md` (cités par les tests mais absents), référence des filtres et + pipelines `docs/pipeline-logstash.md`, audit + `docs/audit-fonctions-logstash.md`, exemples `filters.example.json`, + `blocklist.example.txt`, `enrich-dict.example.json` et + `pipeline.example.d/` (cités par le code de `filters`, `interpreter` et + `enrichment`) ; liens depuis le README. +- `LICENSES/` (texte Apache-2.0 et notice de logstash-patterns-core) : les + motifs grok recopiés dans `grok.py` y renvoient, le dossier était resté + dans RsysLogstach (#57). - `atraced` (issue #37, chantier full async #1) : équivalent asynchrone de `@traced` dans `tracing.py` — la sortie est journalisée quand la coroutine se termine réellement (autour du `await`), et non dès sa diff --git a/FEATURES.md b/FEATURES.md new file mode 100644 index 0000000..4b39782 --- /dev/null +++ b/FEATURES.md @@ -0,0 +1,100 @@ + +# FEATURES.md — Fonctionnalités de PyStashTemplate + +Fonctionnalités et limites connues de la bibliothèque, reprises de +`FEATURES.md` de RsysLogstach lors du découpage +[#111](https://github.com/Mathilde-Team/RsysLogstach/issues/111) (rapatriées +par #57). Les numéros de session et d'issues `#1xx` antérieurs au découpage +renvoient à RsysLogstach. Référence détaillée des formats : +[docs/pipeline-logstash.md](docs/pipeline-logstash.md) ; état fonction par +fonction : [docs/audit-fonctions-logstash.md](docs/audit-fonctions-logstash.md) ; +sorties : [docs/sorties.md](docs/sorties.md). + +## Fonctionnalités implémentées + +### Filtres (module `filters.py`, `FilterPipeline`) + +| Filtre | Options | Session | +|--------|---------|---------| +| **drop** | source, words_file, mode (contains), case_sensitive | 8 | +| **regex** | source, pattern (groupes nommés) | 8 | +| **kv** | source, field_split, value_split, prefix | 8 | +| **mutate** | convert (integer, integer_eu, float, float_eu, string, boolean ; règles de la documentation Logstash, RsysLogstach#73), remove_field, prefix | 14 | +| **mutate** | uppercase, lowercase, capitalize, split, join, merge, copy, update, coerce | 20 | +| **geoip** | source, target, tag_on_failure | 24 | +| **date** | match (ISO8601, UNIX, UNIX_MS, motif Java/Joda), target, timezone, tag_on_failure ; même implémentation que le plugin `date` des `.conf` | #34 | +| **dns** | mêmes options que le plugin `dns` du `.conf`, résolution asynchrone | #36 | + +### Enrichissement (module `enrichment.py`) + +- Dictionnaire statique JSON (`enrich-dict.example.json`) +- GeoIP via geoip2/maxminddb (`_build_geoip_record`, session 21) + +### Pipeline Logstash (module `interpreter.py`, `PipelineInterpreter`) + +- Parsing des fichiers `.conf` via `logstash-pipeline-parser` +- Exemples : `pipeline.example.d/10_input`, `25_filter`, `30_output` +- tag_on_failure pour date et geoip (sessions 19, 22, 24) +- Filtres natifs interprétés : `dissect`, `mutate`, `translate` (toutes les + options du plugin, #119), `mmdb`, `geoip`, `date`, `drop` (avec + `percentage`, #34), `kv` (#113), `fingerprint` (#114), `grok` (#112), + `useragent`, `xml` et `dns` (#121), `clone` et `split` (#141, module + `multievents.py`), plugins simples (#120, module `simples.py`), plus le + pont `filters_json` +- `apply` / `apply_events` asynchrones (#34) + +### Fingerprint (module `fingerprint.py`, session 17) + +- `compute_fingerprint()` — sha256/sha1/md5, MURMUR3 et HMAC (RsysLogstach#28) +- Document entier (fields=None/[]) ou sélection ordonnée de champs +- Séparateur de contrôle `\x1f` anti-collision +- `None` si tous les champs demandés sont absents + +### Traçabilité (module `tracing.py`) + +- Décorateurs `@traced` et `@atraced` (#37) — entrée/sortie systématique (loguru) +- Préserve `__name__`/`__doc__`/`__wrapped__` (functools.wraps) + +### Sorties (paquet `outputs`) + +Voir [docs/sorties.md](docs/sorties.md) et l'épopée #3. + +## Limites connues + +### Fingerprint (`fingerprint.py`) + +- Pas de IPV4_NETWORK (portée trop spécifique) +- Pas de HMAC MURMUR3, comme le filtre Logstash + +### Templates (`templates.py`) + +- Fraction de seconde `S…` : précision microseconde ; au-delà de 6 lettres, + complétée par des zéros (`SSSSSSSSS` → `123456000`) (#123) +- Lettres de date (#123) : Java Time dans `%{{…}}` (`G u y Y Q q M L w W D d E e c a h K k H m s S n N A V O X x Z z`) + et Joda dans `%{+…}` (`G C Y x y w e E M D d a h K k H m s S Z z`) ; + semaines ISO (lundi, semaine 1 d'au moins 4 jours) et textes en anglais, + alors que Java Time suit la locale de la JVM ; `F` et `B` recopiées telles + quelles +- Rendu des valeurs aligné sur Logstash 8 (`StringInterpolation`, #49) : + booléen `true`/`false`, liste jointe par `,`, objet en JSON compact +- Références mal formées refusées (`ValueError`) comme par Logstash : + `a[b]`, `a]`, `[]`, `[a[b]]` +- Écart assumé : un objet à l'intérieur d'une liste est rendu en JSON + (Logstash utilise le `toString()` Java de la map) +- Rendu d'un champ `null` : chaîne vide — écart assumé avec Logstash 8, qui + conserve le gabarit `%{champ}` littéral. **Fingerprint (#29, décision + Mathilde)** : un champ `null` est distingué d'un champ absent — il compte + comme présent (empreinte du contenu vide), `None` uniquement si tous les + champs demandés sont absents + +### Pipeline `.conf` (`interpreter.py`) + +- Plugins natifs non interprétés (structure seule, signalée en debug) : + `aggregate`, `ruby`… Leur équivalent passe par `filters_json` quand il existe +- Comme Logstash, un tableau à un seul élément dans une condition + (`[level] in ["ERROR"]`) est une **référence de champ**, pas un tableau : + écrire `[level] == "ERROR"` ou au moins deux éléments +- `mutate convert` : une chaîne non numérique (« abc ») laisse le champ + inchangé (Logstash/Ruby donnerait 0) +- GeoIP : les tests automatisés utilisent des bases mmdb construites pour + les tests ; aucune base MaxMind réelle n'est livrée diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSES/NOTICE-logstash-patterns-core.txt b/LICENSES/NOTICE-logstash-patterns-core.txt new file mode 100644 index 0000000..0b8a947 --- /dev/null +++ b/LICENSES/NOTICE-logstash-patterns-core.txt @@ -0,0 +1,5 @@ +Elasticsearch +Copyright 2012-2015 Elasticsearch + +This product includes software developed by The Apache Software +Foundation (http://www.apache.org/). \ No newline at end of file diff --git a/PATTERNS.md b/PATTERNS.md new file mode 100644 index 0000000..03ed1e5 --- /dev/null +++ b/PATTERNS.md @@ -0,0 +1,57 @@ + +# PATTERNS.md — Conventions et patterns de PyStashTemplate + +Conventions reprises de RsysLogstach lors du découpage +[#111](https://github.com/Mathilde-Team/RsysLogstach/issues/111) (rapatriées +par #57) : elles portaient sur les modules qui vivent désormais ici. Les +numéros de session et d'issues cités renvoient à l'historique de +RsysLogstach. + +## Traçabilité systématique des fonctions + +**Règle :** toute fonction du paquet (`src/pystashtemplate/`, hors `tests/`) +est tracée à l'entrée ET à la sortie (retour normal ou exception). + +**Implémentation :** décorateur `@traced` (`tracing.py`) pour les fonctions +synchrones, `@atraced` pour les coroutines (#37 : la sortie est journalisée +quand la coroutine se termine réellement, autour du `await`). Le décorateur +enveloppe l'appel entier — il ne peut structurellement pas rater un chemin +de sortie, contrairement à une convention appliquée à la main. +`scripts/audit_debug_sorties.py` reconnaît les deux décorateurs. + +**Contenu des logs :** uniquement le `__qualname__` — jamais les arguments +ni la valeur de retour (les appelants manipulent des secrets : +identifiants des sorties, clés HMAC). Une fonction qui a besoin de +journaliser un détail précis et non sensible le fait via son propre +`logger.debug()` additionnel. + +**Compatibilité :** `functools.wraps` préserve `__name__`/`__doc__`/`__wrapped__` +— compatible avec `inspect.signature`. + +## Absence de dépendances circulaires entre modules + +**Règle :** le graphe de dépendances entre modules du paquet reste acyclique. + +**Vérification :** `tests/test_no_cross_imports.py` analyse les imports via +`ast` (pas de simple relecture) et vérifie mécaniquement l'absence de cycles. + +**Exemples de décisions prises pour respecter cette règle :** + +- `tracing` est intentionnellement sans AUCUNE dépendance interne — c'est le + seul moyen pour que tous les autres modules puissent l'importer sans cycle. +- `util.add_failure_tags` a été déplacée depuis `interpreter.py` (session 24) + vers `util.py` pour être partagée avec `filters.py::GeoipFilter` sans créer + de dépendance `filters → interpreter` (interdite : `interpreter` dépend + déjà de `filters`). +- `_build_geoip_record` (session 21) est dans `enrichment.py`, consommé par + `filters.py` — pas l'inverse. +- `fingerprint.py` dépend de `templates` (résolution de chemins) mais + `templates` ne dépend jamais de `fingerprint` — vérifié par + `test_templates_has_no_dependency_on_fingerprint`. + +## Opérations bloquantes hors boucle asyncio + +**Convention :** les écritures disque (DLQ) se font via `asyncio.to_thread`, +et la résolution DNS passe par `dns.asyncresolver` (#35), pour ne jamais +bloquer la boucle asyncio de l'appelant (connecteur rsyslog, service +réseau…). diff --git a/README.md b/README.md index c4c458d..6b52c92 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,22 @@ outil (…beat) pourrait le faire). `opensearch`, banc de conformité en conteneur en CI) — voir [docs/sorties.md](docs/sorties.md) +## Documentation + +- [docs/pipeline-logstash.md](docs/pipeline-logstash.md) : référence de la + chaîne de filtres JSON, de l'enrichissement et des pipelines `.conf` + (translate, grok, useragent, xml, dns, clone/split…) +- [docs/audit-fonctions-logstash.md](docs/audit-fonctions-logstash.md) : + état fonction par fonction (fait, partiel, pas fait) +- [docs/sorties.md](docs/sorties.md) : sorties agnostiques +- [FEATURES.md](FEATURES.md) : fonctionnalités et limites connues +- [PATTERNS.md](PATTERNS.md) : conventions (traçabilité, graphe acyclique) +- Exemples : `filters.example.json`, `blocklist.example.txt`, + `enrich-dict.example.json`, `pipeline.example.d/` + +Rapatriés de RsysLogstach par #57 (découpage +[#111](https://github.com/Mathilde-Team/RsysLogstach/issues/111)). + ## Utilisation ```bash @@ -131,3 +147,11 @@ et compile les `.mo`. La locale se force par `$LANGUAGE` ou GPL-3.0-or-later. Crédits et historique complet : projet [RsysLogstach](https://github.com/Mathilde-Team/RsysLogstach) (sources d'origine, issues #25, #40, #73, #111...). + +La bibliothèque des motifs `grok` de base (`patterns/legacy/grok-patterns` +de [logstash-patterns-core](https://github.com/logstash-plugins/logstash-patterns-core), +Copyright 2012-2015 Elasticsearch, Apache-2.0) est recopiée sans +modification dans `src/pystashtemplate/grok.py`, avec attribution ; le texte +de la licence Apache-2.0 et la notice d'origine sont dans +[`LICENSES/`](LICENSES/) (rapatriés de RsysLogstach par #57). Cette licence +est compatible avec la GPLv3. diff --git a/blocklist.example.txt b/blocklist.example.txt new file mode 100644 index 0000000..9db68a8 --- /dev/null +++ b/blocklist.example.txt @@ -0,0 +1,7 @@ +# Un motif par ligne. Lignes vides et commençant par "#" ignorées. +# Comparaison "contains" (sous-chaîne) et insensible à la casse par défaut +# (voir "mode" et "case_sensitive" dans la définition du filtre "drop"). +keepalive +heartbeat +# Exemples de bruit fréquent à adapter à vos propres messages : +NTP synchronized diff --git a/docs/audit-fonctions-logstash.md b/docs/audit-fonctions-logstash.md new file mode 100644 index 0000000..58fe06b --- /dev/null +++ b/docs/audit-fonctions-logstash.md @@ -0,0 +1,97 @@ + +# Audit des fonctions Logstash utilisables dans les templates + +Issue RsysLogstach#101, état au 03/11/2026, rapatrié dans PyStashTemplate +par #57 (découpage RsysLogstach#111). Les numéros d'issues cités (#112, +#123…) sont ceux de [RsysLogstach](https://github.com/Mathilde-Team/RsysLogstach/issues), +où les fonctions ont été développées avant le découpage ; les chemins +`src/*.py` sont devenus les modules du paquet `pystashtemplate`. Ce tableau recense les fonctions +qu'un pipeline Logstash peut utiliser : gabarits sprintf `%{...}`, conditions, +plugins `filter{}` et `output{}`, options communes. Il indique ensuite ce que +PyStashTemplate interprète réellement. + +Légende : **fait** = interprété avec le comportement Logstash ; **partiel** = +interprété avec des limites (voir commentaire) ; **pas fait** = accepté par le +parseur mais sans effet sur le document ; **hors périmètre** = sans objet pour +un pont rsyslog → OpenSearch. + +Références : [documentation des filtres Logstash](https://www.elastic.co/guide/en/logstash/current/filter-plugins.html), +[références de champs et sprintf](https://www.elastic.co/guide/en/logstash/current/event-dependent-configuration.html), +[plugin logstash-output-opensearch](https://github.com/opensearch-project/logstash-output-opensearch). + +## Gabarits sprintf (PyStashTemplate : `templates`) + +| Fonction | Fait / pas fait | Commentaires | +|---|---|---| +| `%{champ}` | fait | Champ de premier niveau. | +| `%{[objet][champ]}` | fait | Un niveau par paire de crochets, profondeur libre. | +| `%{[@metadata][champ]}` | fait | `@metadata` traité comme un champ racine ordinaire. | +| `%{[tableau][0]}` | fait | Indice numérique de tableau. | +| `%{+YYYY.MM.dd}` (Joda) | fait | Date de `@timestamp`, ancienne syntaxe. | +| `%{{yyyy.MM.dd}}` (Java Time) | fait (#123) | Lettres `G u y Y Q q M L w W D d E e c a h K k H m s S n N A V O X x Z z` et texte entre quotes ; `%{+…}` suit les lettres Joda (`C`, `x` année de semaine…). Semaines ISO et textes en anglais (Java Time suit la locale de la JVM) ; `F` et `B` recopiées telles quelles. | +| `%{{TIME_NOW}}` | fait | Heure du traitement, pas `@timestamp`. | +| `%{+%s}` (epoch) | fait | Secondes depuis l'epoch de `@timestamp` (corrigé par #102 : rendait `%0`). | +| Champ absent | fait | `--pipeline-on-missing` / `--filters-on-missing` : `keep` conserve `%{...}`, `empty` rend une chaîne vide. Un champ `null` se rend vide. | +| Valeur hash ou tableau dans `%{...}` | fait | Rendue en JSON compact. | +| Échappement de crochets dans un nom de champ (`none`/`percent`/`ampersand`) | fait | `--field-reference-escape-style` (#124), équivalent de `field_reference.escape_style` de logstash.yml : `%5B`/`%5D` ou `[`/`]` désignent un crochet littéral, dans les gabarits comme dans les options des plugins. | +| `${VAR}` / `${VAR:défaut}` (variables d'environnement du `.conf`) | fait (#122) | Substitués au chargement du `.conf`, avant l'analyse : la variable définie prime sur la valeur par défaut ; non définie sans défaut → `ValueError` qui la nomme. `%{champ}` (rendu par événement) non concerné. Noms invalides (`${1x}`) laissés tels quels. | + +## Conditions `if` / `else if` / `else` (PyStashTemplate : `interpreter`) + +| Fonction | Fait / pas fait | Commentaires | +|---|---|---| +| `if [champ]` (présence) | fait | Absent, `null` ou `false` → faux ; chaîne vide et `0` → vrai, comme Logstash. | +| `==`, `!=`, `<`, `<=`, `>`, `>=` | fait | Un opérande absent n'est égal à rien (`!=` vrai, le reste faux). | +| `=~`, `!~` (regex) | fait | Expression régulière Python. | +| `in`, `not in` | fait | Sous-chaîne si la cible est une chaîne, appartenance si c'est un tableau. | +| `and`, `or`, `xor`, `nand` | fait | Sans court-circuit. | +| `!` (négation), parenthèses | fait | | +| `else if` en chaîne, `if` imbriqués | fait | Dans `filter{}` comme dans `output{}`. | + +## Plugins `filter{}` + +| Plugin | Fait / pas fait | Commentaires | +|---|---|---| +| `mutate` | fait | Ordre officiel : `coerce`, `rename`, `update`, `replace`, `convert`, `gsub`, `uppercase`, `capitalize`, `lowercase`, `strip`, `split`, `join`, `merge`, `copy`, puis options communes. `tag_on_failure` (défaut `_mutate_error`). | +| `dissect` | fait | `mapping` (sources imbriquées comprises), `convert_datatype` (`int`, `float`) et `tag_on_failure` (défaut `_dissectfailure` : source absente, vide ou sans correspondance) (#117). Pas de référence indirecte `%{&champ}`. | +| `date` | fait | `match` (ISO8601, UNIX, UNIX_MS, motifs Joda), `target`, `timezone`, `locale` (`fr`), `tag_on_failure`. `SSS` (millisecondes) et fuseaux textuels `z`/`ZZZ` (« CET », IDs IANA) reconnus (#118) ; les abréviations couvertes sont réduites (zones européennes et nord-américaines courantes). Les lettres Java Time des gabarits (#123) ne concernent pas `match`. | +| `geoip` | partiel | `source`, `target`, `fields`, `tag_on_failure`. `database` obligatoire (pas de base GeoLite2 embarquée). | +| `translate` | fait | #119 : `source`/`field`, `target`/`destination` (défaut en place, `translation` si `ecs_compatibility => disabled`), `dictionary` en ligne, `dictionary_path` (YAML, JSON, CSV), `exact`, `regex`, `override`, `fallback` (gabarit sprintf), `iterate_on` (tableau de valeurs ou d'objets), `refresh_interval`, `refresh_behaviour` (`merge`/`replace`). Rechargement au premier document après l'intervalle (pas de minuterie) ; `yaml_dictionary_code_point_limit` et `yaml_load_strategy` sans effet ; clés comparées en texte. | +| `drop` | fait | `percentage` compris. | +| `grok` | fait | Bloc natif (#112) : bibliothèque des 70 motifs de base Logstash, `%{SYNTAXE:champ:int}` et `:float`, `(?...)`, `break_on_match`, `overwrite`, `tag_on_failure`, `patterns_dir`, `patterns_files_glob`, `pattern_definitions`, `keep_empty_captures`, `target`. Moteur `re` Python : `named_captures_only` toujours vrai, `timeout_millis` non appliqué. | +| `kv` | fait | Bloc natif `filter { kv { ... } }` (#113) : `source`, `target` (fusion dans un hash existant), `field_split`, `value_split`, `include_keys`, `exclude_keys`, `prefix`, `trim_key`, `trim_value`, `allow_duplicate_values` (clé répétée → liste, dédup si `false`). Réutilise `filters.KeyValueFilter` (même algorithme que le step `--filters`). | +| `json` | fait | Bloc `filter{}` natif (#115) : `source`, `target` (sinon fusion à la racine), `skip_on_invalid_json`, `tag_on_failure` (défaut `_jsonparsefailure`). `@timestamp` décodé n'est pas converti en date. | +| `dns` | fait (#121) | `src/dnslookup.py`, dnspython : `resolve`, `reverse`, `action`, `nameserver`, `hostsfile`, `timeout`, `max_retries`, caches, `tag_on_timeout`, IDNA. Les `${VAR:défaut}` de l'exemple `pipeline.example.d/25_filter_…` sont substitués au chargement (#122). | +| `fingerprint` | fait | Bloc `filter{}` natif (#114) : `source`, `target`, `method` (SHA1, SHA256, SHA384, SHA512, MD5, MURMUR3, UUID, IPV4_NETWORK), `key` (HMAC ou masque IPv4), `base64encode`, `concatenate_sources`, `concatenate_all_fields`. Côté indexation : `--document-id-fingerprint`. | +| `csv`, `cidr`, `prune`, `urldecode`, `uuid`, `syslog_pri`, `truncate` | fait | Blocs natifs (#120, `src/simples.py`), options principales et défauts du plugin officiel ; `csv` : `convert` en `integer`, `float`, `boolean` seulement ; `prune` : champs de premier niveau, sans `interpolate`. | +| `clone`, `split` | fait (#141) | `clone` : `clones`, `type` ou tag selon `ecs_compatibility` ; `split` : `field`, `terminator`, `target`, tag `_splitparsefailure`. Les nouveaux événements poursuivent le pipeline après le filtre et sont tous indexés (`PipelineInterpreter.apply_events`). | +| `useragent` | fait (#121) | `src/useragent.py`, ua-parser : champs ECS et anciens champs (`ecs_compatibility => disabled`), `prefix`, `regexes`, `lru_cache_size`. | +| `xml` | fait (#121) | `src/xmlfilter.py`, lxml : `store_xml` façon XmlSimple, `xpath`, `namespaces`, `remove_namespaces`, `parse_options` (entités, DTD et XInclude refusés), `force_array`, `force_content`, `suppress_empty`. | +| `aggregate`, `ruby`, `elapsed`, `throttle`, `memcached`, `http`, `jdbc_*` | pas fait | Blocs acceptés par le parseur, sans effet. | +| `mmdb` (communautaire) | fait | Extension hors cœur Logstash : `database`, `source`, `target`. | +| `filters_json` (propre au projet) | fait | Invoque un fichier `--filters` depuis un `.conf`. | + +## Options communes à tous les filtres + +| Option | Fait / pas fait | Commentaires | +|---|---|---| +| `add_field`, `remove_field`, `add_tag`, `remove_tag` | fait | Après tout filtre natif réussi (`mutate`, `dissect`, `date`, `geoip`, `translate`, `mmdb`, `kv`, `grok`), jamais après un échec, comme `filter_matched` (#116). | +| `id`, `enable_metric`, `periodic_flush` | hors périmètre | Sans effet sur le document. | + +## Plugins et options `output{}` + +| Fonction | Fait / pas fait | Commentaires | +|---|---|---| +| `opensearch { … }` / `elasticsearch { … }` | partiel | Lues par document (gabarits sprintf) : `index`, `document_id`, `action`, `pipeline`, `routing`, `doc_as_upsert` (#126). | +| `hosts`, `user`, `password`, `ssl`, `ssl_certificate_verification` | fait (#125) | Lus dans le `.conf` (branches comprises) ; `--opensearch-host`, `OPENSEARCH_USER` / `OPENSEARCH_PASSWORD` et `--no-verify-certs` restent prioritaires. Une seule connexion : valeurs différentes d'un bloc à l'autre refusées. | +| `cacert`, `tls_certificate`, `tls_key` (mTLS) | fait | Mêmes noms que le plugin logstash-output-opensearch : `--cacert`, `--tls-certificate`, `--tls-key` (#100), ou dans le `.conf` (#125) ; la ligne de commande est prioritaire. | +| `keystore`, `truststore` (JKS / PKCS#12) | pas fait | Format Java ; utiliser des fichiers PEM. | +| `action`, `pipeline`, `routing` | fait | #126 : `action` `index` (défaut), `create` (`op_type=create`), `update` (`doc_as_upsert` possible) ou `delete` ; `update` et `delete` exigent `document_id`, sinon le document part en DLQ ; `pipeline` est ignoré pour `update` et `delete`, que l'API n'accepte pas. Un document par requête, pas de `_bulk`. | +| `ilm_*`, `template*` | pas fait | Le template d'index passe par `--index-template`. | +| `stdout`, `file`, `http`, autres sorties | pas fait | Ignorées (trace de débogage). | + +## Sections `input{}` + +| Fonction | Fait / pas fait | Commentaires | +|---|---|---| +| `input { … }` | hors périmètre | Parsé mais jamais exécuté : l'entrée est rsyslog (omprog). | diff --git a/docs/pipeline-logstash.md b/docs/pipeline-logstash.md new file mode 100644 index 0000000..1a46102 --- /dev/null +++ b/docs/pipeline-logstash.md @@ -0,0 +1,211 @@ + +# Référence : filtres et pipelines Logstash + +Référence des formats interprétés par PyStashTemplate : chaîne de filtres +JSON (`pystashtemplate.filters.FilterPipeline`), enrichissement par +dictionnaire (`pystashtemplate.enrichment`) et pipelines `.conf` Logstash +(`pystashtemplate.interpreter.PipelineInterpreter`). + +Cette page vient du README de +[RsysLogstach](https://github.com/Mathilde-Team/RsysLogstach), où elle +documentait les options `--filters`, `--enrich-dict` et `--pipeline-conf` +du connecteur rsyslog, avant le découpage +[#111](https://github.com/Mathilde-Team/RsysLogstach/issues/111) (rapatriée +par #57). Les exemples cités (`filters.example.json`, +`blocklist.example.txt`, `enrich-dict.example.json`, `pipeline.example.d/`) +sont à la racine du dépôt. + +Depuis le chantier « full async » (#1), `FilterPipeline.apply` et +`PipelineInterpreter.apply` / `apply_events` sont des coroutines. + +## Chaîne de filtres JSON (`FilterPipeline`) + +Voir `filters.example.json` : + +```json +[ + {"type": "drop", "source": "msg", "words_file": "/etc/omprog/blocklist.txt", "mode": "contains"}, + {"type": "regex", "source": "msg", "pattern": "^%%\\d+(?P[A-Z_]+)/..."}, + {"type": "kv", "source": "detail", "field_split": " ", "value_split": "=", "prefix": "kv_"}, + {"type": "mutate", "convert": {"severity_code": "integer"}, "remove_field": ["msg"]} +] +``` + +Step `date` (#34), mêmes options que le plugin `date` de Logstash : `{"type": "date", "match": ["horodatage", "ISO8601", "MMM dd HH:mm:ss"], "timezone": "Europe/Paris"}` écrit `@timestamp` (ou `target`) en ISO8601 UTC, et ajoute `_dateparsefailure` (ou `tag_on_failure`) aux tags si aucun motif ne correspond. Motifs `SSS` (millisecondes) et `z`/`ZZZ` (fuseau textuel : « CET », « Europe/Paris ») reconnus, ainsi que l'option `locale` (`fr` : noms de mois/jours français, #118). `grok` n'est pas proposé : un step `regex` à groupes nommés le remplace. + +## Enrichissement par dictionnaire (`DictEnricher`) + +```json +{ + "sw-core-01": {"site": "Besançon - DR", "role": "core", "owner_team": "Infra Réseau"} +} +``` + +## Pipeline Logstash `.conf` (`PipelineInterpreter`) + +Voir `pipeline.example.d/` : input UDP → filter (DNS, GeoIP) → output OpenSearch. + +Fonctions Logstash prises en charge (gabarits `%{...}`, conditions, plugins +`filter{}`/`output{}`) et limites : [audit-fonctions-logstash.md](audit-fonctions-logstash.md). + +Variables d'environnement du `.conf` (#122) : `${VAR}` et `${VAR:défaut}` sont +substitués au chargement, comme Logstash — la variable définie prime sur la +valeur par défaut ; une variable non définie sans défaut refuse le démarrage +(`ValueError` qui la nomme). `%{champ}` (rendu par événement) n'est pas +concerné. +Sorties `opensearch` (#126) : `action` (`index`, `create`, `update`, `delete`), `pipeline` et `routing` acceptent des gabarits, par exemple `opensearch { index => "logs" action => "update" document_id => "%{id}" doc_as_upsert => true routing => "%{host}" }`. + +Nom de champ contenant des crochets (#124) : avec `--field-reference-escape-style percent`, `%{[map%5Bk%5D]}` lit le champ `map[k]` ; `ampersand` utilise `[` et `]`. Défaut `none`, comme Logstash. + +Plugins simples natifs (#120) : `csv`, `cidr`, `prune`, `urldecode`, `uuid`, `syslog_pri`, `truncate` ; par exemple `cidr { address => ["%{ip}"] network => ["10.0.0.0/8"] add_tag => ["interne"] }`. Plusieurs événements par message (#141) : `clone { clones => ["copie"] }` garde l'original et ajoute une copie par nom (ajouté à `tags`, ou écrit dans `type` avec `ecs_compatibility => disabled`) ; `split { field => "message" terminator => "\n" target => "ligne" }` remplace l'événement par un événement par morceau non vide (une liste est parcourue élément par élément ; champ absent ou d'un autre type : tag `_splitparsefailure`). Les options communes (`add_field`, `add_tag`…) s'appliquent aux nouveaux événements ; ceux-ci poursuivent le pipeline à partir du filtre suivant, et chacun est indexé selon ses propres sorties. Un `drop` n'écarte que l'événement qu'il atteint ; rsyslog reçoit un échec transitoire si l'indexation de l'un d'eux échoue, et renvoie alors le message entier. + +Un `dissect` qui échoue (source absente ou sans correspondance) ajoute `_dissectfailure` aux `tags`, ou les tags de `tag_on_failure` (#117) ; `convert_datatype => { "port" => "int" }` convertit ensuite les champs extraits. +Plugin `kv` natif (#113) : `filter { kv { source => "message" target => "pairs" ... } }` +réutilise le même extracteur que le step `kv` de `--filters` (options +`include_keys`, `exclude_keys`, `trim_key`, `trim_value`, +`allow_duplicate_values` comprises ; clé répétée → liste de valeurs). + +Les chaînes entre guillemets sont lues brutes, comme Logstash par défaut +(`config.support_escapes: false`) : `"\d+"` reste `\d+` (#128). + +### `translate` (#119) + +``` +filter { + translate { + source => "[ifTable][index]" + target => "[ifTable][name]" # facultatif : traduction en place + dictionary_path => "/etc/rsyslogstach/ifName.yml" # ou .json, .csv ; ou dictionary => { "1" => "Uplink" } + fallback => "index: %{[ifTable][index]}" + refresh_interval => 300 # relu s'il a changé ; refresh_behaviour => "merge" ou "replace" + } +} +``` + +- Comme le plugin officiel : `override` (faux, sauf en place), `exact`, + `regex` (clés vues comme regex), `exact => false` (remplacement de + chaque clé trouvée dans la valeur), `iterate_on` (tableau de valeurs ou + tableau d'objets), anciens noms `field`/`destination`. +- Le même code sert le step `translate` de `--filters`. +- Différences : rechargement au premier document après l'intervalle (pas + de minuterie) ; clés comparées en texte ; une extension de fichier + inconnue est lue comme du YAML. + +### `grok` (#112) + +``` +filter { + grok { + match => { "message" => "%{SYSLOGBASE} %{GREEDYDATA:texte}" } + # ou plusieurs motifs : { "message" => ["%{IP:client} %{NUMBER:octets:int}", "%{GREEDYDATA:brut}"] } + } +} +``` + +- Motifs `%{SYNTAXE}`, `%{SYNTAXE:champ}`, `%{SYNTAXE:champ:int|float}`, champs + imbriqués (`%{IP:[client][ip]}`) et groupes nommés `(?...)`. +- Bibliothèque de base de Logstash (`USERNAME`, `INT`, `NUMBER`, `WORD`, + `NOTSPACE`, `DATA`, `GREEDYDATA`, `QUOTEDSTRING`, `UUID`, `MAC`, `IP`, + `IPV4`, `IPV6`, `HOSTNAME`, `IPORHOST`, `URI`, `PATH`, `TIMESTAMP_ISO8601`, + `SYSLOGTIMESTAMP`, `SYSLOGBASE`, `HTTPDATE`, `LOGLEVEL`…, 70 motifs). +- Options : `break_on_match` (vrai), `overwrite`, `tag_on_failure` + (`_grokparsefailure`), `patterns_dir` + `patterns_files_glob`, + `pattern_definitions`, `keep_empty_captures`, `target`. +- Sans `overwrite`, une capture vers un champ texte existant donne un + tableau `[ancien, nouveau]`, comme Logstash. +- Différences : moteur `re` de Python (3.11+) au lieu d'Oniguruma — groupes + nommés, classes POSIX et `\z` sont traduits ; `named_captures_only` + toujours vrai ; `timeout_millis` non appliqué. Un motif invalide ou + inconnu est ignoré (journal DEBUG), les autres motifs restent actifs. + +### `useragent` (#121) + +``` +filter { + useragent { + source => "[user_agent][original]" + # target => "[user_agent]" (défaut en mode ECS) + } +} +``` + +- Analyse par [ua-parser](https://github.com/ua-parser/uap-python) (motifs + uap-core, comme le parseur Java de Logstash). Champs ECS écrits : + `[name]`, `[version]` (`89.0.4389.90`), `[device][name]`, `[os][name]`, + `[os][version]`, `[os][full]` sous la cible ; major, minor et patch dans + `[@metadata][filter][user_agent][version]` et `[…][os][version]`. +- `ecs_compatibility => disabled` : cible vide (racine) par défaut et anciens + champs `name`, `device`, `major`, `minor`, `patch`, `version`, `os`, + `os_name`, `os_full`, `os_version`, `os_major`, `os_minor`, `os_patch`, + précédés de `prefix`. +- Options : `source` (requis), `target`, `prefix`, `regexes` (fichier + `regexes.yaml` de uap-core), `lru_cache_size` (100 000). Un tableau donne + son premier élément ; source absente ou vide : rien. Si `target` égale + `source`, la source est remplacée. +- Différences : motifs du paquet `ua-parser-builtins` figé dans + `pyproject.toml`, pas ceux du jar de Logstash ; un User-Agent récent ou + rare peut être classé autrement. Fichier `regexes` illisible : bloc ignoré + (journal DEBUG). + +### `xml` (#121) + +``` +filter { + xml { + source => "message" + target => "doc" + xpath => { "/evenement/@id" => "[evenement][id]" } + } +} +``` + +- `store_xml` (vrai par défaut, `target` requis) : conversion façon + XmlSimple, comme Logstash — attributs et enfants dans le même objet, + enfants en tableaux (`force_array`), texte seul en chaîne ou sous + `content` (`force_content`, ou en présence d'attributs), éléments vides + omis (`suppress_empty`). L'élément racine n'apparaît pas. Analyse stricte. +- `xpath => { "expression" => "[champ]" }` : analyse tolérante (ou selon + `parse_options`, par ex. `strict`), résultats en tableau (texte seul avec + `force_array => false` et un résultat). Préfixes de la racine (défaut sous + `xmlns`) ou `namespaces` ; `remove_namespaces`. +- Échec d'analyse, expression invalide, tableau de longueur différente de 1 + ou valeur non textuelle : tag `_xmlparsefailure`. +- Sécurité : ni entités externes, ni DTD, ni XInclude, ni réseau ; + `parse_options` `noent`, `dtdload`, `dtdattr`, `dtdvalid` ou `xinclude` + rend le bloc invalide (ignoré, journal DEBUG). +- Différences : lxml (libxml2) remplace Nokogiri et REXML ; un document + sans élément racine, même en mode tolérant, ne donne aucun résultat XPath. + +### `dns` (#121) + +``` +filter { + dns { + reverse => [ "[host][ip]" ] + action => "replace" + nameserver => { address => ["192.0.2.53"] search => ["lan"] } + hit_cache_size => 4096 + } +} +``` + +- `resolve` (nom → première adresse, IPv4 puis IPv6) et `reverse` + (adresse → premier nom) ; `action` `append` (défaut, le champ devient + `[valeur, résultat]`) ou `replace`. +- Résolveurs dans l'ordre : `hostsfile`, `/etc/hosts`, puis `nameserver` + (chaîne, liste, ou hash `address`/`search`/`ndots`). Sans les deux : + `/etc/hosts` puis le DNS du système ; avec `hostsfile` seul : aucun DNS. +- `timeout` (0,5 s), `max_retries` (2), `tag_on_timeout` (`_dnstimeout`), + caches `hit_cache_size`/`hit_cache_ttl` (0, 60 s) et + `failed_cache_size`/`failed_cache_ttl` (0, 5 s), noms IDNA. +- Comme Logstash, un champ absent est sauté, mais plusieurs valeurs, une + valeur non textuelle, une adresse invalide ou un échec arrêtent le + filtre, sans options communes. +- `PYSTASHTEMPLATE_DNS=off` (ancien nom `RSYSLOGSTACH_DNS` toujours lu) + coupe les requêtes réseau (fichiers hosts seulement) ; les tests le + positionnent. +- Limite : les nombres écrits `"${VAR}"` ne sont pas encore remplacés + (#122) : le bloc est alors ignoré (journal DEBUG), c'est le cas de + `pipeline.example.d/25_…`. + +Exemple de filtre `json` natif (#115) : `json { source => "message" target => "payload" skip_on_invalid_json => true }`. diff --git a/enrich-dict.example.json b/enrich-dict.example.json new file mode 100644 index 0000000..037805a --- /dev/null +++ b/enrich-dict.example.json @@ -0,0 +1,11 @@ +{ + "sw-core-01": { + "site": "Besançon - DR", + "role": "core", + "owner_team": "Infra Réseau" + }, + "sw-access-12": { + "site": "Besançon - DR", + "role": "access" + } +} diff --git a/filters.example.json b/filters.example.json new file mode 100644 index 0000000..7ce2e36 --- /dev/null +++ b/filters.example.json @@ -0,0 +1,31 @@ +[ + { + "type": "drop", + "source": "msg", + "words_file": "/etc/omprog/blocklist.txt", + "mode": "contains", + "case_sensitive": false, + "_comment": "Bloque (n'indexe pas) tout message contenant un des mots de blocklist.txt (ex. bruit connu : keepalive, heartbeat). Voir blocklist.example.txt." + }, + { + "type": "regex", + "source": "msg", + "pattern": "^%%\\d+(?P[A-Z_]+)/(?P\\d+)/(?P[A-Z_]+): ?(?P.*)$", + "_comment": "Illustratif : format typique HPE Comware '%%10MODULE/sévérité/ÉVÉNEMENT: détail'. Le préfixe numérique collé au nom de module ('10IFNET') empêche un dissect positionnel pur, d'où la regex." + }, + { + "type": "kv", + "source": "detail", + "field_split": " ", + "value_split": "=", + "prefix": "kv_", + "_comment": "Si 'detail' contient des paires clé=valeur (ex. 'user=admin action=login'), ajuster/retirer sinon." + }, + { + "type": "mutate", + "convert": {"severity_code": "integer"}, + "uppercase": ["module"], + "remove_field": ["msg"], + "_comment": "Nouveauté session 14 : cast severity_code (texte extrait par la regex ci-dessus) en entier, puis retire le champ 'msg' brut devenu redondant une fois parsé. 'uppercase' (nouveauté session 20) normalise la casse de 'module', déjà en majuscules chez HPE Comware mais illustratif d'une des nouvelles options officielles Logstash (uppercase/lowercase/capitalize/split/join/merge/copy/update/coerce). Pas de 'source'/'target' ici : mutate opère sur tout le document." + } +] diff --git a/pipeline.example.d/10_input_logstash-rsyslog.conf b/pipeline.example.d/10_input_logstash-rsyslog.conf new file mode 100644 index 0000000..257bcee --- /dev/null +++ b/pipeline.example.d/10_input_logstash-rsyslog.conf @@ -0,0 +1,10 @@ +# Rsyslog : input plugin +input { + udp { + host => "0.0.0.0" + port => 10514 + codec => "json" + type => "rsyslog" + ecs_compatibility => disabled + } +} diff --git a/pipeline.example.d/25_filter_logstash-rsyslog-dns-geoip.conf b/pipeline.example.d/25_filter_logstash-rsyslog-dns-geoip.conf new file mode 100644 index 0000000..c36e82a --- /dev/null +++ b/pipeline.example.d/25_filter_logstash-rsyslog-dns-geoip.conf @@ -0,0 +1,90 @@ +filter { + # Processing of IP addresses. + if [hostname] { + mutate { + add_field => { "[syslog][name]" => "%{[hostname]}" } + add_field => { "[syslog][inputname]" => "%{[inputname]}" } + add_field => { "[syslog][ip]" => "%{[host]}" } + add_field => { "[ifTable][index]" => "%{[interfaceindex]}" } + remove_field => [ "hostname","host","inputname","interfaceindex" ] + } + mutate{ + add_field => { "[host][ip]" => "%{[FromHost]}" } + + } + + } + + + + if [iTtable][index]{ + mutate { + add_field => { "[@metadata][in_if_key_sup]" => "%{[host][ip]}::ifName.%{[ifTable][index]}" } + } + translate { + dictionary_path => "/etc/logstash/dictionaries/ifName.yml" + source => "[@metadata][in_if_key_sup]" + target => "[ifTable][ifName]" + fallback => "index: %{[ifTable][index]}" + refresh_behaviour => "replace" + } + translate { + dictionary_path => "/etc/logstash/dictionaries/ifNamevlan.yml" + source => "[@metadata][in_if_key_sup]" + target => "[ifTable][ifNamevlan]" + fallback => "index: %{[ifTable][index]}" + refresh_behaviour => "replace" + } + translate { + dictionary_path => "/etc/logstash/dictionaries/ifSup.yml" + source => "[@metadata][in_if_key_sup]" + target => "[ifTable][ifSupervision]" + fallback => "false" + refresh_behaviour => "replace" + } + } + + if [host][ip] { + # If localhost then use the IP from the host source. + if [host][ip] == "127.0.0.1" { + mutate { + replace => { "[host][domain]" => "%{[host][ip]}" } + } + } else { + mutate { + add_field => { "[host][domain]" => "%{[host][ip]}"} + } + } + + # Resolve host IP address to hostname. + if [@metadata][resolve_ip2host] == "true" or [@metadata][resolve_ip2host] == "endpoints" { + dns { + reverse => [ "[host][domain]" ] + action => "replace" + nameserver => "${LOGSTASH_NAMESERVER:9.9.9.9}" + hit_cache_size => "${LOGSTASH_DNS_HIT_CACHE_SIZE:0}" + hit_cache_ttl => "${LOGSTASH_DNS_HIT_CACHE_TTL:60}" + failed_cache_size => "${LOGSTASH_DNS_FAILED_CACHE_SIZE:0}" + failed_cache_ttl => "${LOGSTASH_DNS_FAILED_CACHE_TTL:5}" + } + } + + mmdb { + source => "[host][ip]" + database => "/etc/logstash/dictionaries/XXXX.mmdb" + target => "[host]" + } + if [host][longitude] { + mutate { + add_field => { "[host][geo][location]" => "%{[host][latitude]},%{[host][longitude]}" } + add_field => { "[host][geo][tz][name]" => "%{[host][tz]}" } + } + } + if [host][WWW] { + mutate { + add_field => { "[WWW]" => "%{[host][WWW]}" } + } + } +# } + } +} diff --git a/pipeline.example.d/30_output_logstash-rsyslog.conf b/pipeline.example.d/30_output_logstash-rsyslog.conf new file mode 100644 index 0000000..042637f --- /dev/null +++ b/pipeline.example.d/30_output_logstash-rsyslog.conf @@ -0,0 +1,23 @@ +# Rsyslog : output plugin +output { + #stdout + #{ + # codec => rubydebug + #} + opensearch { + action => "index" + #ilm_enabled => false + hosts => [ "${O_Node1:localhost}", "${O_Node2:localhost}", "${O_Node3:localhost}", "${O_Node4:localhost}" ] + ssl => "${O_SSL_ENABLE:true}" + ssl_certificate_verification => "${O_SSL_VERIFY:false}" + user => "${O_USER:}" + password => "${O_PASSWD:}" + # Ou, à la place de user/password, un certificat client (mTLS, #100) ; + # rsyslogstach : --cacert / --tls-certificate / --tls-key. + #cacert => "/etc/logstash/certs/ca.pem" + #tls_certificate => "/etc/logstash/certs/client.pem" + #tls_key => "/etc/logstash/certs/client.key" +#document_type => "_doc" + index => "rsyslogstach-2.0.1-%{+YYYY.MM.dd}" + } +}