Life-NOC v1.0.0 : deux écrans, sans Icinga

Life-NOC devient une seule application Python (bibliothèque standard + python3-yaml,
python3-segno pour les codes QR), qui sert deux personnes :

- la personne aidée, sur son téléphone (/p/<id>/) : ce qui est à faire maintenant, en mots,
  un gros bouton « C'est fait », « Annuler » ; « Tout est fait pour aujourd'hui » sinon ;
- la personne qui configure, souvent un proche aidant (/config/) : supervision sans
  notification, éléments par formulaire, réserve, journal, étiquettes QR à imprimer.

Jamais noté = vert, avec « Quand l'avez-vous fait la dernière fois ? ». Un dossier par
personne, données hors de git. Retiré : Icinga 2, MariaDB/IDO, Apache, Icinga Web 2,
Business Process, générateurs, sondes Nagios, rôles Ansible. Contrat Set-OPS
setops-app.yml (norme 1). 19 tests : make tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Daniel Allaire 2026-11-15 22:51:28 -05:00
parent a64386db45
commit d862f57c89
92 changed files with 1897 additions and 7707 deletions

3
.gitignore vendored
View file

@ -5,3 +5,6 @@
__pycache__/
.ansible/
.vscode/
# Les données vivent hors du dépôt (setops-app.yml : etat.dossier)
donnees/

View file

@ -1,5 +1,31 @@
# CHANGELOG
## v1.0.0 — deux écrans, sans Icinga (2026-11-15)
Life-NOC devient une seule petite application Python, sans framework ni base de données, qui
sert deux personnes : celle qui est aidée (son téléphone) et celle qui configure (souvent un
proche aidant, qui voit sans être notifié).
- **L'écran de la personne aidée** (`/p/<id>/`) : ce qui est à faire maintenant, en mots et en
couleurs, un gros bouton « C'est fait », un bandeau « Noté… Annuler » ; « Tout est fait pour
aujourd'hui » et la prochaine chose quand rien n'est dû. Une page par élément, cible des codes QR.
- **L'écran de configuration et de supervision** (`/config/`) : les personnes, la supervision
par domaine, créer / modifier / retirer un élément par formulaire, puiser dans la réserve, le
journal, les étiquettes QR à imprimer (`python3-segno`).
- **Jamais noté = vert**, avec « Quand l'avez-vous fait la dernière fois ? » ; le rouge reste au
retard et aux données illisibles.
- **Un dossier par personne** (`donnees/personnes/<id>/`) et une réserve commune ; données hors de git.
- Retiré : Icinga 2, MariaDB/IDO, Apache, Icinga Web 2, Business Process, les générateurs de
configuration, les sondes Nagios, les rôles Ansible. Le calcul des états, écrit deux fois
(`lib/` et `checks/`), n'existe plus qu'à un endroit : `lifenoc/moteur.py`.
- Définitions : une mesure et trois seuils par élément (`depuis`, `avant`, `km`, `reste`), au lieu
d'une vingtaine de lignes ; `make migrer` verse les 178 de la preuve de concept dans la réserve,
sans leurs valeurs (jamais réelles).
- Dates au fuseau de la personne (`America/Toronto`), plus en UTC.
- Contrat Set-OPS `setops-app.yml` (norme 1, dépendances Debian). Tests : `make tests`.
- Changement de sens : un stock suffisant est gris (rien à faire), plus vert.
- Pas encore : l'identité (Keycloak pour l'aidant, lien jumelé pour la personne aidée).
## v0.2
POC mock-first fonctionnelle.

128
Makefile
View file

@ -1,105 +1,49 @@
SHELL := /bin/bash
.DEFAULT_GOAL := help
.DEFAULT_GOAL := aide
PYTHON ?= python3
ANSIBLE_PLAYBOOK ?= ansible-playbook
INVENTORY ?= ansible/inventory
PLAYBOOK ?= ansible/site.yml
ARCHIVE ?= life-noc-from-scratch-debian12.zip
PROJECT_NAME ?= life-noc
PYTHON ?= python3
DONNEES ?= donnees
PORT ?= 8787
PERSONNE ?=
LIFENOC := LIFENOC_DONNEES=$(DONNEES) $(PYTHON) -m lifenoc
GENERATORS := scripts/generate_services.py scripts/generate_bpm.py
CHECKS := checks/check_life_noc_mock.sh checks/check_echeance_vie.sh
ICINGA_FILES := $(wildcard icinga/commands/*.conf) $(wildcard icinga/hosts/*.conf) $(wildcard icinga/templates/*.conf) $(wildcard icinga/services/*.conf) $(wildcard icinga/servicegroups/*.conf)
.PHONY: aide servir personnes etat tout verifier tests migrer
.PHONY: help all generate regen services bpm validate validate-yaml validate-python validate-shell validate-generated check mock-ok mock-warning mock-critical clean bootstrap deploy deploy-no-bpm deploy-with-bpm package inventory-example vars-example info
help:
@echo "Life-NOC - cibles disponibles"
aide:
@echo "Life-NOC — voir clair, prioriser juste, agir au bon endroit"
@echo
@echo " make generate Génère services Icinga + BPM"
@echo " make validate Valide YAML, Python, shell et artefacts générés"
@echo " make check Génère puis valide"
@echo " make bootstrap Déploie la plateforme complète depuis Debian 12 vanille"
@echo " make deploy Alias de bootstrap"
@echo " make deploy-with-bpm Déploie explicitement avec artefact BPM"
@echo " make mock-ok Teste la sonde mock en état OK"
@echo " make mock-warning Teste la sonde mock en état WARNING"
@echo " make mock-critical Teste la sonde mock en état CRITICAL"
@echo " make package Crée une archive zip du dépôt"
@echo " make inventory-example Rappelle comment préparer l'inventaire"
@echo " make vars-example Rappelle comment préparer les variables"
@echo " make info Affiche les variables utiles"
@echo " make servir les deux écrans sur http://127.0.0.1:$(PORT)/"
@echo " (/config/ pour configurer, /p/<id>/ pour le téléphone)"
@echo " make personnes les personnes suivies"
@echo " make etat PERSONNE=<id> ce qui mérite l'attention, dans le terminal"
@echo " make tout PERSONNE=<id> tout, le pas-encore compris"
@echo " make verifier relit toutes les données (code 1 si faute)"
@echo " make tests les tests (bibliothèque standard seulement)"
@echo " make migrer ANCIEN=… verse un ancien Life-NOC (domains.yaml) dans la réserve"
@echo
@echo "Variables surchargables : INVENTORY=..., PLAYBOOK=..., ARCHIVE=..."
@echo " Noter un geste : $(PYTHON) -m lifenoc noter <id> revue/revue-hebdomadaire-priorites fait"
@echo " Variables : DONNEES=$(DONNEES) PORT=$(PORT)"
all: check
regen: generate
servir:
$(LIFENOC) servir --port $(PORT)
generate: services bpm
personnes:
@$(LIFENOC) personnes
services: domains.yaml scripts/generate_services.py
$(PYTHON) scripts/generate_services.py
etat:
@test -n "$(PERSONNE)" || { echo "PERSONNE=<id> requis (make personnes)"; exit 2; }
@$(LIFENOC) etat "$(PERSONNE)"
bpm: domains.yaml scripts/generate_bpm.py
$(PYTHON) scripts/generate_bpm.py
tout:
@test -n "$(PERSONNE)" || { echo "PERSONNE=<id> requis (make personnes)"; exit 2; }
@$(LIFENOC) etat --tout "$(PERSONNE)"
validate: validate-yaml validate-python validate-shell validate-generated
verifier:
@$(LIFENOC) verifier
validate-yaml: domains.yaml
@$(PYTHON) -c 'import yaml, pathlib; p = pathlib.Path("domains.yaml"); data = yaml.safe_load(p.read_text(encoding="utf-8")); assert isinstance(data, dict) and isinstance(data.get("domains"), dict), "domains.yaml invalide: clé racine domains requise"; print("YAML valide: domains.yaml")'
tests:
@PYTHONDONTWRITEBYTECODE=1 $(PYTHON) -m unittest discover -s tests
validate-python: $(GENERATORS)
@$(PYTHON) -m py_compile $(GENERATORS)
@echo "Python OK"
validate-shell: $(CHECKS)
@bash -n $(CHECKS)
@echo "Shell OK"
validate-generated: $(ICINGA_FILES) bpm/Life-NOC.conf
@grep -R 'check_life_noc_mock' icinga/templates icinga/commands icinga/services >/dev/null
@$(PYTHON) -c 'import pathlib; p = pathlib.Path("bpm/Life-NOC.conf"); text = p.read_text(encoding="utf-8"); lines = [l.strip() for l in text.splitlines() if l.strip()]; assert any(l == "### Business Process Config File ###" for l in lines), "bpm/Life-NOC.conf invalide: en-tête BPM absent"; assert any(l.startswith("display 1;") for l in lines), "bpm/Life-NOC.conf invalide: aucun display absent"; print("Artefacts générés valides")'
check: generate validate
mock-ok:
@bash checks/check_life_noc_mock.sh --state OK --message "Sous contrôle" --item-name "demo" --date "2026-03-13"
mock-warning:
@bash checks/check_life_noc_mock.sh --state WARNING --message "Attention requise" --item-name "demo" --date "2026-03-13"; test $$? -eq 1
mock-critical:
@bash checks/check_life_noc_mock.sh --state CRITICAL --message "Action requise" --item-name "demo" --date "2026-03-13"; test $$? -eq 2
bootstrap: check
$(ANSIBLE_PLAYBOOK) -i $(INVENTORY) $(PLAYBOOK)
deploy: bootstrap
deploy-no-bpm: bootstrap
deploy-with-bpm: check
$(ANSIBLE_PLAYBOOK) -i $(INVENTORY) $(PLAYBOOK) -e life_noc_bpm_deploy_enabled=true
package: check
@rm -f $(ARCHIVE)
@zip -qr $(ARCHIVE) . -x '*.git*' -x '__pycache__/*' -x '*.pyc' -x '$(ARCHIVE)'
@echo "Archive créée: $(ARCHIVE)"
clean:
rm -f $(ARCHIVE) bpm/Life-NOC.conf
inventory-example:
@echo "Copier ansible/inventory.example vers ansible/inventory puis ajuster l'hôte, l'adresse et l'utilisateur ansible."
vars-example:
@echo "Copier ansible/group_vars/all.yml.example vers ansible/group_vars/all.yml puis remplacer TOUS les mots de passe par les tiens."
info:
@echo "PROJECT_NAME=$(PROJECT_NAME)"
@echo "PYTHON=$(PYTHON)"
@echo "ANSIBLE_PLAYBOOK=$(ANSIBLE_PLAYBOOK)"
@echo "INVENTORY=$(INVENTORY)"
@echo "PLAYBOOK=$(PLAYBOOK)"
@echo "ARCHIVE=$(ARCHIVE)"
migrer:
@test -n "$(ANCIEN)" || { echo "ANCIEN=<chemin de l'ancien dépôt> requis"; exit 2; }
$(LIFENOC) migrer "$(ANCIEN)"

234
README.md
View file

@ -1,182 +1,112 @@
# Life-NOC
Life-NOC applique la logique d'un centre d'opérations (NOC) à la vie quotidienne.
**Voir clair, prioriser juste, agir au bon endroit.**
Le but du projet est de transformer la charge mentale invisible en état observable, afin de savoir rapidement ce qui est sous contrôle, ce qui approche d'une échéance et ce qui mérite de l'attention.
Life-NOC applique la logique d'un centre d'opérations à la vie quotidienne. Il sort de la tête ce
qui revient et qu'on ne doit pas oublier — une revue, un pilulier, un entretien, une échéance, un
stock — et montre, au bon moment, ce qui mérite une action. Il n'agit jamais à la place de la
personne : « une machine qui aide à ne pas perdre le fil ». Voir `docs/vision/`.
## Cible de ce dépôt
Il sert une personne qui a du mal à tout garder en tête (un TDA, par exemple), et les gens qui
accompagnent une personne semi-autonome (un parent âgé et sa famille).
Cette version vise désormais explicitement le scénario suivant :
## Deux écrans, deux personnes
> **Debian 12 vanille + utilisateur `ansible` + clé SSH = plateforme Life-NOC complète**
| | La personne aidée | La personne qui configure |
|---|---|---|
| Où | le petit écran de son téléphone : `/p/<id>/` | un ordinateur : `/config/` |
| Ce qu'elle voit | ce qui est à faire maintenant, en mots ; « Tout est fait pour aujourd'hui » sinon | tout, par domaine, avec la mécanique : seuils, dernières valeurs, journal |
| Ce qu'elle fait | « C'est fait », noter une valeur, « Annuler » | créer et régler les éléments, puiser dans la réserve, imprimer les codes QR |
Le dépôt automatise :
Les deux rôles peuvent revenir à la même personne : le dimanche, l'esprit clair, on configure
pour soi de la semaine. La personne qui configure **voit seulement** : aucune notification ne part.
- l'ajout du dépôt officiel Icinga
- l'installation de MariaDB
- l'installation d'Icinga 2
- l'installation et la configuration d'IDO MySQL
- l'installation d'Apache et d'Icinga Web 2
- l'installation du module Business Process
- le déploiement de Life-NOC
- la génération des services Icinga et de l'artefact BPM
### Le premier niveau, puis le second
## État fonctionnel
Comme dans un centre d'opérations : la personne aidée agit (premier niveau) ; le proche aidant
regarde la supervision et n'intervient que si le premier niveau n'a pas suffi (second niveau).
La modélisation métier reste **mock-first** :
## Les quatre états
- les domaines et éléments de vie sont décrits dans `domains.yaml`
- les services Icinga sont générés automatiquement
- les sondes sont **mockées** par défaut
- l'état par défaut est **OK**
| Couleur | Mot (écran de la personne aidée) | Sens |
|---|---|---|
| gris | Pas encore | pas encore dû — l'écran le tait |
| vert | À faire | c'est le bon moment ; ou jamais noté : « Quand l'avez-vous fait la dernière fois ? » |
| orange | À faire vite | il faut presser |
| rouge | En retard | en retard, ou donnée illisible |
Autrement dit, la POC valide :
## Les mesures
- le modèle déclaratif
- la génération des artefacts
- le bootstrap complet de la plateforme
- le déploiement automatisé par Ansible
- l'affichage Icinga Web 2
- l'évolution future vers de vraies sondes
Une mesure par élément, trois seuils `[à faire, pressé, en retard]` :
## Structure du dépôt
| Mesure | Dans l'écran de configuration | Exemple |
|---|---|---|
| `depuis` | Revient régulièrement | `[5, 7, 10]` jours depuis la dernière fois |
| `avant` | Échéance | `[60, 30, 7]` jours avant l'échéance notée |
| `km` | Kilométrage | `[7000, 8000, 9000]` km depuis le dernier entretien |
| `reste` | Quantité qui reste | `[60, 50, 25]` avec une unité (`%`, `litres`, `V`…) |
```text
life-noc/
├── ansible/
│ ├── group_vars/
│ ├── inventory.example
│ ├── roles/
│ │ ├── base/
│ │ ├── mariadb/
│ │ ├── icinga2/
│ │ ├── icingaweb2/
│ │ ├── businessprocess/
│ │ └── life_noc/
│ ├── deploy_life_noc.yml
│ └── site.yml
├── bpm/
├── checks/
├── docs/
├── icinga/
│ ├── commands/
│ ├── hosts/
│ ├── services/
│ └── templates/
├── scripts/
├── domains.yaml
├── Makefile
└── ansible.cfg
```
## Démarrer
## Source of truth
Le fichier central est :
- `domains.yaml`
Chaque entrée décrit un élément Life-NOC avec :
- `name` : identifiant lisible
- `date` : métadonnée d'échéance ou de repère
- `notes` : contexte humain
- `mock_state` : état simulé (`OK`, `WARNING`, `CRITICAL`) — optionnel
- `mock_message` : message simulé — optionnel
Par défaut :
- `mock_state = OK`
- `mock_message = Sous contrôle`
## Déploiement from scratch
Depuis la machine de contrôle Debian 12 :
Debian 13, `python3`, `python3-yaml` ; `python3-segno` pour les codes QR. Rien d'autre.
```bash
cp ansible/inventory.example ansible/inventory
cp ansible/group_vars/all.yml.example ansible/group_vars/all.yml
make servir # http://127.0.0.1:8787/
```
Modifier ensuite :
1. Ouvrir `/config/`, ajouter une personne.
2. **Commencer petit** : « Puiser dans la réserve » une dizaine d'éléments, ou en créer.
3. Ouvrir `/p/<id>/` sur le téléphone de la personne, l'ajouter à son écran d'accueil.
4. « Codes QR » : imprimer, coller chaque étiquette là où la chose se fait (la génératrice, le
pilulier, la voiture). Le code ouvre la page de l'élément ; un toucher, c'est noté.
5. Au bout d'un mois, retirer ce qui n'a jamais servi : c'est du bruit.
- l'hôte cible dans `ansible/inventory`
- les mots de passe dans `ansible/group_vars/all.yml`
## Les données
Puis lancer :
Des fichiers texte, hors de git, dans `donnees/` (ou `$LIFENOC_DONNEES`) :
```
donnees/
reserve.yaml des éléments prêts à l'emploi
personnes/<id>/
personne.yaml {nom: …}
elements.yaml ce qui est suivi (l'écran de configuration l'écrit ; la main aussi)
intrants.yaml la dernière valeur de chaque élément
journal.tsv chaque geste, une ligne, jamais réécrit
```
Relus à chaque page : une modification à la main ne demande aucun redémarrage. Le fuseau des
dates vient de `$LIFENOC_FUSEAU` (défaut `America/Toronto`).
## Sans navigateur
```bash
make bootstrap
make personnes
make etat PERSONNE=daniel # ce qui mérite l'attention
python3 -m lifenoc noter daniel revue/revue-hebdomadaire-priorites fait
make verifier # relit toutes les données (code 1 si faute)
make tests
```
ou :
API : `GET /api/<id>/etats` ; `POST /api/<id>/element/<domaine>/<élément>` avec
`{"geste": "valeur", "saisie": "42", "par": "capteur"}` — pour une sonde ou un capteur.
## Sécurité
L'application n'a pas d'authentification : elle écoute en `127.0.0.1`, et c'est ce qui la sert
(nginx, le frontal de Set-OPS, un tunnel) qui décide qui la joint. Les identités (le proche
aidant par Keycloak, la personne aidée par un lien jumelé à son téléphone) sont la prochaine étape.
## Dans un locataire Set-OPS
`setops-app.yml` est le contrat : `execution: python`, dépendances Debian, les données dans
`donnees/`. Set-OPS la déploie à une étiquette `vX.Y.Z`, la sauvegarde et la supervise par `/sante`.
## Depuis l'ancien Life-NOC (Icinga)
```bash
ansible-playbook -i ansible/inventory ansible/site.yml
make migrer ANCIEN=<chemin d'un dépôt qui porte domains.yaml>
```
## Génération locale
### Générer les services Icinga
```bash
python3 scripts/generate_services.py
```
### Générer l'artefact BPM
```bash
python3 scripts/generate_bpm.py
```
## Makefile
Le dépôt fournit un `Makefile` pour les gestes courants.
Exemples :
```bash
make generate
make validate
make check
make bootstrap
make deploy-with-bpm
make package
```
Pour la liste complète :
```bash
make help
```
## Accès web attendus
Une fois le playbook terminé, les chemins utiles sont typiquement :
```text
/icingaweb2
/icingaweb2/monitoring/host/show?host=life-noc
/icingaweb2/monitoring/list/services?host_name=life-noc
```
## Documentation complémentaire
- `docs/concept.md`
- `docs/architecture.md`
- `docs/deploiement-from-scratch.md`
## Philosophie de cette POC
Cette POC ne prétend pas encore mesurer le réel.
Elle sert à construire proprement :
- l'ossature du système
- la hiérarchie des domaines
- les conventions de nommage
- la chaîne de génération
- le bootstrap serveur
- le déploiement
- l'intégration Icinga Web 2
Les vraies sondes viendront plus tard, en remplacement progressif des mocks.
Verse les 178 définitions dans la réserve. Les anciennes valeurs ne sont pas reprises : elles
n'ont jamais été réelles.

View file

@ -1,9 +0,0 @@
[defaults]
inventory = ansible/inventory
host_key_checking = False
retry_files_enabled = False
interpreter_python = auto_silent
stdout_callback = yaml
[ssh_connection]
pipelining = True

View file

@ -1 +0,0 @@
- import_playbook: site.yml

View file

@ -1,22 +0,0 @@
life_noc_fqdn: c7-life-noc-01
life_noc_admin_ui_enabled: true
life_noc_admin_user: icingadmin
life_noc_admin_password: l1f3_N0C_ADM
life_noc_db_root_socket: /run/mysqld/mysqld.sock
life_noc_db_icinga_name: icinga
life_noc_db_icinga_user: icinga
life_noc_db_icinga_password: l1f3_N0C_DB
life_noc_db_web_name: icingaweb2
life_noc_db_web_user: icingaweb2
life_noc_db_web_password: l1f3_N0C_WEB_DB
life_noc_icinga_repo_enabled: true
life_noc_icinga_repo_distribution: icinga-bookworm
life_noc_icinga_keyring_deb_url: https://packages.icinga.com/icinga-archive-keyring_latest+debian12.deb
life_noc_businessprocess_enabled: true
life_noc_businessprocess_version: v2.5.2
life_noc_businessprocess_repo: https://github.com/Icinga/icingaweb2-module-businessprocess.git

View file

@ -1,21 +0,0 @@
life_noc_fqdn: c7-life-noc-01
life_noc_admin_user: icingadmin
life_noc_admin_password: CHANGE_ME_NOW
life_noc_db_root_socket: /run/mysqld/mysqld.sock
life_noc_db_icinga_name: icinga
life_noc_db_icinga_user: icinga
life_noc_db_icinga_password: CHANGE_ME_ICINGA_DB
life_noc_db_web_name: icingaweb2
life_noc_db_web_user: icingaweb2
life_noc_db_web_password: CHANGE_ME_WEB_DB
life_noc_icinga_repo_enabled: true
life_noc_icinga_repo_distribution: icinga-bookworm
life_noc_icinga_keyring_deb_url: https://packages.icinga.com/icinga-archive-keyring_latest+debian12.deb
life_noc_businessprocess_enabled: true
life_noc_businessprocess_version: v2.5.2
life_noc_businessprocess_repo: https://github.com/Icinga/icingaweb2-module-businessprocess.git

View file

@ -1,2 +0,0 @@
[icinga]
c7-life-noc-01 ansible_host=Life-NOC.chezlepro.ca ansible_user=ansible

View file

@ -1,2 +0,0 @@
[icinga]
life-noc-01 ansible_host=192.0.2.10 ansible_user=ansible

View file

@ -1,3 +0,0 @@
life_noc_icinga_repo_enabled: true
life_noc_icinga_repo_distribution: icinga-bookworm
life_noc_icinga_keyring_deb_url: https://packages.icinga.com/icinga-archive-keyring_latest+debian12.deb

View file

@ -1,67 +0,0 @@
- name: install base prerequisites
ansible.builtin.apt:
name:
- apt-transport-https
- ca-certificates
- curl
- git
- gnupg
- python3
- python3-yaml
- unzip
- wget
state: present
update_cache: true
- name: download icinga archive keyring package
ansible.builtin.get_url:
url: "{{ life_noc_icinga_keyring_deb_url }}"
dest: /tmp/icinga-archive-keyring.deb
mode: "0644"
when: life_noc_icinga_repo_enabled | bool
- name: install icinga archive keyring package
ansible.builtin.apt:
deb: /tmp/icinga-archive-keyring.deb
state: present
when: life_noc_icinga_repo_enabled | bool
- name: verify icinga keyring exists
ansible.builtin.stat:
path: /usr/share/keyrings/icinga-archive-keyring.gpg
register: icinga_keyring_file
- name: fail if icinga keyring is missing
ansible.builtin.fail:
msg: "La keyring Icinga /usr/share/keyrings/icinga-archive-keyring.gpg est absente après installation."
when: not icinga_keyring_file.stat.exists
- name: configure official icinga apt repository
ansible.builtin.apt_repository:
repo: "deb [signed-by=/usr/share/keyrings/icinga-archive-keyring.gpg] https://packages.icinga.com/debian {{ life_noc_icinga_repo_distribution }} main"
filename: icinga
state: present
update_cache: false
when: life_noc_icinga_repo_enabled | bool
- name: configure official icinga apt source repository
ansible.builtin.apt_repository:
repo: "deb-src [signed-by=/usr/share/keyrings/icinga-archive-keyring.gpg] https://packages.icinga.com/debian {{ life_noc_icinga_repo_distribution }} main"
filename: icinga
state: present
update_cache: false
when: life_noc_icinga_repo_enabled | bool
- name: verify icinga repository file exists
ansible.builtin.stat:
path: /etc/apt/sources.list.d/icinga.list
register: icinga_repo_file
- name: fail if icinga repository file is missing
ansible.builtin.fail:
msg: "Le fichier /etc/apt/sources.list.d/icinga.list est absent."
when: not icinga_repo_file.stat.exists
- name: update apt cache after icinga repository configuration
ansible.builtin.apt:
update_cache: true

View file

@ -1,4 +0,0 @@
life_noc_businessprocess_enabled: true
life_noc_businessprocess_version: v2.5.2
life_noc_businessprocess_repo: https://github.com/Icinga/icingaweb2-module-businessprocess.git
life_noc_businessprocess_module_dir: /usr/share/icingaweb2/modules/businessprocess

View file

@ -1,4 +0,0 @@
- name: restart apache2
ansible.builtin.service:
name: apache2
state: restarted

View file

@ -1,36 +0,0 @@
- name: install icinga web php libraries required by businessprocess
ansible.builtin.apt:
name:
- icinga-php-library
- icinga-php-thirdparty
state: present
update_cache: true
when: life_noc_businessprocess_enabled | bool
- name: install businessprocess module from git
ansible.builtin.git:
repo: "{{ life_noc_businessprocess_repo }}"
dest: "{{ life_noc_businessprocess_module_dir }}"
version: "{{ life_noc_businessprocess_version }}"
force: true
when: life_noc_businessprocess_enabled | bool
notify: restart apache2
- name: ensure businessprocess config directories exist
ansible.builtin.file:
path: "{{ item }}"
state: directory
owner: root
group: icingaweb2
mode: "2770"
loop:
- /etc/icingaweb2/modules/businessprocess
- /etc/icingaweb2/modules/businessprocess/processes
when: life_noc_businessprocess_enabled | bool
- name: enable businessprocess module
ansible.builtin.command: icingacli module enable businessprocess
args:
creates: /etc/icingaweb2/enabledModules/businessprocess
when: life_noc_businessprocess_enabled | bool
notify: restart apache2

View file

@ -1,6 +0,0 @@
life_noc_db_root_socket: /run/mysqld/mysqld.sock
life_noc_db_icinga_name: icinga
life_noc_db_icinga_user: icinga
life_noc_db_icinga_password: icinga-change-me
life_noc_icinga_ido_host: 127.0.0.1
life_noc_icinga_ido_port: 3306

View file

@ -1,7 +0,0 @@
- name: restart icinga2
ansible.builtin.service:
name: icinga2
state: restarted
- name: validate icinga2
ansible.builtin.command: icinga2 daemon -C

View file

@ -1,63 +0,0 @@
- name: install icinga2 packages
ansible.builtin.apt:
name:
- icinga2
- icinga2-ido-mysql
- monitoring-plugins-basic
- monitoring-plugins-common
state: present
update_cache: true
- name: ensure icinga database exists
ansible.builtin.shell: |
mysql --socket={{ life_noc_db_root_socket }} -Nse "CREATE DATABASE IF NOT EXISTS {{ life_noc_db_icinga_name }} CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;"
changed_when: false
- name: ensure icinga database user exists and has grants
ansible.builtin.shell: |
mysql --socket={{ life_noc_db_root_socket }} -Nse "GRANT ALTER, CREATE, SELECT, INSERT, UPDATE, DELETE, DROP, CREATE VIEW, INDEX, EXECUTE ON {{ life_noc_db_icinga_name }}.* TO '{{ life_noc_db_icinga_user }}'@'localhost' IDENTIFIED BY '{{ life_noc_db_icinga_password }}'; FLUSH PRIVILEGES;"
changed_when: false
- name: check whether icinga ido schema is already imported
ansible.builtin.shell: |
mysql --socket={{ life_noc_db_root_socket }} -Nse "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='{{ life_noc_db_icinga_name }}' AND table_name='icinga_programstatus';"
register: life_noc_icinga_schema_check
changed_when: false
- name: import icinga ido schema
ansible.builtin.shell: |
mysql --socket={{ life_noc_db_root_socket }} {{ life_noc_db_icinga_name }} < /usr/share/icinga2-ido-mysql/schema/mysql.sql
when: life_noc_icinga_schema_check.stdout | trim == '0'
- name: install ido mysql feature configuration
ansible.builtin.template:
src: ido-mysql.conf.j2
dest: /etc/icinga2/features-available/ido-mysql.conf
owner: root
group: root
mode: "0644"
notify:
- validate icinga2
- restart icinga2
- name: enable ido-mysql feature
ansible.builtin.command: icinga2 feature enable ido-mysql
args:
creates: /etc/icinga2/features-enabled/ido-mysql.conf
notify:
- validate icinga2
- restart icinga2
- name: enable command feature
ansible.builtin.command: icinga2 feature enable command
args:
creates: /etc/icinga2/features-enabled/command.conf
notify:
- validate icinga2
- restart icinga2
- name: enable and start icinga2
ansible.builtin.service:
name: icinga2
enabled: true
state: started

View file

@ -1,13 +0,0 @@
/**
* Managed by Ansible (Life-NOC)
*/
library "db_ido_mysql"
object IdoMysqlConnection "ido-mysql" {
user = "{{ life_noc_db_icinga_user }}"
password = "{{ life_noc_db_icinga_password }}"
host = "{{ life_noc_icinga_ido_host }}"
port = {{ life_noc_icinga_ido_port }}
database = "{{ life_noc_db_icinga_name }}"
enable_ha = false
}

View file

@ -1,11 +0,0 @@
life_noc_db_root_socket: /run/mysqld/mysqld.sock
life_noc_db_web_name: icingaweb2
life_noc_db_web_user: icingaweb2
life_noc_db_web_password: icingaweb2-change-me
life_noc_db_icinga_name: icinga
life_noc_db_icinga_user: icinga
life_noc_db_icinga_password: icinga-change-me
life_noc_admin_user: icingadmin
life_noc_admin_password: CHANGE_ME_NOW
life_noc_fqdn: localhost
life_noc_icinga2_command_pipe: /var/run/icinga2/cmd/icinga2.cmd

View file

@ -1,4 +0,0 @@
- name: restart apache2
ansible.builtin.service:
name: apache2
state: restarted

View file

@ -1,121 +0,0 @@
- name: install icinga web and apache packages
ansible.builtin.apt:
name:
- apache2
- icingaweb2
- libapache2-mod-php8.2
- php8.2-curl
- php8.2-gd
- php8.2-intl
- php8.2-mbstring
- php8.2-mysql
- php8.2-xml
state: present
update_cache: true
- name: ensure apache2 is enabled and started
ansible.builtin.service:
name: apache2
enabled: true
state: started
- name: add web and monitoring users to icingaweb2 group
ansible.builtin.user:
name: "{{ item }}"
groups: icingaweb2
append: true
loop:
- www-data
- nagios
- name: ensure icingaweb2 database exists
ansible.builtin.shell: |
mysql --socket={{ life_noc_db_root_socket }} -Nse "CREATE DATABASE IF NOT EXISTS {{ life_noc_db_web_name }} CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;"
changed_when: false
- name: ensure icingaweb2 database user exists and has grants
ansible.builtin.shell: |
mysql --socket={{ life_noc_db_root_socket }} -Nse "GRANT SELECT, INSERT, UPDATE, DELETE, DROP, CREATE VIEW, INDEX, EXECUTE ON {{ life_noc_db_web_name }}.* TO '{{ life_noc_db_web_user }}'@'localhost' IDENTIFIED BY '{{ life_noc_db_web_password }}'; FLUSH PRIVILEGES;"
changed_when: false
- name: check whether icingaweb2 schema is already imported
ansible.builtin.shell: |
mysql --socket={{ life_noc_db_root_socket }} -Nse "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='{{ life_noc_db_web_name }}' AND table_name='icingaweb_user';"
register: life_noc_web_schema_check
changed_when: false
- name: import icingaweb2 schema
ansible.builtin.shell: |
mysql --socket={{ life_noc_db_root_socket }} {{ life_noc_db_web_name }} < /usr/share/icingaweb2/schema/mysql.schema.sql
args:
executable: /bin/bash
when: life_noc_web_schema_check.stdout | trim == '0'
- name: generate icingaweb2 admin password hash
ansible.builtin.command: >-
php -r 'echo password_hash(getenv("LIFE_NOC_ADMIN_PASSWORD"), PASSWORD_DEFAULT);'
environment:
LIFE_NOC_ADMIN_PASSWORD: "{{ life_noc_admin_password }}"
register: life_noc_admin_password_hash
changed_when: false
no_log: true
- name: ensure icingaweb2 admin user exists with expected password
ansible.builtin.shell: |
mysql --socket={{ life_noc_db_root_socket }} {{ life_noc_db_web_name }} <<'SQL'
INSERT INTO icingaweb_user (name, active, password_hash)
VALUES ('{{ life_noc_admin_user }}', 1, '{{ life_noc_admin_password_hash.stdout }}')
ON DUPLICATE KEY UPDATE
active = VALUES(active),
password_hash = VALUES(password_hash);
SQL
no_log: true
- name: ensure icingaweb2 config directories exist
ansible.builtin.file:
path: "{{ item.path }}"
state: directory
owner: root
group: icingaweb2
mode: "{{ item.mode }}"
loop:
- { path: '/etc/icingaweb2', mode: '2770' }
- { path: '/etc/icingaweb2/enabledModules', mode: '2770' }
- { path: '/etc/icingaweb2/modules', mode: '2770' }
- { path: '/etc/icingaweb2/modules/monitoring', mode: '2770' }
- { path: '/etc/icingaweb2/preferences', mode: '2770' }
- name: deploy icingaweb2 core configuration
ansible.builtin.template:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
owner: root
group: icingaweb2
mode: "0660"
loop:
- { src: 'config.ini.j2', dest: '/etc/icingaweb2/config.ini' }
- { src: 'resources.ini.j2', dest: '/etc/icingaweb2/resources.ini' }
- { src: 'authentication.ini.j2', dest: '/etc/icingaweb2/authentication.ini' }
- { src: 'roles.ini.j2', dest: '/etc/icingaweb2/roles.ini' }
notify: restart apache2
- name: deploy monitoring module configuration
ansible.builtin.template:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
owner: root
group: icingaweb2
mode: "0660"
loop:
- { src: 'backends.ini.j2', dest: '/etc/icingaweb2/modules/monitoring/backends.ini' }
- { src: 'commandtransports.ini.j2', dest: '/etc/icingaweb2/modules/monitoring/commandtransports.ini' }
notify: restart apache2
- name: enable icingaweb2 modules
ansible.builtin.command: "icingacli module enable {{ item }}"
args:
creates: "/etc/icingaweb2/enabledModules/{{ item }}"
loop:
- monitoring
- doc
notify: restart apache2

View file

@ -1,3 +0,0 @@
[icingaweb2]
backend = "db"
resource = "icingaweb2"

View file

@ -1,3 +0,0 @@
[icinga2_ido_mysql]
type = "ido"
resource = "icinga2_ido_mysql"

View file

@ -1,3 +0,0 @@
[icinga2]
transport = "local"
path = "/run/icinga2/cmd/icinga2.cmd"

View file

@ -1,11 +0,0 @@
[global]
show_stacktraces = "0"
config_backend = "db"
config_resource = "icingaweb2"
[logging]
log = "syslog"
level = "ERROR"
[themes]
default = "Icinga"

View file

@ -1,21 +0,0 @@
[icingaweb2]
type = "db"
db = "mysql"
host = "localhost"
port = "3306"
dbname = "{{ life_noc_db_web_name }}"
username = "{{ life_noc_db_web_user }}"
password = "{{ life_noc_db_web_password }}"
charset = "utf8mb4"
use_ssl = "0"
[icinga2_ido_mysql]
type = "db"
db = "mysql"
host = "localhost"
port = "3306"
dbname = "{{ life_noc_db_icinga_name }}"
username = "{{ life_noc_db_icinga_user }}"
password = "{{ life_noc_db_icinga_password }}"
charset = "latin1"
use_ssl = "0"

View file

@ -1,3 +0,0 @@
[administrators]
users = "{{ life_noc_admin_user }}"
permissions = "*"

View file

@ -1,12 +0,0 @@
life_noc_project_root: /opt/life-noc
life_noc_icinga_conf_root: /etc/icinga2/conf.d/life-noc
life_noc_plugin_dir: /usr/lib/nagios/plugins
life_noc_validate_icinga: true
life_noc_reload_icinga: true
life_noc_bpm_deploy_enabled: false
life_noc_bpm_destination_dir: /etc/icingaweb2/modules/businessprocess/processes
life_noc_bpm_target_file: /etc/icingaweb2/modules/businessprocess/processes/Life-NOC.conf
life_noc_public_base_url: "http://{{ ansible_host | default(inventory_hostname) }}:8787"
life_noc_owner: root
life_noc_group: root
life_noc_admin_ui_enabled: false

View file

@ -1,20 +0,0 @@
- name: validate icinga
ansible.builtin.command: icinga2 daemon -C
when: life_noc_validate_icinga | bool
listen: validate and reload icinga
- name: reload icinga
ansible.builtin.service:
name: icinga2
state: reloaded
when: life_noc_reload_icinga | bool
listen: validate and reload icinga
- name: reload systemd
ansible.builtin.systemd:
daemon_reload: true
- name: restart life-noc input api
ansible.builtin.service:
name: life-noc-input-api
state: restarted

View file

@ -1,253 +0,0 @@
---
- name: install minimal dependencies
ansible.builtin.apt:
name:
- python3
- python3-yaml
state: present
update_cache: true
- name: remove legacy life-noc subdirectory under icinga conf.d
ansible.builtin.file:
path: /etc/icinga2/conf.d/life-noc
state: absent
notify:
- validate icinga
- reload icinga
- name: find previously deployed flattened life-noc config files
ansible.builtin.find:
paths: /etc/icinga2/conf.d
patterns: "life-noc-*"
file_type: file
register: life_noc_flattened_files
- name: remove previously deployed flattened life-noc config files
ansible.builtin.file:
path: "{{ item.path }}"
state: absent
loop: "{{ life_noc_flattened_files.files }}"
notify:
- validate icinga
- reload icinga
- name: create project root
ansible.builtin.file:
path: "{{ life_noc_project_root }}"
state: directory
owner: root
group: root
mode: "0755"
- name: copy project files
ansible.builtin.copy:
src: "{{ playbook_dir }}/../"
dest: "{{ life_noc_project_root }}/"
owner: root
group: root
mode: preserve
notify:
- restart life-noc input api
- name: generate icinga services from domains
ansible.builtin.command:
cmd: python3 scripts/generate_services.py
chdir: "{{ life_noc_project_root }}"
environment:
LIFE_NOC_PUBLIC_BASE_URL: "{{ life_noc_public_base_url }}"
changed_when: true
- name: generate bpm from domains
ansible.builtin.command:
cmd: python3 scripts/generate_bpm.py
chdir: "{{ life_noc_project_root }}"
changed_when: true
##################################
- name: find life-noc command files on target
ansible.builtin.find:
paths: "{{ life_noc_project_root }}/icinga/commands"
patterns: "*.conf"
file_type: file
register: life_noc_command_files
- name: deploy life-noc command files into icinga conf.d
ansible.builtin.copy:
src: "{{ item.path }}"
dest: "/etc/icinga2/conf.d/life-noc-command-{{ item.path | basename }}"
remote_src: true
owner: root
group: root
mode: "0644"
loop: "{{ life_noc_command_files.files }}"
notify:
- validate icinga
- reload icinga
- name: find life-noc template files on target
ansible.builtin.find:
paths: "{{ life_noc_project_root }}/icinga/templates"
patterns: "*.conf"
file_type: file
register: life_noc_template_files
- name: deploy life-noc template files into icinga conf.d
ansible.builtin.copy:
src: "{{ item.path }}"
dest: "/etc/icinga2/conf.d/life-noc-template-{{ item.path | basename }}"
remote_src: true
owner: root
group: root
mode: "0644"
loop: "{{ life_noc_template_files.files }}"
notify:
- validate icinga
- reload icinga
- name: find life-noc servicegroup files on target
ansible.builtin.find:
paths: "{{ life_noc_project_root }}/icinga/servicegroups"
patterns: "*.conf"
file_type: file
register: life_noc_servicegroup_files
- name: deploy life-noc servicegroup files into icinga conf.d
ansible.builtin.copy:
src: "{{ item.path }}"
dest: "/etc/icinga2/conf.d/life-noc-servicegroup-{{ item.path | basename }}"
remote_src: true
owner: root
group: root
mode: "0644"
loop: "{{ life_noc_servicegroup_files.files }}"
notify:
- validate icinga
- reload icinga
- name: find life-noc host files on target
ansible.builtin.find:
paths: "{{ life_noc_project_root }}/icinga/hosts"
patterns: "*.conf"
file_type: file
register: life_noc_host_files
- name: deploy life-noc host files into icinga conf.d
ansible.builtin.copy:
src: "{{ item.path }}"
dest: "/etc/icinga2/conf.d/life-noc-host-{{ item.path | basename }}"
remote_src: true
owner: root
group: root
mode: "0644"
loop: "{{ life_noc_host_files.files }}"
notify:
- validate icinga
- reload icinga
- name: find life-noc service files on target
ansible.builtin.find:
paths: "{{ life_noc_project_root }}/icinga/services"
patterns: "*.conf"
file_type: file
register: life_noc_service_files
- name: deploy life-noc service files into icinga conf.d
ansible.builtin.copy:
src: "{{ item.path }}"
dest: "/etc/icinga2/conf.d/life-noc-service-{{ item.path | basename }}"
remote_src: true
owner: root
group: root
mode: "0644"
loop: "{{ life_noc_service_files.files }}"
notify:
- validate icinga
- reload icinga
##################################
- name: install mock plugin
ansible.builtin.copy:
src: "{{ life_noc_project_root }}/checks/check_life_noc_mock.sh"
dest: /usr/lib/nagios/plugins/check_life_noc_mock.sh
remote_src: true
owner: root
group: root
mode: "0755"
notify:
- validate icinga
- reload icinga
- name: install compatibility wrapper plugin
ansible.builtin.copy:
src: "{{ life_noc_project_root }}/checks/check_echeance_vie.sh"
dest: /usr/lib/nagios/plugins/check_echeance_vie.sh
remote_src: true
owner: root
group: root
mode: "0755"
notify:
- validate icinga
- reload icinga
- name: install generic life-noc probe plugin
ansible.builtin.copy:
src: "{{ life_noc_project_root }}/checks/check_life_noc_probe.py"
dest: /usr/lib/nagios/plugins/check_life_noc_probe.py
remote_src: true
owner: root
group: root
mode: "0755"
notify:
- validate icinga
- reload icinga
- name: ensure bpm destination directory exists
ansible.builtin.file:
path: "{{ life_noc_bpm_destination_dir }}"
state: directory
owner: root
group: root
mode: "0755"
when:
- life_noc_bpm_deploy_enabled | bool
- life_noc_bpm_destination_dir is defined
- name: deploy bpm config
ansible.builtin.copy:
src: "{{ life_noc_project_root }}/bpm/Life-NOC.conf"
dest: "{{ life_noc_bpm_destination_dir }}/Life-NOC.conf"
remote_src: true
owner: root
group: root
mode: "0644"
when:
- life_noc_bpm_deploy_enabled | bool
- life_noc_bpm_destination_dir is defined
- name: install api dependencies for inputs service
ansible.builtin.apt:
name:
- python3-fastapi
- python3-uvicorn
- python3-multipart
state: present
update_cache: true
- name: deploy life-noc input api systemd unit
ansible.builtin.template:
src: life-noc-input-api.service.j2
dest: /etc/systemd/system/life-noc-input-api.service
owner: root
group: root
mode: "0644"
notify:
- reload systemd
- restart life-noc input api
- name: enable and start life-noc input api
ansible.builtin.service:
name: life-noc-input-api
enabled: true
state: started

View file

@ -1,16 +0,0 @@
[Unit]
Description=Life-NOC Input API
After=network.target
[Service]
Type=simple
User=root
Group=root
WorkingDirectory={{ life_noc_project_root }}
Environment=LIFE_NOC_ADMIN_UI_ENABLED={{ "1" if (life_noc_admin_ui_enabled | bool) else "0" }}
ExecStart=/usr/bin/python3 -m uvicorn scripts.life_noc_input_api:app --host 0.0.0.0 --port 8787
Restart=on-failure
RestartSec=3
[Install]
WantedBy=multi-user.target

View file

@ -1 +0,0 @@
life_noc_db_root_socket: /run/mysqld/mysqld.sock

View file

@ -1,13 +0,0 @@
- name: install mariadb server
ansible.builtin.apt:
name:
- mariadb-server
- mariadb-client
state: present
update_cache: true
- name: enable and start mariadb
ansible.builtin.service:
name: mariadb
enabled: true
state: started

View file

@ -1,10 +0,0 @@
- hosts: icinga
become: true
roles:
- base
- mariadb
- icinga2
- icingaweb2
- businessprocess
- life_noc

View file

@ -1,62 +0,0 @@
### Business Process Config File ###
#
# Title : Life-NOC
# Description :
# Owner : icingadmin
# AddToMenu : yes
# Backend :
# Statetype : soft
#
###################################
REVUE = life-noc;revue-revue-quotidienne-life-noc & life-noc;revue-revue-hebdomadaire-priorites & life-noc;revue-revue-mensuelle-systeme-vie & life-noc;revue-revue-trimestrielle-orientation
FOCUS = life-noc;focus-entretien-processus-focus & life-noc;focus-nettoyage-inbox-mentale & life-noc;focus-revue-limitation-engagements
FINANCES-PERSONNELLES = life-noc;finances-personnelles-revision-comptes-bancaires & life-noc;finances-personnelles-verification-cartes-credit & life-noc;finances-personnelles-paiement-cartes-credit & life-noc;finances-personnelles-revision-budget-personnel & life-noc;finances-personnelles-verification-prelevements-automatiques & life-noc;finances-personnelles-verification-placements & life-noc;finances-personnelles-verification-cotisations-reer & life-noc;finances-personnelles-verification-celi & life-noc;finances-personnelles-preparation-dossier-financier-annuel
FISCALITE-PERSONNELLE = life-noc;fiscalite-personnelle-preparation-documents-impots & life-noc;fiscalite-personnelle-production-impots-federal & life-noc;fiscalite-personnelle-production-impots-quebec & life-noc;fiscalite-personnelle-paiement-solde-impots & life-noc;fiscalite-personnelle-verification-avis-cotisation & life-noc;fiscalite-personnelle-archivage-documents-fiscaux & life-noc;fiscalite-personnelle-verification-acomptes-provisionnels
OBLIGATIONS-LEGALES-PERSONNELLES = life-noc;obligations-legales-personnelles-verification-testament & life-noc;obligations-legales-personnelles-verification-mandat-inaptitude & life-noc;obligations-legales-personnelles-verification-directives-medicales & life-noc;obligations-legales-personnelles-verification-papiers-identite & life-noc;obligations-legales-personnelles-renouvellement-permis-conduire & life-noc;obligations-legales-personnelles-verification-carte-assurance-maladie & life-noc;obligations-legales-personnelles-verification-passeport
MAISON = life-noc;maison-remplacement-filtre-fournaise & life-noc;maison-inspection-fournaise & life-noc;maison-inspection-thermopompe & life-noc;maison-nettoyage-unites-exterieures & life-noc;maison-inspection-toiture & life-noc;maison-inspection-gouttieres & life-noc;maison-inspection-fondation & life-noc;maison-verification-drainage-terrain & life-noc;maison-test-detecteurs-fumee & life-noc;maison-test-detecteurs-co & life-noc;maison-remplacement-piles-detecteurs & life-noc;maison-verification-plomberie-visible & life-noc;maison-inspection-sump-pump & life-noc;maison-verification-calfetrage & life-noc;maison-inspection-portes-garage & life-noc;maison-verification-extincteurs
GARAGE-ET-RANGEMENT = life-noc;garage-et-rangement-inspection-rangement-plafond & life-noc;garage-et-rangement-revue-inventaire-garage & life-noc;garage-et-rangement-verification-rouille-outillage & life-noc;garage-et-rangement-inspection-securite-garage & life-noc;garage-et-rangement-rotation-stockage-bacs
ENERGIE = life-noc;energie-inspection-batteries-lifepo4 & life-noc;energie-verification-tension-batteries & life-noc;energie-verification-smartshunt & life-noc;energie-verification-cerbo-gx & life-noc;energie-verification-can-rs485 & life-noc;energie-inspection-cablage-energie & life-noc;energie-verification-busbars & life-noc;energie-verification-parametres-charge & life-noc;energie-test-charge-batteries & life-noc;energie-test-comportement-onduleur & life-noc;energie-verification-journal-evenements-victron
RESILIENCE = life-noc;resilience-test-generatrice-propane & life-noc;resilience-verification-carburant-generatrice & life-noc;resilience-verification-procedure-bascule & life-noc;resilience-verification-stock-lampes-piles & life-noc;resilience-verification-trousses-urgence & life-noc;resilience-revision-plan-urgence & life-noc;resilience-test-autonomie-base & life-noc;resilience-verification-moyens-cuisson-secours
STOCK-ALIMENTAIRE = life-noc;stock-alimentaire-rotation-nourriture-seche & life-noc;stock-alimentaire-verification-reserve-eau & life-noc;stock-alimentaire-verification-mylar-absorbeurs & life-noc;stock-alimentaire-revue-inventaire-conserves & life-noc;stock-alimentaire-revue-inventaire-farine-riz-pates & life-noc;stock-alimentaire-verification-bacs-legumes-racines & life-noc;stock-alimentaire-revue-supplements-vitamines
SANTE = life-noc;sante-verification-trousse-premiers-soins & life-noc;sante-verification-expiration-medicaments & life-noc;sante-revision-rendez-vous-medicaux & life-noc;sante-verification-lunettes-prescriptions & life-noc;sante-verification-dossier-sante
VOITURE = life-noc;voiture-verification-huile-moteur & life-noc;voiture-inspection-freins & life-noc;voiture-verification-pneus & life-noc;voiture-ajustement-valves & life-noc;voiture-verification-timing-belt & life-noc;voiture-verification-batterie-voiture & life-noc;voiture-verification-balais-essuie-glace & life-noc;voiture-verification-liquides & life-noc;voiture-verification-eclairage & life-noc;voiture-verification-immatriculation-assurance
JARDIN = life-noc;jardin-inspection-vignes & life-noc;jardin-entretien-bleuetiers & life-noc;jardin-entretien-framboisiers & life-noc;jardin-inspection-kiwis-nordiques & life-noc;jardin-entretien-rhubarbe & life-noc;jardin-inspection-groseillier & life-noc;jardin-inspection-muriers & life-noc;jardin-entretien-houblon & life-noc;jardin-revision-pharmacopee-jardin & life-noc;jardin-revision-armoire-produits-jardin
OUTILS-ET-EQUIPEMENTS = life-noc;outils-et-equipements-entretien-outils-jardin & life-noc;outils-et-equipements-inspection-outils-electriques & life-noc;outils-et-equipements-verification-rallonges-et-connecteurs & life-noc;outils-et-equipements-verification-compresseur-et-accessoires & life-noc;outils-et-equipements-revision-inventaire-outillage
INFORMATIQUE-PERSONNELLE = life-noc;informatique-personnelle-verification-sauvegardes-personnelles & life-noc;informatique-personnelle-nettoyage-stockage-personnel & life-noc;informatique-personnelle-verification-comptes-importants & life-noc;informatique-personnelle-revue-mots-de-passe-personnels & life-noc;informatique-personnelle-verification-documents-cloud-personnels
INFRASTRUCTURE-CHEZLEPRO = life-noc;infrastructure-chezlepro-verification-proxmox & life-noc;infrastructure-chezlepro-verification-ceph & life-noc;infrastructure-chezlepro-test-restauration-backups & life-noc;infrastructure-chezlepro-verification-pbs-truenas & life-noc;infrastructure-chezlepro-verification-ups-infrastructure & life-noc;infrastructure-chezlepro-verification-capacite-stockage & life-noc;infrastructure-chezlepro-verification-apt-cacher-ng & life-noc;infrastructure-chezlepro-verification-icinga2 & life-noc;infrastructure-chezlepro-verification-keycloak-openldap & life-noc;infrastructure-chezlepro-verification-nextcloud & life-noc;infrastructure-chezlepro-verification-mailcow & life-noc;infrastructure-chezlepro-verification-openvas & life-noc;infrastructure-chezlepro-verification-journaux-systemes
RESEAU-CHEZLEPRO = life-noc;reseau-chezlepro-verification-firewalls & life-noc;reseau-chezlepro-verification-vpn-openvpn & life-noc;reseau-chezlepro-verification-crl-certificats & life-noc;reseau-chezlepro-verification-switches & life-noc;reseau-chezlepro-verification-vlans-segmentation & life-noc;reseau-chezlepro-verification-dns & life-noc;reseau-chezlepro-verification-dynamic-dns & life-noc;reseau-chezlepro-audit-regles-firewall & life-noc;reseau-chezlepro-verification-geoblocking & life-noc;reseau-chezlepro-verification-certificats-publics
SECURITE-CHEZLEPRO = life-noc;securite-chezlepro-verification-mises-a-jour-securite & life-noc;securite-chezlepro-audit-comptes-acces & life-noc;securite-chezlepro-verification-ids-snort & life-noc;securite-chezlepro-revue-pki-privee & life-noc;securite-chezlepro-revue-politiques-securite & life-noc;securite-chezlepro-verification-sauvegardes-configuration
EXPLOITATION-CHEZLEPRO = life-noc;exploitation-chezlepro-revision-playbooks-ansible & life-noc;exploitation-chezlepro-verification-inventaires-ansible & life-noc;exploitation-chezlepro-revision-documentation-technique & life-noc;exploitation-chezlepro-verification-procedures-reprise & life-noc;exploitation-chezlepro-revue-capacite-ressources & life-noc;exploitation-chezlepro-verification-jobs-automatises
OBLIGATIONS-CHEZLEPRO = life-noc;obligations-chezlepro-verification-dossier-comptable-entreprise & life-noc;obligations-chezlepro-verification-facturation-clients & life-noc;obligations-chezlepro-verification-paiements-fournisseurs & life-noc;obligations-chezlepro-verification-contrats-ententes & life-noc;obligations-chezlepro-verification-registraire-entreprise & life-noc;obligations-chezlepro-verification-declarations-taxes & life-noc;obligations-chezlepro-verification-assurances-entreprise & life-noc;obligations-chezlepro-archivage-documents-entreprise
ACTIFS-CHEZLEPRO = life-noc;actifs-chezlepro-revision-inventaire-materiel & life-noc;actifs-chezlepro-verification-amortissables & life-noc;actifs-chezlepro-verification-serveurs-et-composants & life-noc;actifs-chezlepro-verification-reserve-pieces & life-noc;actifs-chezlepro-revision-actifs-transferts
PROJETS = life-noc;projets-revision-life-noc & life-noc;projets-revision-alliance-boreale & life-noc;projets-revision-erplibre & life-noc;projets-revision-semence-numerique & life-noc;projets-revision-ortrux-1 & life-noc;projets-revision-district16
COMMUNAUTE = life-noc;communaute-verification-outils-aa & life-noc;communaute-verification-espace-87-16 & life-noc;communaute-verification-salles-visio-groupes & life-noc;communaute-verification-depots-rapports-rsg & life-noc;communaute-revision-outils-communication-communaute
DOCUMENTATION = life-noc;documentation-revue-docs-personnelles-importantes & life-noc;documentation-revue-wiki-technique & life-noc;documentation-revue-base-connaissances & life-noc;documentation-verification-sauvegarde-docs-cles
ANIMAUX = life-noc;animaux-verification-stock-nourriture-chats & life-noc;animaux-verification-friandises-et-litiere & life-noc;animaux-revision-routine-soins-animaux
display 1;REVUE;REVUE
display 1;FOCUS;FOCUS
display 1;FINANCES-PERSONNELLES;FINANCES-PERSONNELLES
display 1;FISCALITE-PERSONNELLE;FISCALITE-PERSONNELLE
display 1;OBLIGATIONS-LEGALES-PERSONNELLES;OBLIGATIONS-LEGALES-PERSONNELLES
display 1;MAISON;MAISON
display 1;GARAGE-ET-RANGEMENT;GARAGE-ET-RANGEMENT
display 1;ENERGIE;ENERGIE
display 1;RESILIENCE;RESILIENCE
display 1;STOCK-ALIMENTAIRE;STOCK-ALIMENTAIRE
display 1;SANTE;SANTE
display 1;VOITURE;VOITURE
display 1;JARDIN;JARDIN
display 1;OUTILS-ET-EQUIPEMENTS;OUTILS-ET-EQUIPEMENTS
display 1;INFORMATIQUE-PERSONNELLE;INFORMATIQUE-PERSONNELLE
display 1;INFRASTRUCTURE-CHEZLEPRO;INFRASTRUCTURE-CHEZLEPRO
display 1;RESEAU-CHEZLEPRO;RESEAU-CHEZLEPRO
display 1;SECURITE-CHEZLEPRO;SECURITE-CHEZLEPRO
display 1;EXPLOITATION-CHEZLEPRO;EXPLOITATION-CHEZLEPRO
display 1;OBLIGATIONS-CHEZLEPRO;OBLIGATIONS-CHEZLEPRO
display 1;ACTIFS-CHEZLEPRO;ACTIFS-CHEZLEPRO
display 1;PROJETS;PROJETS
display 1;COMMUNAUTE;COMMUNAUTE
display 1;DOCUMENTATION;DOCUMENTATION
display 1;ANIMAUX;ANIMAUX

View file

@ -1,5 +0,0 @@
#!/bin/bash
# Compatibilité transitoire.
# Cette ancienne sonde d'échéance est conservée comme wrapper vers la sonde mock.
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
exec "$SCRIPT_DIR/check_life_noc_mock.sh" "$@"

View file

@ -1,57 +0,0 @@
#!/bin/bash
set -u
STATE="OK"
MESSAGE="Sous contrôle"
ITEM_NAME=""
DATE_ECHEANCE=""
while [ "$#" -gt 0 ]; do
case "$1" in
--state)
STATE="$2"
shift 2
;;
--message)
MESSAGE="$2"
shift 2
;;
--item-name)
ITEM_NAME="$2"
shift 2
;;
--date)
DATE_ECHEANCE="$2"
shift 2
;;
*)
echo "UNKNOWN - argument non reconnu: $1"
exit 3
;;
esac
done
STATE_UPPER=$(printf '%s' "$STATE" | tr '[:lower:]' '[:upper:]')
OUTPUT_SUFFIX=""
[ -n "$ITEM_NAME" ] && OUTPUT_SUFFIX="$OUTPUT_SUFFIX | item=$ITEM_NAME"
[ -n "$DATE_ECHEANCE" ] && OUTPUT_SUFFIX="$OUTPUT_SUFFIX date=$DATE_ECHEANCE"
case "$STATE_UPPER" in
OK)
echo "OK - $MESSAGE$OUTPUT_SUFFIX"
exit 0
;;
WARNING)
echo "WARNING - $MESSAGE$OUTPUT_SUFFIX"
exit 1
;;
CRITICAL)
echo "CRITICAL - $MESSAGE$OUTPUT_SUFFIX"
exit 2
;;
*)
echo "UNKNOWN - état mock invalide: $STATE"
exit 3
;;
esac

View file

@ -1,211 +0,0 @@
#!/usr/bin/env python3
import argparse
from datetime import datetime, timezone
from pathlib import Path
import yaml
def exit_with(code: int, text: str) -> None:
print(text)
raise SystemExit(code)
def parse_date(value: str) -> datetime:
return datetime.strptime(value, "%Y-%m-%d").replace(tzinfo=timezone.utc)
def load_input_item(inputs_file: str, item_key: str) -> dict:
path = Path(inputs_file)
if not path.exists():
raise ValueError(f"inputs file introuvable: {inputs_file}")
data = yaml.safe_load(path.read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise ValueError(f"inputs file invalide: {inputs_file}")
if item_key not in data:
raise ValueError(f"item_key introuvable dans le store: {item_key}")
item = data[item_key]
if not isinstance(item, dict):
raise ValueError(f"entrée invalide pour item_key: {item_key}")
return item
def load_input_value(inputs_file: str, item_key: str) -> str:
item = load_input_item(inputs_file, item_key)
if "value" not in item:
raise ValueError(f"champ 'value' absent pour item_key: {item_key}")
return str(item["value"]).strip()
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--probe-type", required=True)
ap.add_argument("--source-type", required=True)
ap.add_argument("--source-value")
ap.add_argument("--inputs-file")
ap.add_argument("--item-key")
ap.add_argument("--unit", required=True)
ap.add_argument("--unknown-lt", type=float)
ap.add_argument("--unknown-gte", type=float)
ap.add_argument("--ok-gte", type=float)
ap.add_argument("--ok-lt", type=float)
ap.add_argument("--warning-gte", type=float)
ap.add_argument("--warning-lt", type=float)
ap.add_argument("--critical-gte", type=float)
ap.add_argument("--critical-lt", type=float)
ap.add_argument("--on-error", default="critical")
ap.add_argument("--label", default="life-noc")
args = ap.parse_args()
try:
if args.probe_type in {"elapsed_time", "days_until_due"}:
if args.source_type != "manual_date":
exit_with(2, f"CRITICAL - source_type non supporté: {args.source_type}")
if args.unit != "days":
exit_with(2, f"CRITICAL - unité non supportée: {args.unit}")
if args.inputs_file and args.item_key:
source_value = load_input_value(args.inputs_file, args.item_key)
elif args.source_value:
source_value = args.source_value
else:
raise ValueError("aucune source fournie: inputs-file/item-key ou source-value requis")
dt = parse_date(source_value)
now = datetime.now(timezone.utc)
elif args.probe_type == "elapsed_distance":
if args.source_type != "manual_counter":
exit_with(2, f"CRITICAL - source_type non supporté: {args.source_type}")
if args.unit != "km":
exit_with(2, f"CRITICAL - unité non supportée: {args.unit}")
if args.inputs_file and args.item_key:
item = load_input_item(args.inputs_file, args.item_key)
current_value = float(str(item.get("value", "")).strip())
reference_value = float(str(item.get("reference_value", "")).strip())
else:
raise ValueError("manual_counter exige inputs-file et item-key")
metric = current_value - reference_value
if args.unknown_lt is not None and metric < args.unknown_lt:
exit_with(3, f"UNKNOWN - {args.label}: écart compteur invalide ({metric:.0f} km)")
if args.critical_gte is not None and metric >= args.critical_gte:
exit_with(2, f"CRITICAL - {args.label}: {metric:.0f} km")
if args.warning_gte is not None and metric >= args.warning_gte:
exit_with(1, f"WARNING - {args.label}: {metric:.0f} km")
if args.ok_gte is not None and metric >= args.ok_gte:
exit_with(0, f"OK - {args.label}: {metric:.0f} km")
exit_with(2, f"CRITICAL - {args.label}: seuils incohérents")
elif args.probe_type == "remaining_quantity":
if args.source_type != "manual_value":
exit_with(2, f"CRITICAL - source_type non supporté: {args.source_type}")
if args.unit not in {"%", "units", "litres"}:
exit_with(2, f"CRITICAL - unité non supportée: {args.unit}")
if args.inputs_file and args.item_key:
item = load_input_item(args.inputs_file, args.item_key)
metric = float(str(item.get("value", "")).strip())
elif args.source_value:
metric = float(str(args.source_value).strip())
else:
raise ValueError("manual_value exige inputs-file/item-key ou source-value")
unit_suffix = args.unit
if args.critical_lt is not None and metric < args.critical_lt:
exit_with(2, f"CRITICAL - {args.label}: {metric:.1f} {unit_suffix} restants")
if args.warning_lt is not None and metric < args.warning_lt:
exit_with(1, f"WARNING - {args.label}: {metric:.1f} {unit_suffix} restants")
if args.ok_gte is not None and metric >= args.ok_gte:
exit_with(0, f"OK - {args.label}: {metric:.1f} {unit_suffix} restants")
if args.unknown_gte is not None and metric >= args.unknown_gte:
exit_with(3, f"UNKNOWN - {args.label}: {metric:.1f} {unit_suffix} restants")
exit_with(2, f"CRITICAL - {args.label}: seuils incohérents")
elif args.probe_type == "current_value":
if args.source_type != "manual_value":
exit_with(2, f"CRITICAL - source_type non supporté: {args.source_type}")
if args.unit not in {"%", "units", "litres", "volts", "watts"}:
exit_with(2, f"CRITICAL - unité non supportée: {args.unit}")
if args.inputs_file and args.item_key:
item = load_input_item(args.inputs_file, args.item_key)
metric = float(str(item.get("value", "")).strip())
elif args.source_value:
metric = float(str(args.source_value).strip())
else:
raise ValueError("manual_value exige inputs-file/item-key ou source-value")
unit_suffix = args.unit
if args.critical_lt is not None and metric < args.critical_lt:
exit_with(2, f"CRITICAL - {args.label}: {metric:.1f} {unit_suffix}")
if args.critical_gte is not None and metric >= args.critical_gte:
exit_with(2, f"CRITICAL - {args.label}: {metric:.1f} {unit_suffix}")
if args.warning_lt is not None and metric < args.warning_lt:
exit_with(1, f"WARNING - {args.label}: {metric:.1f} {unit_suffix}")
if args.warning_gte is not None and metric >= args.warning_gte:
exit_with(1, f"WARNING - {args.label}: {metric:.1f} {unit_suffix}")
if args.ok_gte is not None and metric >= args.ok_gte:
exit_with(0, f"OK - {args.label}: {metric:.1f} {unit_suffix}")
if args.ok_lt is not None and metric < args.ok_lt:
exit_with(0, f"OK - {args.label}: {metric:.1f} {unit_suffix}")
if args.unknown_gte is not None and metric >= args.unknown_gte:
exit_with(3, f"UNKNOWN - {args.label}: {metric:.1f} {unit_suffix}")
if args.unknown_lt is not None and metric < args.unknown_lt:
exit_with(3, f"UNKNOWN - {args.label}: {metric:.1f} {unit_suffix}")
exit_with(2, f"CRITICAL - {args.label}: seuils incohérents")
else:
exit_with(2, f"CRITICAL - probe_type non supporté: {args.probe_type}")
if args.probe_type == "elapsed_time":
metric = (now - dt).total_seconds() / 86400.0
if args.critical_gte is not None and metric >= args.critical_gte:
exit_with(2, f"CRITICAL - {args.label}: {metric:.1f} jours")
if args.warning_gte is not None and metric >= args.warning_gte:
exit_with(1, f"WARNING - {args.label}: {metric:.1f} jours")
if args.ok_gte is not None and metric >= args.ok_gte:
exit_with(0, f"OK - {args.label}: {metric:.1f} jours")
if args.unknown_lt is not None and metric < args.unknown_lt:
exit_with(3, f"UNKNOWN - {args.label}: {metric:.1f} jours")
exit_with(2, f"CRITICAL - {args.label}: seuils incohérents")
elif args.probe_type == "days_until_due":
metric = (dt - now).total_seconds() / 86400.0
if args.critical_lt is not None and metric < args.critical_lt:
exit_with(2, f"CRITICAL - {args.label}: {metric:.1f} jours restants")
if args.warning_lt is not None and metric < args.warning_lt:
exit_with(1, f"WARNING - {args.label}: {metric:.1f} jours restants")
if args.ok_lt is not None and metric < args.ok_lt:
exit_with(0, f"OK - {args.label}: {metric:.1f} jours restants")
if args.unknown_gte is not None and metric >= args.unknown_gte:
exit_with(3, f"UNKNOWN - {args.label}: {metric:.1f} jours restants")
exit_with(2, f"CRITICAL - {args.label}: seuils incohérents")
except Exception as exc:
if args.on_error == "critical":
exit_with(2, f"CRITICAL - erreur sonde: {exc}")
exit_with(3, f"UNKNOWN - erreur sonde: {exc}")
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -1,12 +0,0 @@
object CheckCommand "check_echeance_vie" {
command = [ PluginDir + "/check_echeance_vie.sh" ]
arguments = {
"--state" = "$mock_state$"
"--message" = "$mock_message$"
"--item-name" = "$service.name$"
"--date" = "$date_echeance$"
}
}

View file

@ -1,12 +0,0 @@
object CheckCommand "check_life_noc_mock" {
command = [ PluginDir + "/check_life_noc_mock.sh" ]
arguments = {
"--state" = "$mock_state$"
"--message" = "$mock_message$"
"--item-name" = "$service.name$"
"--date" = "$date_echeance$"
}
}

View file

@ -1,27 +0,0 @@
object CheckCommand "check_life_noc_probe" {
command = [ PluginDir + "/check_life_noc_probe.py" ]
arguments = {
"--probe-type" = "$life_noc_probe_type$"
"--source-type" = "$life_noc_source_type$"
"--source-value" = "$life_noc_source_value$"
"--inputs-file" = "$life_noc_inputs_file$"
"--item-key" = "$life_noc_item_key$"
"--unit" = "$life_noc_metric_unit$"
"--unknown-lt" = "$life_noc_threshold_unknown_lt$"
"--unknown-gte" = "$life_noc_threshold_unknown_gte$"
"--ok-gte" = "$life_noc_threshold_ok_gte$"
"--ok-lt" = "$life_noc_threshold_ok_lt$"
"--warning-gte" = "$life_noc_threshold_warning_gte$"
"--warning-lt" = "$life_noc_threshold_warning_lt$"
"--critical-gte" = "$life_noc_threshold_critical_gte$"
"--critical-lt" = "$life_noc_threshold_critical_lt$"
"--on-error" = "$life_noc_on_error$"
"--label" = "$life_noc_label$"
}
}

View file

@ -1,9 +0,0 @@
object Host "life-noc" {
import "generic-host"
address = "127.0.0.1"
vars.type = "life-noc"
}

View file

@ -1,105 +0,0 @@
/*
AUTO-GENERATED FILE - SERVICE GROUPS
Ne pas modifier manuellement.
Source: domains.yaml
*/
object ServiceGroup "REVUE" {
display_name = "REVUE"
}
object ServiceGroup "FOCUS" {
display_name = "FOCUS"
}
object ServiceGroup "FINANCES-PERSONNELLES" {
display_name = "FINANCES-PERSONNELLES"
}
object ServiceGroup "FISCALITE-PERSONNELLE" {
display_name = "FISCALITE-PERSONNELLE"
}
object ServiceGroup "OBLIGATIONS-LEGALES-PERSONNELLES" {
display_name = "OBLIGATIONS-LEGALES-PERSONNELLES"
}
object ServiceGroup "MAISON" {
display_name = "MAISON"
}
object ServiceGroup "GARAGE-ET-RANGEMENT" {
display_name = "GARAGE-ET-RANGEMENT"
}
object ServiceGroup "ENERGIE" {
display_name = "ENERGIE"
}
object ServiceGroup "RESILIENCE" {
display_name = "RESILIENCE"
}
object ServiceGroup "STOCK-ALIMENTAIRE" {
display_name = "STOCK-ALIMENTAIRE"
}
object ServiceGroup "SANTE" {
display_name = "SANTE"
}
object ServiceGroup "VOITURE" {
display_name = "VOITURE"
}
object ServiceGroup "JARDIN" {
display_name = "JARDIN"
}
object ServiceGroup "OUTILS-ET-EQUIPEMENTS" {
display_name = "OUTILS-ET-EQUIPEMENTS"
}
object ServiceGroup "INFORMATIQUE-PERSONNELLE" {
display_name = "INFORMATIQUE-PERSONNELLE"
}
object ServiceGroup "INFRASTRUCTURE-CHEZLEPRO" {
display_name = "INFRASTRUCTURE-CHEZLEPRO"
}
object ServiceGroup "RESEAU-CHEZLEPRO" {
display_name = "RESEAU-CHEZLEPRO"
}
object ServiceGroup "SECURITE-CHEZLEPRO" {
display_name = "SECURITE-CHEZLEPRO"
}
object ServiceGroup "EXPLOITATION-CHEZLEPRO" {
display_name = "EXPLOITATION-CHEZLEPRO"
}
object ServiceGroup "OBLIGATIONS-CHEZLEPRO" {
display_name = "OBLIGATIONS-CHEZLEPRO"
}
object ServiceGroup "ACTIFS-CHEZLEPRO" {
display_name = "ACTIFS-CHEZLEPRO"
}
object ServiceGroup "PROJETS" {
display_name = "PROJETS"
}
object ServiceGroup "COMMUNAUTE" {
display_name = "COMMUNAUTE"
}
object ServiceGroup "DOCUMENTATION" {
display_name = "DOCUMENTATION"
}
object ServiceGroup "ANIMAUX" {
display_name = "ANIMAUX"
}

View file

@ -1,95 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: actifs-chezlepro
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "actifs-chezlepro-revision-inventaire-materiel" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/actifs-chezlepro.yaml"
vars.life_noc_item_key = "revision-inventaire-materiel"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-inventaire-materiel"
groups = [ "ACTIFS-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Revoir l'inventaire du matériel de Chezlepro"
vars.instructions_url = "/life-noc/item/actifs-chezlepro/revision-inventaire-materiel"
assign where host.name == "life-noc"
}
apply Service "actifs-chezlepro-verification-amortissables" {
import "service_echeance"
vars.date_echeance = "2026-06-01"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "ACTIFS-CHEZLEPRO" ]
notes = "Vérifier le registre des biens amortissables"
vars.instructions_url = "/life-noc/item/actifs-chezlepro/verification-amortissables"
assign where host.name == "life-noc"
}
apply Service "actifs-chezlepro-verification-serveurs-et-composants" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/actifs-chezlepro.yaml"
vars.life_noc_item_key = "verification-serveurs-et-composants"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-serveurs-et-composants"
groups = [ "ACTIFS-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier l'état des serveurs et composants matériels"
vars.instructions_url = "/life-noc/item/actifs-chezlepro/verification-serveurs-et-composants"
assign where host.name == "life-noc"
}
apply Service "actifs-chezlepro-verification-reserve-pieces" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "remaining_quantity"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/actifs-chezlepro.yaml"
vars.life_noc_item_key = "verification-reserve-pieces"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "verification-reserve-pieces"
groups = [ "ACTIFS-CHEZLEPRO" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Vérifier les pièces de rechange critiques"
vars.instructions_url = "/life-noc/item/actifs-chezlepro/verification-reserve-pieces"
assign where host.name == "life-noc"
}
apply Service "actifs-chezlepro-revision-actifs-transferts" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/actifs-chezlepro.yaml"
vars.life_noc_item_key = "revision-actifs-transferts"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-actifs-transferts"
groups = [ "ACTIFS-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Réviser les actifs transférés ou à transférer à l'entreprise"
vars.instructions_url = "/life-noc/item/actifs-chezlepro/revision-actifs-transferts"
assign where host.name == "life-noc"
}

View file

@ -1,63 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: animaux
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "animaux-verification-stock-nourriture-chats" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "remaining_quantity"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/animaux.yaml"
vars.life_noc_item_key = "verification-stock-nourriture-chats"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "verification-stock-nourriture-chats"
groups = [ "ANIMAUX" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Vérification du stock de nourriture pour chats"
vars.instructions_url = "/life-noc/item/animaux/verification-stock-nourriture-chats"
assign where host.name == "life-noc"
}
apply Service "animaux-verification-friandises-et-litiere" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "remaining_quantity"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/animaux.yaml"
vars.life_noc_item_key = "verification-friandises-et-litiere"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "verification-friandises-et-litiere"
groups = [ "ANIMAUX" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Vérification des stocks de friandises et de litière"
vars.instructions_url = "/life-noc/item/animaux/verification-friandises-et-litiere"
assign where host.name == "life-noc"
}
apply Service "animaux-revision-routine-soins-animaux" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/animaux.yaml"
vars.life_noc_item_key = "revision-routine-soins-animaux"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-routine-soins-animaux"
groups = [ "ANIMAUX" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Revue de la routine de soins et des besoins matériels des chats"
vars.instructions_url = "/life-noc/item/animaux/revision-routine-soins-animaux"
assign where host.name == "life-noc"
}

View file

@ -1,105 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: communaute
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "communaute-verification-outils-aa" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/communaute.yaml"
vars.life_noc_item_key = "verification-outils-aa"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-outils-aa"
groups = [ "COMMUNAUTE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier les outils numériques liés aux activités communautaires"
vars.instructions_url = "/life-noc/item/communaute/verification-outils-aa"
assign where host.name == "life-noc"
}
apply Service "communaute-verification-espace-87-16" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/communaute.yaml"
vars.life_noc_item_key = "verification-espace-87-16"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-espace-87-16"
groups = [ "COMMUNAUTE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier l'espace Nextcloud du district"
vars.instructions_url = "/life-noc/item/communaute/verification-espace-87-16"
assign where host.name == "life-noc"
}
apply Service "communaute-verification-salles-visio-groupes" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/communaute.yaml"
vars.life_noc_item_key = "verification-salles-visio-groupes"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-salles-visio-groupes"
groups = [ "COMMUNAUTE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier les salles de visioconférence des groupes"
vars.instructions_url = "/life-noc/item/communaute/verification-salles-visio-groupes"
assign where host.name == "life-noc"
}
apply Service "communaute-verification-depots-rapports-rsg" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/communaute.yaml"
vars.life_noc_item_key = "verification-depots-rapports-rsg"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-depots-rapports-rsg"
groups = [ "COMMUNAUTE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier les dépôts de rapports RSG"
vars.instructions_url = "/life-noc/item/communaute/verification-depots-rapports-rsg"
assign where host.name == "life-noc"
}
apply Service "communaute-revision-outils-communication-communaute" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/communaute.yaml"
vars.life_noc_item_key = "revision-outils-communication-communaute"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-outils-communication-communaute"
groups = [ "COMMUNAUTE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Réviser les moyens de communication communautaires"
vars.instructions_url = "/life-noc/item/communaute/revision-outils-communication-communaute"
assign where host.name == "life-noc"
}

View file

@ -1,85 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: documentation
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "documentation-revue-docs-personnelles-importantes" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/documentation.yaml"
vars.life_noc_item_key = "revue-docs-personnelles-importantes"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revue-docs-personnelles-importantes"
groups = [ "DOCUMENTATION" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Revoir l'organisation des documents personnels importants"
vars.instructions_url = "/life-noc/item/documentation/revue-docs-personnelles-importantes"
assign where host.name == "life-noc"
}
apply Service "documentation-revue-wiki-technique" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/documentation.yaml"
vars.life_noc_item_key = "revue-wiki-technique"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revue-wiki-technique"
groups = [ "DOCUMENTATION" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Revoir le wiki technique et sa cohérence"
vars.instructions_url = "/life-noc/item/documentation/revue-wiki-technique"
assign where host.name == "life-noc"
}
apply Service "documentation-revue-base-connaissances" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/documentation.yaml"
vars.life_noc_item_key = "revue-base-connaissances"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revue-base-connaissances"
groups = [ "DOCUMENTATION" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Revoir la base de connaissances globale"
vars.instructions_url = "/life-noc/item/documentation/revue-base-connaissances"
assign where host.name == "life-noc"
}
apply Service "documentation-verification-sauvegarde-docs-cles" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/documentation.yaml"
vars.life_noc_item_key = "verification-sauvegarde-docs-cles"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-sauvegarde-docs-cles"
groups = [ "DOCUMENTATION" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier la sauvegarde des documents clés"
vars.instructions_url = "/life-noc/item/documentation/verification-sauvegarde-docs-cles"
assign where host.name == "life-noc"
}

View file

@ -1,206 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: energie
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "energie-inspection-batteries-lifepo4" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/energie.yaml"
vars.life_noc_item_key = "inspection-batteries-lifepo4"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-batteries-lifepo4"
groups = [ "ENERGIE" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Inspection physique et logique des batteries LiFePO4"
vars.instructions_url = "/life-noc/item/energie/inspection-batteries-lifepo4"
assign where host.name == "life-noc"
}
apply Service "energie-verification-tension-batteries" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "current_value"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/energie.yaml"
vars.life_noc_item_key = "verification-tension-batteries"
vars.life_noc_metric_unit = "volts"
vars.life_noc_label = "verification-tension-batteries"
groups = [ "ENERGIE" ]
vars.life_noc_threshold_ok_gte = "51.2"
vars.life_noc_threshold_warning_lt = "51.2"
vars.life_noc_threshold_critical_lt = "50.0"
vars.life_noc_on_error = "critical"
notes = "Vérification des tensions et cohérence des batteries"
vars.instructions_url = "/life-noc/item/energie/verification-tension-batteries"
assign where host.name == "life-noc"
}
apply Service "energie-verification-smartshunt" {
import "service_echeance"
vars.date_echeance = "2026-03-15"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "ENERGIE" ]
notes = "Vérification SmartShunt et cohérence du monitoring"
vars.instructions_url = "/life-noc/item/energie/verification-smartshunt"
assign where host.name == "life-noc"
}
apply Service "energie-verification-cerbo-gx" {
import "service_echeance"
vars.date_echeance = "2026-03-15"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "ENERGIE" ]
notes = "Vérification Cerbo GX et remontée des données"
vars.instructions_url = "/life-noc/item/energie/verification-cerbo-gx"
assign where host.name == "life-noc"
}
apply Service "energie-verification-can-rs485" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/energie.yaml"
vars.life_noc_item_key = "verification-can-rs485"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-can-rs485"
groups = [ "ENERGIE" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérification des communications CAN ou RS485"
vars.instructions_url = "/life-noc/item/energie/verification-can-rs485"
assign where host.name == "life-noc"
}
apply Service "energie-inspection-cablage-energie" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/energie.yaml"
vars.life_noc_item_key = "inspection-cablage-energie"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-cablage-energie"
groups = [ "ENERGIE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Inspection du câblage et des connexions énergétiques"
vars.instructions_url = "/life-noc/item/energie/inspection-cablage-energie"
assign where host.name == "life-noc"
}
apply Service "energie-verification-busbars" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/energie.yaml"
vars.life_noc_item_key = "verification-busbars"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-busbars"
groups = [ "ENERGIE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification du serrage, corrosion et échauffement des busbars"
vars.instructions_url = "/life-noc/item/energie/verification-busbars"
assign where host.name == "life-noc"
}
apply Service "energie-verification-parametres-charge" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/energie.yaml"
vars.life_noc_item_key = "verification-parametres-charge"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-parametres-charge"
groups = [ "ENERGIE" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérification des paramètres de charge et float"
vars.instructions_url = "/life-noc/item/energie/verification-parametres-charge"
assign where host.name == "life-noc"
}
apply Service "energie-test-charge-batteries" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/energie.yaml"
vars.life_noc_item_key = "test-charge-batteries"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "test-charge-batteries"
groups = [ "ENERGIE" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Test de comportement en charge des batteries"
vars.instructions_url = "/life-noc/item/energie/test-charge-batteries"
assign where host.name == "life-noc"
}
apply Service "energie-test-comportement-onduleur" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/energie.yaml"
vars.life_noc_item_key = "test-comportement-onduleur"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "test-comportement-onduleur"
groups = [ "ENERGIE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier le comportement du Multiplus sous charge légère"
vars.instructions_url = "/life-noc/item/energie/test-comportement-onduleur"
assign where host.name == "life-noc"
}
apply Service "energie-verification-journal-evenements-victron" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/energie.yaml"
vars.life_noc_item_key = "verification-journal-evenements-victron"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-journal-evenements-victron"
groups = [ "ENERGIE" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérification des événements et anomalies Victron"
vars.instructions_url = "/life-noc/item/energie/verification-journal-evenements-victron"
assign where host.name == "life-noc"
}

View file

@ -1,125 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: exploitation-chezlepro
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "exploitation-chezlepro-revision-playbooks-ansible" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/exploitation-chezlepro.yaml"
vars.life_noc_item_key = "revision-playbooks-ansible"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-playbooks-ansible"
groups = [ "EXPLOITATION-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Revue des playbooks Ansible"
vars.instructions_url = "/life-noc/item/exploitation-chezlepro/revision-playbooks-ansible"
assign where host.name == "life-noc"
}
apply Service "exploitation-chezlepro-verification-inventaires-ansible" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/exploitation-chezlepro.yaml"
vars.life_noc_item_key = "verification-inventaires-ansible"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-inventaires-ansible"
groups = [ "EXPLOITATION-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification des inventaires Ansible"
vars.instructions_url = "/life-noc/item/exploitation-chezlepro/verification-inventaires-ansible"
assign where host.name == "life-noc"
}
apply Service "exploitation-chezlepro-revision-documentation-technique" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/exploitation-chezlepro.yaml"
vars.life_noc_item_key = "revision-documentation-technique"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-documentation-technique"
groups = [ "EXPLOITATION-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Revue de la documentation technique Chezlepro"
vars.instructions_url = "/life-noc/item/exploitation-chezlepro/revision-documentation-technique"
assign where host.name == "life-noc"
}
apply Service "exploitation-chezlepro-verification-procedures-reprise" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/exploitation-chezlepro.yaml"
vars.life_noc_item_key = "verification-procedures-reprise"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-procedures-reprise"
groups = [ "EXPLOITATION-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier les procédures de reprise et restauration"
vars.instructions_url = "/life-noc/item/exploitation-chezlepro/verification-procedures-reprise"
assign where host.name == "life-noc"
}
apply Service "exploitation-chezlepro-revue-capacite-ressources" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/exploitation-chezlepro.yaml"
vars.life_noc_item_key = "revue-capacite-ressources"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revue-capacite-ressources"
groups = [ "EXPLOITATION-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Revue CPU RAM stockage et charge de l'infrastructure"
vars.instructions_url = "/life-noc/item/exploitation-chezlepro/revue-capacite-ressources"
assign where host.name == "life-noc"
}
apply Service "exploitation-chezlepro-verification-jobs-automatises" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/exploitation-chezlepro.yaml"
vars.life_noc_item_key = "verification-jobs-automatises"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-jobs-automatises"
groups = [ "EXPLOITATION-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification des jobs automatisés et scripts périodiques"
vars.instructions_url = "/life-noc/item/exploitation-chezlepro/verification-jobs-automatises"
assign where host.name == "life-noc"
}

View file

@ -1,185 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: finances-personnelles
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "finances-personnelles-revision-comptes-bancaires" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/finances-personnelles.yaml"
vars.life_noc_item_key = "revision-comptes-bancaires"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-comptes-bancaires"
groups = [ "FINANCES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Révision mensuelle des comptes bancaires personnels"
vars.instructions_url = "/life-noc/item/finances-personnelles/revision-comptes-bancaires"
assign where host.name == "life-noc"
}
apply Service "finances-personnelles-verification-cartes-credit" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/finances-personnelles.yaml"
vars.life_noc_item_key = "verification-cartes-credit"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-cartes-credit"
groups = [ "FINANCES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérification des soldes et transactions des cartes de crédit"
vars.instructions_url = "/life-noc/item/finances-personnelles/verification-cartes-credit"
assign where host.name == "life-noc"
}
apply Service "finances-personnelles-paiement-cartes-credit" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/finances-personnelles.yaml"
vars.life_noc_item_key = "paiement-cartes-credit"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "paiement-cartes-credit"
groups = [ "FINANCES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Paiement des cartes de crédit personnelles"
vars.instructions_url = "/life-noc/item/finances-personnelles/paiement-cartes-credit"
assign where host.name == "life-noc"
}
apply Service "finances-personnelles-revision-budget-personnel" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/finances-personnelles.yaml"
vars.life_noc_item_key = "revision-budget-personnel"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-budget-personnel"
groups = [ "FINANCES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Révision mensuelle du budget personnel"
vars.instructions_url = "/life-noc/item/finances-personnelles/revision-budget-personnel"
assign where host.name == "life-noc"
}
apply Service "finances-personnelles-verification-prelevements-automatiques" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/finances-personnelles.yaml"
vars.life_noc_item_key = "verification-prelevements-automatiques"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-prelevements-automatiques"
groups = [ "FINANCES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérification des prélèvements automatiques personnels"
vars.instructions_url = "/life-noc/item/finances-personnelles/verification-prelevements-automatiques"
assign where host.name == "life-noc"
}
apply Service "finances-personnelles-verification-placements" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/finances-personnelles.yaml"
vars.life_noc_item_key = "verification-placements"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-placements"
groups = [ "FINANCES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification périodique des placements et comptes enregistrés"
vars.instructions_url = "/life-noc/item/finances-personnelles/verification-placements"
assign where host.name == "life-noc"
}
apply Service "finances-personnelles-verification-cotisations-reer" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/finances-personnelles.yaml"
vars.life_noc_item_key = "verification-cotisations-reer"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-cotisations-reer"
groups = [ "FINANCES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_lt = "5"
vars.life_noc_threshold_ok_gte = "5"
vars.life_noc_threshold_warning_gte = "7"
vars.life_noc_threshold_critical_gte = "10"
vars.life_noc_on_error = "critical"
notes = "Vérification des cotisations REER"
vars.instructions_url = "/life-noc/item/finances-personnelles/verification-cotisations-reer"
assign where host.name == "life-noc"
}
apply Service "finances-personnelles-verification-celi" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/finances-personnelles.yaml"
vars.life_noc_item_key = "verification-celi"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-celi"
groups = [ "FINANCES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification de l'espace CELI et de son utilisation"
vars.instructions_url = "/life-noc/item/finances-personnelles/verification-celi"
assign where host.name == "life-noc"
}
apply Service "finances-personnelles-preparation-dossier-financier-annuel" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/finances-personnelles.yaml"
vars.life_noc_item_key = "preparation-dossier-financier-annuel"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "preparation-dossier-financier-annuel"
groups = [ "FINANCES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_lt = "300"
vars.life_noc_threshold_ok_gte = "300"
vars.life_noc_threshold_warning_gte = "365"
vars.life_noc_threshold_critical_gte = "395"
vars.life_noc_on_error = "critical"
notes = "Préparer le dossier financier annuel personnel"
vars.instructions_url = "/life-noc/item/finances-personnelles/preparation-dossier-financier-annuel"
assign where host.name == "life-noc"
}

View file

@ -1,109 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: fiscalite-personnelle
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "fiscalite-personnelle-preparation-documents-impots" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/fiscalite-personnelle.yaml"
vars.life_noc_item_key = "preparation-documents-impots"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "preparation-documents-impots"
groups = [ "FISCALITE-PERSONNELLE" ]
vars.life_noc_threshold_unknown_lt = "5"
vars.life_noc_threshold_ok_gte = "5"
vars.life_noc_threshold_warning_gte = "7"
vars.life_noc_threshold_critical_gte = "10"
vars.life_noc_on_error = "critical"
notes = "Rassembler tous les documents fiscaux personnels"
vars.instructions_url = "/life-noc/item/fiscalite-personnelle/preparation-documents-impots"
assign where host.name == "life-noc"
}
apply Service "fiscalite-personnelle-production-impots-federal" {
import "service_echeance"
vars.date_echeance = "2026-04-30"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "FISCALITE-PERSONNELLE" ]
notes = "Produire la déclaration de revenus fédérale"
vars.instructions_url = "/life-noc/item/fiscalite-personnelle/production-impots-federal"
assign where host.name == "life-noc"
}
apply Service "fiscalite-personnelle-production-impots-quebec" {
import "service_echeance"
vars.date_echeance = "2026-04-30"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "FISCALITE-PERSONNELLE" ]
notes = "Produire la déclaration de revenus Québec"
vars.instructions_url = "/life-noc/item/fiscalite-personnelle/production-impots-quebec"
assign where host.name == "life-noc"
}
apply Service "fiscalite-personnelle-paiement-solde-impots" {
import "service_echeance"
vars.date_echeance = "2026-04-30"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "FISCALITE-PERSONNELLE" ]
notes = "Payer tout solde d'impôt exigible"
vars.instructions_url = "/life-noc/item/fiscalite-personnelle/paiement-solde-impots"
assign where host.name == "life-noc"
}
apply Service "fiscalite-personnelle-verification-avis-cotisation" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/fiscalite-personnelle.yaml"
vars.life_noc_item_key = "verification-avis-cotisation"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-avis-cotisation"
groups = [ "FISCALITE-PERSONNELLE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier les avis de cotisation ARC et Revenu Québec"
vars.instructions_url = "/life-noc/item/fiscalite-personnelle/verification-avis-cotisation"
assign where host.name == "life-noc"
}
apply Service "fiscalite-personnelle-archivage-documents-fiscaux" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/fiscalite-personnelle.yaml"
vars.life_noc_item_key = "archivage-documents-fiscaux"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "archivage-documents-fiscaux"
groups = [ "FISCALITE-PERSONNELLE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Archiver les documents fiscaux personnels"
vars.instructions_url = "/life-noc/item/fiscalite-personnelle/archivage-documents-fiscaux"
assign where host.name == "life-noc"
}
apply Service "fiscalite-personnelle-verification-acomptes-provisionnels" {
import "service_echeance"
vars.date_echeance = "2026-03-15"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "FISCALITE-PERSONNELLE" ]
notes = "Vérifier si des acomptes provisionnels sont requis"
vars.instructions_url = "/life-noc/item/fiscalite-personnelle/verification-acomptes-provisionnels"
assign where host.name == "life-noc"
}

View file

@ -1,65 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: focus
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "focus-entretien-processus-focus" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/focus.yaml"
vars.life_noc_item_key = "entretien-processus-focus"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "entretien-processus-focus"
groups = [ "FOCUS" ]
vars.life_noc_threshold_unknown_lt = "5"
vars.life_noc_threshold_ok_gte = "5"
vars.life_noc_threshold_warning_gte = "7"
vars.life_noc_threshold_critical_gte = "10"
vars.life_noc_on_error = "critical"
notes = "Vérifier que les cartouches FOCUS sont à jour"
vars.instructions_url = "/life-noc/item/focus/entretien-processus-focus"
assign where host.name == "life-noc"
}
apply Service "focus-nettoyage-inbox-mentale" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/focus.yaml"
vars.life_noc_item_key = "nettoyage-inbox-mentale"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "nettoyage-inbox-mentale"
groups = [ "FOCUS" ]
vars.life_noc_threshold_unknown_lt = "5"
vars.life_noc_threshold_ok_gte = "5"
vars.life_noc_threshold_warning_gte = "7"
vars.life_noc_threshold_critical_gte = "10"
vars.life_noc_on_error = "critical"
notes = "Vider et clarifier les éléments capturés hors système"
vars.instructions_url = "/life-noc/item/focus/nettoyage-inbox-mentale"
assign where host.name == "life-noc"
}
apply Service "focus-revue-limitation-engagements" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/focus.yaml"
vars.life_noc_item_key = "revue-limitation-engagements"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revue-limitation-engagements"
groups = [ "FOCUS" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérifier que les engagements actifs demeurent réalistes"
vars.instructions_url = "/life-noc/item/focus/revue-limitation-engagements"
assign where host.name == "life-noc"
}

View file

@ -1,105 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: garage-et-rangement
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "garage-et-rangement-inspection-rangement-plafond" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/garage-et-rangement.yaml"
vars.life_noc_item_key = "inspection-rangement-plafond"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-rangement-plafond"
groups = [ "GARAGE-ET-RANGEMENT" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification des supports suspendus au plafond du garage"
vars.instructions_url = "/life-noc/item/garage-et-rangement/inspection-rangement-plafond"
assign where host.name == "life-noc"
}
apply Service "garage-et-rangement-revue-inventaire-garage" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/garage-et-rangement.yaml"
vars.life_noc_item_key = "revue-inventaire-garage"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revue-inventaire-garage"
groups = [ "GARAGE-ET-RANGEMENT" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Revue de l'inventaire et de l'ordre du garage"
vars.instructions_url = "/life-noc/item/garage-et-rangement/revue-inventaire-garage"
assign where host.name == "life-noc"
}
apply Service "garage-et-rangement-verification-rouille-outillage" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/garage-et-rangement.yaml"
vars.life_noc_item_key = "verification-rouille-outillage"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-rouille-outillage"
groups = [ "GARAGE-ET-RANGEMENT" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification de la corrosion sur les outils et équipements"
vars.instructions_url = "/life-noc/item/garage-et-rangement/verification-rouille-outillage"
assign where host.name == "life-noc"
}
apply Service "garage-et-rangement-inspection-securite-garage" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/garage-et-rangement.yaml"
vars.life_noc_item_key = "inspection-securite-garage"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-securite-garage"
groups = [ "GARAGE-ET-RANGEMENT" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification des conditions de sécurité du garage"
vars.instructions_url = "/life-noc/item/garage-et-rangement/inspection-securite-garage"
assign where host.name == "life-noc"
}
apply Service "garage-et-rangement-rotation-stockage-bacs" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/garage-et-rangement.yaml"
vars.life_noc_item_key = "rotation-stockage-bacs"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "rotation-stockage-bacs"
groups = [ "GARAGE-ET-RANGEMENT" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Revue des contenus de bacs de rangement"
vars.instructions_url = "/life-noc/item/garage-et-rangement/rotation-stockage-bacs"
assign where host.name == "life-noc"
}

View file

@ -1,105 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: informatique-personnelle
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "informatique-personnelle-verification-sauvegardes-personnelles" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/informatique-personnelle.yaml"
vars.life_noc_item_key = "verification-sauvegardes-personnelles"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-sauvegardes-personnelles"
groups = [ "INFORMATIQUE-PERSONNELLE" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérification des sauvegardes personnelles"
vars.instructions_url = "/life-noc/item/informatique-personnelle/verification-sauvegardes-personnelles"
assign where host.name == "life-noc"
}
apply Service "informatique-personnelle-nettoyage-stockage-personnel" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/informatique-personnelle.yaml"
vars.life_noc_item_key = "nettoyage-stockage-personnel"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "nettoyage-stockage-personnel"
groups = [ "INFORMATIQUE-PERSONNELLE" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Nettoyage du stockage numérique personnel"
vars.instructions_url = "/life-noc/item/informatique-personnelle/nettoyage-stockage-personnel"
assign where host.name == "life-noc"
}
apply Service "informatique-personnelle-verification-comptes-importants" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/informatique-personnelle.yaml"
vars.life_noc_item_key = "verification-comptes-importants"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-comptes-importants"
groups = [ "INFORMATIQUE-PERSONNELLE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification des comptes numériques personnels importants"
vars.instructions_url = "/life-noc/item/informatique-personnelle/verification-comptes-importants"
assign where host.name == "life-noc"
}
apply Service "informatique-personnelle-revue-mots-de-passe-personnels" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/informatique-personnelle.yaml"
vars.life_noc_item_key = "revue-mots-de-passe-personnels"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revue-mots-de-passe-personnels"
groups = [ "INFORMATIQUE-PERSONNELLE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Revue des mots de passe personnels critiques"
vars.instructions_url = "/life-noc/item/informatique-personnelle/revue-mots-de-passe-personnels"
assign where host.name == "life-noc"
}
apply Service "informatique-personnelle-verification-documents-cloud-personnels" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/informatique-personnelle.yaml"
vars.life_noc_item_key = "verification-documents-cloud-personnels"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-documents-cloud-personnels"
groups = [ "INFORMATIQUE-PERSONNELLE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier la cohérence des documents personnels sauvegardés"
vars.instructions_url = "/life-noc/item/informatique-personnelle/verification-documents-cloud-personnels"
assign where host.name == "life-noc"
}

View file

@ -1,254 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: infrastructure-chezlepro
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "infrastructure-chezlepro-verification-proxmox" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/infrastructure-chezlepro.yaml"
vars.life_noc_item_key = "verification-proxmox"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-proxmox"
groups = [ "INFRASTRUCTURE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérification générale de l'environnement Proxmox"
vars.instructions_url = "/life-noc/item/infrastructure-chezlepro/verification-proxmox"
assign where host.name == "life-noc"
}
apply Service "infrastructure-chezlepro-verification-ceph" {
import "service_echeance"
vars.date_echeance = "2026-04-01"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "INFRASTRUCTURE-CHEZLEPRO" ]
notes = "Vérification générale de l'état Ceph"
vars.instructions_url = "/life-noc/item/infrastructure-chezlepro/verification-ceph"
assign where host.name == "life-noc"
}
apply Service "infrastructure-chezlepro-test-restauration-backups" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/infrastructure-chezlepro.yaml"
vars.life_noc_item_key = "test-restauration-backups"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "test-restauration-backups"
groups = [ "INFRASTRUCTURE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Test de restauration des sauvegardes"
vars.instructions_url = "/life-noc/item/infrastructure-chezlepro/test-restauration-backups"
assign where host.name == "life-noc"
}
apply Service "infrastructure-chezlepro-verification-pbs-truenas" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/infrastructure-chezlepro.yaml"
vars.life_noc_item_key = "verification-pbs-truenas"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-pbs-truenas"
groups = [ "INFRASTRUCTURE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification des solutions de sauvegarde et synchronisation"
vars.instructions_url = "/life-noc/item/infrastructure-chezlepro/verification-pbs-truenas"
assign where host.name == "life-noc"
}
apply Service "infrastructure-chezlepro-verification-ups-infrastructure" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "current_value"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/infrastructure-chezlepro.yaml"
vars.life_noc_item_key = "verification-ups-infrastructure"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "verification-ups-infrastructure"
groups = [ "INFRASTRUCTURE-CHEZLEPRO" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Vérification des UPS de l'infrastructure"
vars.instructions_url = "/life-noc/item/infrastructure-chezlepro/verification-ups-infrastructure"
assign where host.name == "life-noc"
}
apply Service "infrastructure-chezlepro-verification-capacite-stockage" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "current_value"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/infrastructure-chezlepro.yaml"
vars.life_noc_item_key = "verification-capacite-stockage"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "verification-capacite-stockage"
groups = [ "INFRASTRUCTURE-CHEZLEPRO" ]
vars.life_noc_threshold_ok_gte = "25"
vars.life_noc_threshold_warning_lt = "25"
vars.life_noc_threshold_critical_lt = "15"
vars.life_noc_on_error = "critical"
notes = "Vérifier capacité et croissance du stockage"
vars.instructions_url = "/life-noc/item/infrastructure-chezlepro/verification-capacite-stockage"
assign where host.name == "life-noc"
}
apply Service "infrastructure-chezlepro-verification-apt-cacher-ng" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/infrastructure-chezlepro.yaml"
vars.life_noc_item_key = "verification-apt-cacher-ng"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-apt-cacher-ng"
groups = [ "INFRASTRUCTURE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification du bon fonctionnement d'apt-cacher-ng"
vars.instructions_url = "/life-noc/item/infrastructure-chezlepro/verification-apt-cacher-ng"
assign where host.name == "life-noc"
}
apply Service "infrastructure-chezlepro-verification-icinga2" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/infrastructure-chezlepro.yaml"
vars.life_noc_item_key = "verification-icinga2"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-icinga2"
groups = [ "INFRASTRUCTURE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérification de la supervision Icinga2"
vars.instructions_url = "/life-noc/item/infrastructure-chezlepro/verification-icinga2"
assign where host.name == "life-noc"
}
apply Service "infrastructure-chezlepro-verification-keycloak-openldap" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/infrastructure-chezlepro.yaml"
vars.life_noc_item_key = "verification-keycloak-openldap"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-keycloak-openldap"
groups = [ "INFRASTRUCTURE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification de l'identité et de l'authentification centralisées"
vars.instructions_url = "/life-noc/item/infrastructure-chezlepro/verification-keycloak-openldap"
assign where host.name == "life-noc"
}
apply Service "infrastructure-chezlepro-verification-nextcloud" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/infrastructure-chezlepro.yaml"
vars.life_noc_item_key = "verification-nextcloud"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-nextcloud"
groups = [ "INFRASTRUCTURE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérification de l'état Nextcloud"
vars.instructions_url = "/life-noc/item/infrastructure-chezlepro/verification-nextcloud"
assign where host.name == "life-noc"
}
apply Service "infrastructure-chezlepro-verification-mailcow" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/infrastructure-chezlepro.yaml"
vars.life_noc_item_key = "verification-mailcow"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-mailcow"
groups = [ "INFRASTRUCTURE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification de l'infrastructure Mailcow"
vars.instructions_url = "/life-noc/item/infrastructure-chezlepro/verification-mailcow"
assign where host.name == "life-noc"
}
apply Service "infrastructure-chezlepro-verification-openvas" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/infrastructure-chezlepro.yaml"
vars.life_noc_item_key = "verification-openvas"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-openvas"
groups = [ "INFRASTRUCTURE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification de la plateforme OpenVAS"
vars.instructions_url = "/life-noc/item/infrastructure-chezlepro/verification-openvas"
assign where host.name == "life-noc"
}
apply Service "infrastructure-chezlepro-verification-journaux-systemes" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/infrastructure-chezlepro.yaml"
vars.life_noc_item_key = "verification-journaux-systemes"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-journaux-systemes"
groups = [ "INFRASTRUCTURE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Revue des journaux systèmes critiques"
vars.instructions_url = "/life-noc/item/infrastructure-chezlepro/verification-journaux-systemes"
assign where host.name == "life-noc"
}

View file

@ -1,203 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: jardin
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "jardin-inspection-vignes" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/jardin.yaml"
vars.life_noc_item_key = "inspection-vignes"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-vignes"
groups = [ "JARDIN" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Inspection et entretien des vignes"
vars.instructions_url = "/life-noc/item/jardin/inspection-vignes"
assign where host.name == "life-noc"
}
apply Service "jardin-entretien-bleuetiers" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/jardin.yaml"
vars.life_noc_item_key = "entretien-bleuetiers"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "entretien-bleuetiers"
groups = [ "JARDIN" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Entretien des bleuetiers"
vars.instructions_url = "/life-noc/item/jardin/entretien-bleuetiers"
assign where host.name == "life-noc"
}
apply Service "jardin-entretien-framboisiers" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/jardin.yaml"
vars.life_noc_item_key = "entretien-framboisiers"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "entretien-framboisiers"
groups = [ "JARDIN" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Entretien des framboisiers"
vars.instructions_url = "/life-noc/item/jardin/entretien-framboisiers"
assign where host.name == "life-noc"
}
apply Service "jardin-inspection-kiwis-nordiques" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/jardin.yaml"
vars.life_noc_item_key = "inspection-kiwis-nordiques"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-kiwis-nordiques"
groups = [ "JARDIN" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification des kiwis nordiques"
vars.instructions_url = "/life-noc/item/jardin/inspection-kiwis-nordiques"
assign where host.name == "life-noc"
}
apply Service "jardin-entretien-rhubarbe" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/jardin.yaml"
vars.life_noc_item_key = "entretien-rhubarbe"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "entretien-rhubarbe"
groups = [ "JARDIN" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Entretien de la rhubarbe"
vars.instructions_url = "/life-noc/item/jardin/entretien-rhubarbe"
assign where host.name == "life-noc"
}
apply Service "jardin-inspection-groseillier" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/jardin.yaml"
vars.life_noc_item_key = "inspection-groseillier"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-groseillier"
groups = [ "JARDIN" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Inspection du groseillier"
vars.instructions_url = "/life-noc/item/jardin/inspection-groseillier"
assign where host.name == "life-noc"
}
apply Service "jardin-inspection-muriers" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/jardin.yaml"
vars.life_noc_item_key = "inspection-muriers"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-muriers"
groups = [ "JARDIN" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Inspection des mûriers"
vars.instructions_url = "/life-noc/item/jardin/inspection-muriers"
assign where host.name == "life-noc"
}
apply Service "jardin-entretien-houblon" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/jardin.yaml"
vars.life_noc_item_key = "entretien-houblon"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "entretien-houblon"
groups = [ "JARDIN" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification et entretien du houblon"
vars.instructions_url = "/life-noc/item/jardin/entretien-houblon"
assign where host.name == "life-noc"
}
apply Service "jardin-revision-pharmacopée-jardin" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "remaining_quantity"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/jardin.yaml"
vars.life_noc_item_key = "revision-pharmacopée-jardin"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "revision-pharmacopée-jardin"
groups = [ "JARDIN" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Vérification du stock de soins pour végétaux"
vars.instructions_url = "/life-noc/item/jardin/revision-pharmacopée-jardin"
assign where host.name == "life-noc"
}
apply Service "jardin-revision-armoire-produits-jardin" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "remaining_quantity"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/jardin.yaml"
vars.life_noc_item_key = "revision-armoire-produits-jardin"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "revision-armoire-produits-jardin"
groups = [ "JARDIN" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Vérification et ordre de l'armoire des produits pour végétaux"
vars.instructions_url = "/life-noc/item/jardin/revision-armoire-produits-jardin"
assign where host.name == "life-noc"
}

View file

@ -1,316 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: maison
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "maison-remplacement-filtre-fournaise" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "remplacement-filtre-fournaise"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "remplacement-filtre-fournaise"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Remplacer le filtre de la fournaise"
vars.instructions_url = "/life-noc/item/maison/remplacement-filtre-fournaise"
assign where host.name == "life-noc"
}
apply Service "maison-inspection-fournaise" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "inspection-fournaise"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-fournaise"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "150"
vars.life_noc_threshold_ok_gte = "150"
vars.life_noc_threshold_warning_gte = "180"
vars.life_noc_threshold_critical_gte = "210"
vars.life_noc_on_error = "critical"
notes = "Inspection générale de la fournaise avant saison froide"
vars.instructions_url = "/life-noc/item/maison/inspection-fournaise"
assign where host.name == "life-noc"
}
apply Service "maison-inspection-thermopompe" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "inspection-thermopompe"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-thermopompe"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Inspection et entretien de la thermopompe"
vars.instructions_url = "/life-noc/item/maison/inspection-thermopompe"
assign where host.name == "life-noc"
}
apply Service "maison-nettoyage-unites-exterieures" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "nettoyage-unites-exterieures"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "nettoyage-unites-exterieures"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Nettoyer les unités extérieures et vérifier le dégagement"
vars.instructions_url = "/life-noc/item/maison/nettoyage-unites-exterieures"
assign where host.name == "life-noc"
}
apply Service "maison-inspection-toiture" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "inspection-toiture"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-toiture"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "150"
vars.life_noc_threshold_ok_gte = "150"
vars.life_noc_threshold_warning_gte = "180"
vars.life_noc_threshold_critical_gte = "210"
vars.life_noc_on_error = "critical"
notes = "Inspection annuelle de la toiture"
vars.instructions_url = "/life-noc/item/maison/inspection-toiture"
assign where host.name == "life-noc"
}
apply Service "maison-inspection-gouttieres" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "inspection-gouttieres"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-gouttieres"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "150"
vars.life_noc_threshold_ok_gte = "150"
vars.life_noc_threshold_warning_gte = "180"
vars.life_noc_threshold_critical_gte = "210"
vars.life_noc_on_error = "critical"
notes = "Inspection et nettoyage des gouttières"
vars.instructions_url = "/life-noc/item/maison/inspection-gouttieres"
assign where host.name == "life-noc"
}
apply Service "maison-inspection-fondation" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "inspection-fondation"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-fondation"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Inspection de la fondation et des fissures"
vars.instructions_url = "/life-noc/item/maison/inspection-fondation"
assign where host.name == "life-noc"
}
apply Service "maison-verification-drainage-terrain" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "verification-drainage-terrain"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-drainage-terrain"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification du drainage autour de la maison"
vars.instructions_url = "/life-noc/item/maison/verification-drainage-terrain"
assign where host.name == "life-noc"
}
apply Service "maison-test-detecteurs-fumee" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "test-detecteurs-fumee"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "test-detecteurs-fumee"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Test des détecteurs de fumée"
vars.instructions_url = "/life-noc/item/maison/test-detecteurs-fumee"
assign where host.name == "life-noc"
}
apply Service "maison-test-detecteurs-co" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "test-detecteurs-co"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "test-detecteurs-co"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Test des détecteurs de monoxyde de carbone"
vars.instructions_url = "/life-noc/item/maison/test-detecteurs-co"
assign where host.name == "life-noc"
}
apply Service "maison-remplacement-piles-detecteurs" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "remplacement-piles-detecteurs"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "remplacement-piles-detecteurs"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "150"
vars.life_noc_threshold_ok_gte = "150"
vars.life_noc_threshold_warning_gte = "180"
vars.life_noc_threshold_critical_gte = "210"
vars.life_noc_on_error = "critical"
notes = "Remplacement préventif des piles des détecteurs"
vars.instructions_url = "/life-noc/item/maison/remplacement-piles-detecteurs"
assign where host.name == "life-noc"
}
apply Service "maison-verification-plomberie-visible" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "verification-plomberie-visible"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-plomberie-visible"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification visuelle de la plomberie accessible"
vars.instructions_url = "/life-noc/item/maison/verification-plomberie-visible"
assign where host.name == "life-noc"
}
apply Service "maison-inspection-sump-pump" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "inspection-sump-pump"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-sump-pump"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérification de la pompe de puisard si applicable"
vars.instructions_url = "/life-noc/item/maison/inspection-sump-pump"
assign where host.name == "life-noc"
}
apply Service "maison-verification-calfetrage" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "verification-calfetrage"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-calfetrage"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "150"
vars.life_noc_threshold_ok_gte = "150"
vars.life_noc_threshold_warning_gte = "180"
vars.life_noc_threshold_critical_gte = "210"
vars.life_noc_on_error = "critical"
notes = "Vérification du calfeutrage portes et fenêtres"
vars.instructions_url = "/life-noc/item/maison/verification-calfetrage"
assign where host.name == "life-noc"
}
apply Service "maison-inspection-portes-garage" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/maison.yaml"
vars.life_noc_item_key = "inspection-portes-garage"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-portes-garage"
groups = [ "MAISON" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification mécanique et sécurité des portes de garage"
vars.instructions_url = "/life-noc/item/maison/inspection-portes-garage"
assign where host.name == "life-noc"
}
apply Service "maison-verification-extincteurs" {
import "service_echeance"
vars.date_echeance = "2026-06-01"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "MAISON" ]
notes = "Vérification des extincteurs"
vars.instructions_url = "/life-noc/item/maison/verification-extincteurs"
assign where host.name == "life-noc"
}

View file

@ -1,153 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: obligations-chezlepro
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "obligations-chezlepro-verification-dossier-comptable-entreprise" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/obligations-chezlepro.yaml"
vars.life_noc_item_key = "verification-dossier-comptable-entreprise"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-dossier-comptable-entreprise"
groups = [ "OBLIGATIONS-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérifier l'ordre du dossier comptable Chezlepro"
vars.instructions_url = "/life-noc/item/obligations-chezlepro/verification-dossier-comptable-entreprise"
assign where host.name == "life-noc"
}
apply Service "obligations-chezlepro-verification-facturation-clients" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/obligations-chezlepro.yaml"
vars.life_noc_item_key = "verification-facturation-clients"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-facturation-clients"
groups = [ "OBLIGATIONS-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérifier la facturation et son suivi"
vars.instructions_url = "/life-noc/item/obligations-chezlepro/verification-facturation-clients"
assign where host.name == "life-noc"
}
apply Service "obligations-chezlepro-verification-paiements-fournisseurs" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/obligations-chezlepro.yaml"
vars.life_noc_item_key = "verification-paiements-fournisseurs"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-paiements-fournisseurs"
groups = [ "OBLIGATIONS-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérifier les paiements fournisseurs"
vars.instructions_url = "/life-noc/item/obligations-chezlepro/verification-paiements-fournisseurs"
assign where host.name == "life-noc"
}
apply Service "obligations-chezlepro-verification-contrats-ententes" {
import "service_echeance"
vars.date_echeance = "2026-05-15"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "OBLIGATIONS-CHEZLEPRO" ]
notes = "Vérifier contrats, ententes et obligations associées"
vars.instructions_url = "/life-noc/item/obligations-chezlepro/verification-contrats-ententes"
assign where host.name == "life-noc"
}
apply Service "obligations-chezlepro-verification-registraire-entreprise" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "days_until_due"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/obligations-chezlepro.yaml"
vars.life_noc_item_key = "verification-registraire-entreprise"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-registraire-entreprise"
groups = [ "OBLIGATIONS-CHEZLEPRO" ]
vars.life_noc_threshold_ok_lt = "366"
vars.life_noc_threshold_warning_lt = "90"
vars.life_noc_threshold_critical_lt = "30"
vars.life_noc_on_error = "critical"
notes = "Entrer la prochaine date limite pertinente."
vars.instructions_url = "/life-noc/item/obligations-chezlepro/verification-registraire-entreprise"
assign where host.name == "life-noc"
}
apply Service "obligations-chezlepro-verification-declarations-taxes" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "days_until_due"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/obligations-chezlepro.yaml"
vars.life_noc_item_key = "verification-declarations-taxes"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-declarations-taxes"
groups = [ "OBLIGATIONS-CHEZLEPRO" ]
vars.life_noc_threshold_ok_lt = "366"
vars.life_noc_threshold_warning_lt = "45"
vars.life_noc_threshold_critical_lt = "15"
vars.life_noc_on_error = "critical"
notes = "Entrer la prochaine date limite applicable."
vars.instructions_url = "/life-noc/item/obligations-chezlepro/verification-declarations-taxes"
assign where host.name == "life-noc"
}
apply Service "obligations-chezlepro-verification-assurances-entreprise" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "days_until_due"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/obligations-chezlepro.yaml"
vars.life_noc_item_key = "verification-assurances-entreprise"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-assurances-entreprise"
groups = [ "OBLIGATIONS-CHEZLEPRO" ]
vars.life_noc_threshold_ok_lt = "366"
vars.life_noc_threshold_warning_lt = "90"
vars.life_noc_threshold_critical_lt = "30"
vars.life_noc_on_error = "critical"
notes = "Entrer la date de renouvellement la plus proche."
vars.instructions_url = "/life-noc/item/obligations-chezlepro/verification-assurances-entreprise"
assign where host.name == "life-noc"
}
apply Service "obligations-chezlepro-archivage-documents-entreprise" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/obligations-chezlepro.yaml"
vars.life_noc_item_key = "archivage-documents-entreprise"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "archivage-documents-entreprise"
groups = [ "OBLIGATIONS-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Archiver les documents administratifs et financiers de l'entreprise"
vars.instructions_url = "/life-noc/item/obligations-chezlepro/archivage-documents-entreprise"
assign where host.name == "life-noc"
}

View file

@ -1,127 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: obligations-legales-personnelles
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "obligations-legales-personnelles-verification-testament" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/obligations-legales-personnelles.yaml"
vars.life_noc_item_key = "verification-testament"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-testament"
groups = [ "OBLIGATIONS-LEGALES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier la pertinence et l'actualité du testament"
vars.instructions_url = "/life-noc/item/obligations-legales-personnelles/verification-testament"
assign where host.name == "life-noc"
}
apply Service "obligations-legales-personnelles-verification-mandat-inaptitude" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/obligations-legales-personnelles.yaml"
vars.life_noc_item_key = "verification-mandat-inaptitude"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-mandat-inaptitude"
groups = [ "OBLIGATIONS-LEGALES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier le mandat de protection et documents connexes"
vars.instructions_url = "/life-noc/item/obligations-legales-personnelles/verification-mandat-inaptitude"
assign where host.name == "life-noc"
}
apply Service "obligations-legales-personnelles-verification-directives-medicales" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/obligations-legales-personnelles.yaml"
vars.life_noc_item_key = "verification-directives-medicales"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-directives-medicales"
groups = [ "OBLIGATIONS-LEGALES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_lt = "150"
vars.life_noc_threshold_ok_gte = "150"
vars.life_noc_threshold_warning_gte = "180"
vars.life_noc_threshold_critical_gte = "210"
vars.life_noc_on_error = "critical"
notes = "Vérifier les directives médicales anticipées"
vars.instructions_url = "/life-noc/item/obligations-legales-personnelles/verification-directives-medicales"
assign where host.name == "life-noc"
}
apply Service "obligations-legales-personnelles-verification-papiers-identite" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/obligations-legales-personnelles.yaml"
vars.life_noc_item_key = "verification-papiers-identite"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-papiers-identite"
groups = [ "OBLIGATIONS-LEGALES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier l'expiration des papiers d'identité"
vars.instructions_url = "/life-noc/item/obligations-legales-personnelles/verification-papiers-identite"
assign where host.name == "life-noc"
}
apply Service "obligations-legales-personnelles-renouvellement-permis-conduire" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "days_until_due"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/obligations-legales-personnelles.yaml"
vars.life_noc_item_key = "renouvellement-permis-conduire"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "renouvellement-permis-conduire"
groups = [ "OBLIGATIONS-LEGALES-PERSONNELLES" ]
vars.life_noc_threshold_unknown_gte = "90"
vars.life_noc_threshold_ok_lt = "90"
vars.life_noc_threshold_warning_lt = "30"
vars.life_noc_threshold_critical_lt = "7"
vars.life_noc_on_error = "critical"
notes = "Vérifier la proximité de l’échéance du permis"
vars.instructions_url = "/life-noc/item/obligations-legales-personnelles/renouvellement-permis-conduire"
assign where host.name == "life-noc"
}
apply Service "obligations-legales-personnelles-verification-carte-assurance-maladie" {
import "service_echeance"
vars.date_echeance = "2026-10-01"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "OBLIGATIONS-LEGALES-PERSONNELLES" ]
notes = "Vérifier l'expiration de la carte d'assurance maladie"
vars.instructions_url = "/life-noc/item/obligations-legales-personnelles/verification-carte-assurance-maladie"
assign where host.name == "life-noc"
}
apply Service "obligations-legales-personnelles-verification-passeport" {
import "service_echeance"
vars.date_echeance = "2026-06-01"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "OBLIGATIONS-LEGALES-PERSONNELLES" ]
notes = "Vérifier l'expiration du passeport"
vars.instructions_url = "/life-noc/item/obligations-legales-personnelles/verification-passeport"
assign where host.name == "life-noc"
}

View file

@ -1,105 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: outils-et-equipements
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "outils-et-equipements-entretien-outils-jardin" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/outils-et-equipements.yaml"
vars.life_noc_item_key = "entretien-outils-jardin"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "entretien-outils-jardin"
groups = [ "OUTILS-ET-EQUIPEMENTS" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Nettoyage et entretien des outils de jardin"
vars.instructions_url = "/life-noc/item/outils-et-equipements/entretien-outils-jardin"
assign where host.name == "life-noc"
}
apply Service "outils-et-equipements-inspection-outils-electriques" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/outils-et-equipements.yaml"
vars.life_noc_item_key = "inspection-outils-electriques"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "inspection-outils-electriques"
groups = [ "OUTILS-ET-EQUIPEMENTS" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification des outils électriques"
vars.instructions_url = "/life-noc/item/outils-et-equipements/inspection-outils-electriques"
assign where host.name == "life-noc"
}
apply Service "outils-et-equipements-verification-rallonges-et-connecteurs" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/outils-et-equipements.yaml"
vars.life_noc_item_key = "verification-rallonges-et-connecteurs"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-rallonges-et-connecteurs"
groups = [ "OUTILS-ET-EQUIPEMENTS" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification des rallonges et connecteurs"
vars.instructions_url = "/life-noc/item/outils-et-equipements/verification-rallonges-et-connecteurs"
assign where host.name == "life-noc"
}
apply Service "outils-et-equipements-verification-compresseur-et-accessoires" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/outils-et-equipements.yaml"
vars.life_noc_item_key = "verification-compresseur-et-accessoires"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-compresseur-et-accessoires"
groups = [ "OUTILS-ET-EQUIPEMENTS" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification du compresseur et accessoires"
vars.instructions_url = "/life-noc/item/outils-et-equipements/verification-compresseur-et-accessoires"
assign where host.name == "life-noc"
}
apply Service "outils-et-equipements-revision-inventaire-outillage" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/outils-et-equipements.yaml"
vars.life_noc_item_key = "revision-inventaire-outillage"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-inventaire-outillage"
groups = [ "OUTILS-ET-EQUIPEMENTS" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Revue de l'inventaire d'outillage"
vars.instructions_url = "/life-noc/item/outils-et-equipements/revision-inventaire-outillage"
assign where host.name == "life-noc"
}

View file

@ -1,125 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: projets
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "projets-revision-life-noc" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/projets.yaml"
vars.life_noc_item_key = "revision-life-noc"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-life-noc"
groups = [ "PROJETS" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Révision du projet Life-NOC"
vars.instructions_url = "/life-noc/item/projets/revision-life-noc"
assign where host.name == "life-noc"
}
apply Service "projets-revision-alliance-boreale" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/projets.yaml"
vars.life_noc_item_key = "revision-alliance-boreale"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-alliance-boreale"
groups = [ "PROJETS" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Révision du projet Alliance Boréale"
vars.instructions_url = "/life-noc/item/projets/revision-alliance-boreale"
assign where host.name == "life-noc"
}
apply Service "projets-revision-erplibre" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/projets.yaml"
vars.life_noc_item_key = "revision-erplibre"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-erplibre"
groups = [ "PROJETS" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Révision du projet ERPLibre"
vars.instructions_url = "/life-noc/item/projets/revision-erplibre"
assign where host.name == "life-noc"
}
apply Service "projets-revision-semence-numerique" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/projets.yaml"
vars.life_noc_item_key = "revision-semence-numerique"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-semence-numerique"
groups = [ "PROJETS" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Révision du projet semence numérique"
vars.instructions_url = "/life-noc/item/projets/revision-semence-numerique"
assign where host.name == "life-noc"
}
apply Service "projets-revision-ortrux-1" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/projets.yaml"
vars.life_noc_item_key = "revision-ortrux-1"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-ortrux-1"
groups = [ "PROJETS" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Révision du système Ortrux-1"
vars.instructions_url = "/life-noc/item/projets/revision-ortrux-1"
assign where host.name == "life-noc"
}
apply Service "projets-revision-district16" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/projets.yaml"
vars.life_noc_item_key = "revision-district16"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-district16"
groups = [ "PROJETS" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Révision du projet DISTRICT16"
vars.instructions_url = "/life-noc/item/projets/revision-district16"
assign where host.name == "life-noc"
}

View file

@ -1,195 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: reseau-chezlepro
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "reseau-chezlepro-verification-firewalls" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/reseau-chezlepro.yaml"
vars.life_noc_item_key = "verification-firewalls"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-firewalls"
groups = [ "RESEAU-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérification des firewalls"
vars.instructions_url = "/life-noc/item/reseau-chezlepro/verification-firewalls"
assign where host.name == "life-noc"
}
apply Service "reseau-chezlepro-verification-vpn-openvpn" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/reseau-chezlepro.yaml"
vars.life_noc_item_key = "verification-vpn-openvpn"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-vpn-openvpn"
groups = [ "RESEAU-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérification des tunnels OpenVPN"
vars.instructions_url = "/life-noc/item/reseau-chezlepro/verification-vpn-openvpn"
assign where host.name == "life-noc"
}
apply Service "reseau-chezlepro-verification-crl-certificats" {
import "service_echeance"
vars.date_echeance = "2026-04-15"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "RESEAU-CHEZLEPRO" ]
notes = "Vérification de la CRL et des certificats"
vars.instructions_url = "/life-noc/item/reseau-chezlepro/verification-crl-certificats"
assign where host.name == "life-noc"
}
apply Service "reseau-chezlepro-verification-switches" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/reseau-chezlepro.yaml"
vars.life_noc_item_key = "verification-switches"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-switches"
groups = [ "RESEAU-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification des switches et uplinks"
vars.instructions_url = "/life-noc/item/reseau-chezlepro/verification-switches"
assign where host.name == "life-noc"
}
apply Service "reseau-chezlepro-verification-vlans-segmentation" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/reseau-chezlepro.yaml"
vars.life_noc_item_key = "verification-vlans-segmentation"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-vlans-segmentation"
groups = [ "RESEAU-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification de la segmentation réseau"
vars.instructions_url = "/life-noc/item/reseau-chezlepro/verification-vlans-segmentation"
assign where host.name == "life-noc"
}
apply Service "reseau-chezlepro-verification-dns" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/reseau-chezlepro.yaml"
vars.life_noc_item_key = "verification-dns"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-dns"
groups = [ "RESEAU-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification DNS interne et externe"
vars.instructions_url = "/life-noc/item/reseau-chezlepro/verification-dns"
assign where host.name == "life-noc"
}
apply Service "reseau-chezlepro-verification-dynamic-dns" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/reseau-chezlepro.yaml"
vars.life_noc_item_key = "verification-dynamic-dns"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-dynamic-dns"
groups = [ "RESEAU-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification du DNS dynamique si utilisé"
vars.instructions_url = "/life-noc/item/reseau-chezlepro/verification-dynamic-dns"
assign where host.name == "life-noc"
}
apply Service "reseau-chezlepro-audit-regles-firewall" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/reseau-chezlepro.yaml"
vars.life_noc_item_key = "audit-regles-firewall"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "audit-regles-firewall"
groups = [ "RESEAU-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Audit périodique des règles de firewall"
vars.instructions_url = "/life-noc/item/reseau-chezlepro/audit-regles-firewall"
assign where host.name == "life-noc"
}
apply Service "reseau-chezlepro-verification-geoblocking" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/reseau-chezlepro.yaml"
vars.life_noc_item_key = "verification-geoblocking"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-geoblocking"
groups = [ "RESEAU-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier le geoblocking et son effet attendu"
vars.instructions_url = "/life-noc/item/reseau-chezlepro/verification-geoblocking"
assign where host.name == "life-noc"
}
apply Service "reseau-chezlepro-verification-certificats-publics" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "days_until_due"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/reseau-chezlepro.yaml"
vars.life_noc_item_key = "verification-certificats-publics"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-certificats-publics"
groups = [ "RESEAU-CHEZLEPRO" ]
vars.life_noc_threshold_ok_lt = "366"
vars.life_noc_threshold_warning_lt = "45"
vars.life_noc_threshold_critical_lt = "15"
vars.life_noc_on_error = "critical"
notes = "Retenir la date d’expiration la plus proche parmi les certificats publics suivis."
vars.instructions_url = "/life-noc/item/reseau-chezlepro/verification-certificats-publics"
assign where host.name == "life-noc"
}

View file

@ -1,145 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: resilience
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "resilience-test-generatrice-propane" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/resilience.yaml"
vars.life_noc_item_key = "test-generatrice-propane"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "test-generatrice-propane"
groups = [ "RESILIENCE" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Test mensuel de la génératrice au propane"
vars.instructions_url = "/life-noc/item/resilience/test-generatrice-propane"
assign where host.name == "life-noc"
}
apply Service "resilience-verification-carburant-generatrice" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "remaining_quantity"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/resilience.yaml"
vars.life_noc_item_key = "verification-carburant-generatrice"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "verification-carburant-generatrice"
groups = [ "RESILIENCE" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Vérification de l'approvisionnement propane lié à la génératrice"
vars.instructions_url = "/life-noc/item/resilience/verification-carburant-generatrice"
assign where host.name == "life-noc"
}
apply Service "resilience-verification-procedure-bascule" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/resilience.yaml"
vars.life_noc_item_key = "verification-procedure-bascule"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-procedure-bascule"
groups = [ "RESILIENCE" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Réviser la procédure de bascule en mode secours"
vars.instructions_url = "/life-noc/item/resilience/verification-procedure-bascule"
assign where host.name == "life-noc"
}
apply Service "resilience-verification-stock-lampes-piles" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "remaining_quantity"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/resilience.yaml"
vars.life_noc_item_key = "verification-stock-lampes-piles"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "verification-stock-lampes-piles"
groups = [ "RESILIENCE" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Vérification des lampes, piles et éclairage d'urgence"
vars.instructions_url = "/life-noc/item/resilience/verification-stock-lampes-piles"
assign where host.name == "life-noc"
}
apply Service "resilience-verification-trousses-urgence" {
import "service_echeance"
vars.date_echeance = "2026-05-15"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "RESILIENCE" ]
notes = "Vérification des trousses d'urgence"
vars.instructions_url = "/life-noc/item/resilience/verification-trousses-urgence"
assign where host.name == "life-noc"
}
apply Service "resilience-revision-plan-urgence" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/resilience.yaml"
vars.life_noc_item_key = "revision-plan-urgence"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-plan-urgence"
groups = [ "RESILIENCE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Réviser le plan d'urgence domestique"
vars.instructions_url = "/life-noc/item/resilience/revision-plan-urgence"
assign where host.name == "life-noc"
}
apply Service "resilience-test-autonomie-base" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/resilience.yaml"
vars.life_noc_item_key = "test-autonomie-base"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "test-autonomie-base"
groups = [ "RESILIENCE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier l'autonomie énergétique minimale attendue"
vars.instructions_url = "/life-noc/item/resilience/test-autonomie-base"
assign where host.name == "life-noc"
}
apply Service "resilience-verification-moyens-cuisson-secours" {
import "service_echeance"
vars.date_echeance = "2026-05-15"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "RESILIENCE" ]
notes = "Vérification des moyens de cuisson de secours"
vars.instructions_url = "/life-noc/item/resilience/verification-moyens-cuisson-secours"
assign where host.name == "life-noc"
}

View file

@ -1,85 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: revue
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "revue-revue-quotidienne-life-noc" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/revue.yaml"
vars.life_noc_item_key = "revue-quotidienne-life-noc"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revue-quotidienne-life-noc"
groups = [ "REVUE" ]
vars.life_noc_threshold_unknown_lt = "1"
vars.life_noc_threshold_ok_gte = "1"
vars.life_noc_threshold_warning_gte = "2"
vars.life_noc_threshold_critical_gte = "3"
vars.life_noc_on_error = "critical"
notes = "Vérifier le tableau de bord Life-NOC"
vars.instructions_url = "/life-noc/item/revue/revue-quotidienne-life-noc"
assign where host.name == "life-noc"
}
apply Service "revue-revue-hebdomadaire-priorites" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/revue.yaml"
vars.life_noc_item_key = "revue-hebdomadaire-priorites"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revue-hebdomadaire-priorites"
groups = [ "REVUE" ]
vars.life_noc_threshold_unknown_lt = "5"
vars.life_noc_threshold_ok_gte = "5"
vars.life_noc_threshold_warning_gte = "7"
vars.life_noc_threshold_critical_gte = "10"
vars.life_noc_on_error = "critical"
notes = "Revoir les priorités de la semaine"
vars.instructions_url = "https://chezlepro.ca/life-noc/test-instructions"
assign where host.name == "life-noc"
}
apply Service "revue-revue-mensuelle-systeme-vie" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/revue.yaml"
vars.life_noc_item_key = "revue-mensuelle-systeme-vie"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revue-mensuelle-systeme-vie"
groups = [ "REVUE" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Revue mensuelle de l'ensemble du système Life-NOC"
vars.instructions_url = "/life-noc/item/revue/revue-mensuelle-systeme-vie"
assign where host.name == "life-noc"
}
apply Service "revue-revue-trimestrielle-orientation" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/revue.yaml"
vars.life_noc_item_key = "revue-trimestrielle-orientation"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revue-trimestrielle-orientation"
groups = [ "REVUE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Revue trimestrielle des orientations de vie et de Chezlepro"
vars.instructions_url = "/life-noc/item/revue/revue-trimestrielle-orientation"
assign where host.name == "life-noc"
}

View file

@ -1,85 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: sante
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "sante-verification-trousse-premiers-soins" {
import "service_echeance"
vars.date_echeance = "2026-04-01"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "SANTE" ]
notes = "Vérification de la trousse de premiers soins"
vars.instructions_url = "/life-noc/item/sante/verification-trousse-premiers-soins"
assign where host.name == "life-noc"
}
apply Service "sante-verification-expiration-medicaments" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "days_until_due"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/sante.yaml"
vars.life_noc_item_key = "verification-expiration-medicaments"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-expiration-medicaments"
groups = [ "SANTE" ]
vars.life_noc_threshold_ok_lt = "366"
vars.life_noc_threshold_warning_lt = "90"
vars.life_noc_threshold_critical_lt = "30"
vars.life_noc_on_error = "critical"
notes = "Mettre la plus proche date d’expiration pertinente."
vars.instructions_url = "/life-noc/item/sante/verification-expiration-medicaments"
assign where host.name == "life-noc"
}
apply Service "sante-revision-rendez-vous-medicaux" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "days_until_due"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/sante.yaml"
vars.life_noc_item_key = "revision-rendez-vous-medicaux"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revision-rendez-vous-medicaux"
groups = [ "SANTE" ]
vars.life_noc_threshold_ok_lt = "366"
vars.life_noc_threshold_warning_lt = "14"
vars.life_noc_threshold_critical_lt = "2"
vars.life_noc_on_error = "critical"
notes = "Entrer la prochaine date significative déjà connue."
vars.instructions_url = "/life-noc/item/sante/revision-rendez-vous-medicaux"
assign where host.name == "life-noc"
}
apply Service "sante-verification-lunettes-prescriptions" {
import "service_echeance"
vars.date_echeance = "2026-06-01"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "SANTE" ]
notes = "Vérifier les prescriptions et besoins de renouvellement"
vars.instructions_url = "/life-noc/item/sante/verification-lunettes-prescriptions"
assign where host.name == "life-noc"
}
apply Service "sante-verification-dossier-sante" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/sante.yaml"
vars.life_noc_item_key = "verification-dossier-sante"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-dossier-sante"
groups = [ "SANTE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérifier l'ordre et l'accessibilité des documents de santé"
vars.instructions_url = "/life-noc/item/sante/verification-dossier-sante"
assign where host.name == "life-noc"
}

View file

@ -1,116 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: securite-chezlepro
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "securite-chezlepro-verification-mises-a-jour-securite" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/securite-chezlepro.yaml"
vars.life_noc_item_key = "verification-mises-a-jour-securite"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-mises-a-jour-securite"
groups = [ "SECURITE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérification des mises à jour de sécurité"
vars.instructions_url = "/life-noc/item/securite-chezlepro/verification-mises-a-jour-securite"
assign where host.name == "life-noc"
}
apply Service "securite-chezlepro-audit-comptes-acces" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/securite-chezlepro.yaml"
vars.life_noc_item_key = "audit-comptes-acces"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "audit-comptes-acces"
groups = [ "SECURITE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Audit des comptes et accès privilégiés"
vars.instructions_url = "/life-noc/item/securite-chezlepro/audit-comptes-acces"
assign where host.name == "life-noc"
}
apply Service "securite-chezlepro-verification-ids-snort" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/securite-chezlepro.yaml"
vars.life_noc_item_key = "verification-ids-snort"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-ids-snort"
groups = [ "SECURITE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification des IDS et de leur état"
vars.instructions_url = "/life-noc/item/securite-chezlepro/verification-ids-snort"
assign where host.name == "life-noc"
}
apply Service "securite-chezlepro-revue-pki-privee" {
import "service_echeance"
vars.date_echeance = "2026-05-15"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "SECURITE-CHEZLEPRO" ]
notes = "Revue de la PKI privée et des autorités intermédiaires"
vars.instructions_url = "/life-noc/item/securite-chezlepro/revue-pki-privee"
assign where host.name == "life-noc"
}
apply Service "securite-chezlepro-revue-politiques-securite" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/securite-chezlepro.yaml"
vars.life_noc_item_key = "revue-politiques-securite"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "revue-politiques-securite"
groups = [ "SECURITE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Revue des politiques et pratiques de sécurité numérique"
vars.instructions_url = "/life-noc/item/securite-chezlepro/revue-politiques-securite"
assign where host.name == "life-noc"
}
apply Service "securite-chezlepro-verification-sauvegardes-configuration" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/securite-chezlepro.yaml"
vars.life_noc_item_key = "verification-sauvegardes-configuration"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-sauvegardes-configuration"
groups = [ "SECURITE-CHEZLEPRO" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Vérifier les sauvegardes des configurations critiques"
vars.instructions_url = "/life-noc/item/securite-chezlepro/verification-sauvegardes-configuration"
assign where host.name == "life-noc"
}

View file

@ -1,139 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: stock-alimentaire
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "stock-alimentaire-rotation-nourriture-seche" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/stock-alimentaire.yaml"
vars.life_noc_item_key = "rotation-nourriture-seche"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "rotation-nourriture-seche"
groups = [ "STOCK-ALIMENTAIRE" ]
vars.life_noc_threshold_unknown_lt = "20"
vars.life_noc_threshold_ok_gte = "20"
vars.life_noc_threshold_warning_gte = "31"
vars.life_noc_threshold_critical_gte = "45"
vars.life_noc_on_error = "critical"
notes = "Rotation des stocks de nourriture sèche"
vars.instructions_url = "/life-noc/item/stock-alimentaire/rotation-nourriture-seche"
assign where host.name == "life-noc"
}
apply Service "stock-alimentaire-verification-reserve-eau" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "remaining_quantity"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/stock-alimentaire.yaml"
vars.life_noc_item_key = "verification-reserve-eau"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "verification-reserve-eau"
groups = [ "STOCK-ALIMENTAIRE" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Vérification de la réserve d'eau potable"
vars.instructions_url = "/life-noc/item/stock-alimentaire/verification-reserve-eau"
assign where host.name == "life-noc"
}
apply Service "stock-alimentaire-verification-mylar-absorbeurs" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "remaining_quantity"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/stock-alimentaire.yaml"
vars.life_noc_item_key = "verification-mylar-absorbeurs"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "verification-mylar-absorbeurs"
groups = [ "STOCK-ALIMENTAIRE" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Vérifier l'intégrité des emballages Mylar et absorbeurs"
vars.instructions_url = "/life-noc/item/stock-alimentaire/verification-mylar-absorbeurs"
assign where host.name == "life-noc"
}
apply Service "stock-alimentaire-revue-inventaire-conserves" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "remaining_quantity"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/stock-alimentaire.yaml"
vars.life_noc_item_key = "revue-inventaire-conserves"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "revue-inventaire-conserves"
groups = [ "STOCK-ALIMENTAIRE" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Revue des conserves et dates de rotation"
vars.instructions_url = "/life-noc/item/stock-alimentaire/revue-inventaire-conserves"
assign where host.name == "life-noc"
}
apply Service "stock-alimentaire-revue-inventaire-farine-riz-pates" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "remaining_quantity"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/stock-alimentaire.yaml"
vars.life_noc_item_key = "revue-inventaire-farine-riz-pates"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "revue-inventaire-farine-riz-pates"
groups = [ "STOCK-ALIMENTAIRE" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Vérification des gros stocks alimentaires de base"
vars.instructions_url = "/life-noc/item/stock-alimentaire/revue-inventaire-farine-riz-pates"
assign where host.name == "life-noc"
}
apply Service "stock-alimentaire-verification-bacs-legumes-racines" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "remaining_quantity"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/stock-alimentaire.yaml"
vars.life_noc_item_key = "verification-bacs-legumes-racines"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "verification-bacs-legumes-racines"
groups = [ "STOCK-ALIMENTAIRE" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Vérification des bacs de stockage de légumes racines"
vars.instructions_url = "/life-noc/item/stock-alimentaire/verification-bacs-legumes-racines"
assign where host.name == "life-noc"
}
apply Service "stock-alimentaire-revue-supplements-vitamines" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "remaining_quantity"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/stock-alimentaire.yaml"
vars.life_noc_item_key = "revue-supplements-vitamines"
vars.life_noc_metric_unit = "%"
vars.life_noc_label = "revue-supplements-vitamines"
groups = [ "STOCK-ALIMENTAIRE" ]
vars.life_noc_threshold_ok_gte = "50"
vars.life_noc_threshold_warning_lt = "50"
vars.life_noc_threshold_critical_lt = "25"
vars.life_noc_on_error = "critical"
notes = "Vérification du stock de suppléments et dates utiles"
vars.instructions_url = "/life-noc/item/stock-alimentaire/revue-supplements-vitamines"
assign where host.name == "life-noc"
}

View file

@ -1,185 +0,0 @@
/*
AUTO-GENERATED FILE - DOMAIN: voiture
Ne pas modifier manuellement.
Source: domains.yaml
*/
apply Service "voiture-verification-huile-moteur" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_distance"
vars.life_noc_source_type = "manual_counter"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/voiture.yaml"
vars.life_noc_item_key = "verification-huile-moteur"
vars.life_noc_metric_unit = "km"
vars.life_noc_label = "verification-huile-moteur"
groups = [ "VOITURE" ]
vars.life_noc_threshold_unknown_lt = "0"
vars.life_noc_threshold_ok_gte = "0"
vars.life_noc_threshold_warning_gte = "8000"
vars.life_noc_threshold_critical_gte = "10000"
vars.life_noc_on_error = "unknown"
notes = "Vérification de l'huile moteur"
vars.instructions_url = "/life-noc/item/voiture/verification-huile-moteur"
assign where host.name == "life-noc"
}
apply Service "voiture-inspection-freins" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_distance"
vars.life_noc_source_type = "manual_counter"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/voiture.yaml"
vars.life_noc_item_key = "inspection-freins"
vars.life_noc_metric_unit = "km"
vars.life_noc_label = "inspection-freins"
groups = [ "VOITURE" ]
vars.life_noc_threshold_unknown_lt = "0"
vars.life_noc_threshold_ok_gte = "0"
vars.life_noc_threshold_warning_gte = "15000"
vars.life_noc_threshold_critical_gte = "20000"
vars.life_noc_on_error = "unknown"
notes = "Inspection des freins"
vars.instructions_url = "/life-noc/item/voiture/inspection-freins"
assign where host.name == "life-noc"
}
apply Service "voiture-verification-pneus" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_distance"
vars.life_noc_source_type = "manual_counter"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/voiture.yaml"
vars.life_noc_item_key = "verification-pneus"
vars.life_noc_metric_unit = "km"
vars.life_noc_label = "verification-pneus"
groups = [ "VOITURE" ]
vars.life_noc_threshold_unknown_lt = "0"
vars.life_noc_threshold_ok_gte = "0"
vars.life_noc_threshold_warning_gte = "10000"
vars.life_noc_threshold_critical_gte = "12000"
vars.life_noc_on_error = "unknown"
notes = "Vérification usure, pression et permutation des pneus"
vars.instructions_url = "/life-noc/item/voiture/verification-pneus"
assign where host.name == "life-noc"
}
apply Service "voiture-ajustement-valves" {
import "service_echeance"
vars.date_echeance = "2026-08-01"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "VOITURE" ]
notes = "Vérification et ajustement des valves Honda Accord"
vars.instructions_url = "/life-noc/item/voiture/ajustement-valves"
assign where host.name == "life-noc"
}
apply Service "voiture-verification-timing-belt" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_distance"
vars.life_noc_source_type = "manual_counter"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/voiture.yaml"
vars.life_noc_item_key = "verification-timing-belt"
vars.life_noc_metric_unit = "km"
vars.life_noc_label = "verification-timing-belt"
groups = [ "VOITURE" ]
vars.life_noc_threshold_unknown_lt = "0"
vars.life_noc_threshold_ok_gte = "0"
vars.life_noc_threshold_warning_gte = "150000"
vars.life_noc_threshold_critical_gte = "168000"
vars.life_noc_on_error = "unknown"
notes = "Vérification de la courroie de distribution et pompe à eau"
vars.instructions_url = "/life-noc/item/voiture/verification-timing-belt"
assign where host.name == "life-noc"
}
apply Service "voiture-verification-batterie-voiture" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "current_value"
vars.life_noc_source_type = "manual_value"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/voiture.yaml"
vars.life_noc_item_key = "verification-batterie-voiture"
vars.life_noc_metric_unit = "volts"
vars.life_noc_label = "verification-batterie-voiture"
groups = [ "VOITURE" ]
vars.life_noc_threshold_ok_gte = "12.5"
vars.life_noc_threshold_warning_lt = "12.5"
vars.life_noc_threshold_critical_lt = "12.2"
vars.life_noc_on_error = "critical"
notes = "Vérification de l'état de la batterie automobile"
vars.instructions_url = "/life-noc/item/voiture/verification-batterie-voiture"
assign where host.name == "life-noc"
}
apply Service "voiture-verification-balais-essuie-glace" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/voiture.yaml"
vars.life_noc_item_key = "verification-balais-essuie-glace"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-balais-essuie-glace"
groups = [ "VOITURE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification des essuie-glaces"
vars.instructions_url = "/life-noc/item/voiture/verification-balais-essuie-glace"
assign where host.name == "life-noc"
}
apply Service "voiture-verification-liquides" {
import "service_echeance"
vars.date_echeance = "2026-04-15"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
groups = [ "VOITURE" ]
notes = "Vérification des liquides de la voiture"
vars.instructions_url = "/life-noc/item/voiture/verification-liquides"
assign where host.name == "life-noc"
}
apply Service "voiture-verification-eclairage" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "elapsed_time"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/voiture.yaml"
vars.life_noc_item_key = "verification-eclairage"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-eclairage"
groups = [ "VOITURE" ]
vars.life_noc_threshold_unknown_lt = "60"
vars.life_noc_threshold_ok_gte = "60"
vars.life_noc_threshold_warning_gte = "90"
vars.life_noc_threshold_critical_gte = "120"
vars.life_noc_on_error = "critical"
notes = "Vérification de l'éclairage et des phares"
vars.instructions_url = "/life-noc/item/voiture/verification-eclairage"
assign where host.name == "life-noc"
}
apply Service "voiture-verification-immatriculation-assurance" {
import "service_life_noc_probe"
vars.life_noc_probe_type = "days_until_due"
vars.life_noc_source_type = "manual_date"
vars.life_noc_source_value = ""
vars.life_noc_inputs_file = "/opt/life-noc/data/inputs/voiture.yaml"
vars.life_noc_item_key = "verification-immatriculation-assurance"
vars.life_noc_metric_unit = "days"
vars.life_noc_label = "verification-immatriculation-assurance"
groups = [ "VOITURE" ]
vars.life_noc_threshold_ok_lt = "366"
vars.life_noc_threshold_warning_lt = "90"
vars.life_noc_threshold_critical_lt = "30"
vars.life_noc_on_error = "critical"
notes = "Retenir la date la plus proche à renouveler."
vars.instructions_url = "/life-noc/item/voiture/verification-immatriculation-assurance"
assign where host.name == "life-noc"
}

View file

@ -1,17 +0,0 @@
template Service "service_echeance" {
import "generic-service"
check_command = "check_life_noc_mock"
vars.mock_state = "OK"
vars.mock_message = "Sous contrôle"
vars.warning_days = 14
vars.critical_days = 3
max_check_attempts = 1
check_interval = 1m
retry_interval = 30s
enable_notifications = false
}

View file

@ -1,5 +0,0 @@
template Service "service-focus" {
check_command = "dummy"
}

View file

@ -1,4 +0,0 @@
template Service "service_life_noc_probe" {
check_command = "check_life_noc_probe"
vars.life_noc_on_error = "critical"
}

View file

View file

@ -1,355 +0,0 @@
from __future__ import annotations
from copy import deepcopy
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import os
import tempfile
import yaml
DOMAINS_FILE = Path(os.environ.get("LIFE_NOC_DOMAINS_FILE", "domains.yaml"))
ALLOWED_PROBE_TYPES = [
"",
"elapsed_time",
"days_until_due",
"elapsed_distance",
"current_value",
"remaining_quantity",
]
ALLOWED_SOURCE_TYPES = [
"",
"manual_date",
"manual_counter",
"manual_value",
"mqtt",
"file_json",
"file_text",
"csv",
"api",
"command",
"derived",
]
ALLOWED_METRIC_UNITS = [
"",
"days",
"km",
"units",
"%",
"volts",
"litres",
"watts",
]
ALLOWED_ON_ERROR = ["", "critical", "warning", "unknown"]
ALLOWED_FORM_MODES = [
"",
"complete_date",
"due_date",
"counter_pair",
"numeric_value",
"remaining_quantity",
]
THRESHOLD_FIELDS = [
"unknown_lt",
"ok_gte",
"warning_gte",
"critical_gte",
"unknown_gte",
"ok_lt",
"warning_lt",
"critical_lt",
]
class DomainsError(ValueError):
pass
class DomainsConflictError(DomainsError):
pass
def _now_suffix() -> str:
return datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
def load_domains_document() -> dict[str, Any]:
if not DOMAINS_FILE.exists():
raise DomainsError(f'Fichier introuvable: {DOMAINS_FILE}')
data = yaml.safe_load(DOMAINS_FILE.read_text(encoding='utf-8'))
if not isinstance(data, dict):
raise DomainsError('domains.yaml invalide')
domains = data.get('domains')
if not isinstance(domains, dict):
raise DomainsError("domains.yaml invalide: clé 'domains' absente ou invalide")
return data
def save_domains_document(doc: dict[str, Any], create_backup: bool = True) -> Path:
if not isinstance(doc, dict) or not isinstance(doc.get('domains'), dict):
raise DomainsError("document domains invalide")
target = DOMAINS_FILE
target.parent.mkdir(parents=True, exist_ok=True)
rendered = yaml.safe_dump(doc, sort_keys=False, allow_unicode=True, width=1000)
if create_backup and target.exists():
backup = target.with_suffix(target.suffix + f'.bak.{_now_suffix()}')
backup.write_text(target.read_text(encoding='utf-8'), encoding='utf-8')
fd, tmp_name = tempfile.mkstemp(prefix=target.name + '.', dir=str(target.parent))
try:
with os.fdopen(fd, 'w', encoding='utf-8') as handle:
handle.write(rendered)
os.replace(tmp_name, target)
finally:
if os.path.exists(tmp_name):
os.unlink(tmp_name)
return target
def list_domains() -> list[str]:
doc = load_domains_document()
return list(doc['domains'].keys())
def list_domain_items(domain: str) -> list[dict[str, Any]]:
doc = load_domains_document()
items = doc['domains'].get(domain)
if not isinstance(items, list):
raise KeyError(domain)
return items
def get_domain_item(domain: str, item_key: str) -> dict[str, Any]:
items = list_domain_items(domain)
for item in items:
if isinstance(item, dict) and str(item.get('name', '')).strip() == item_key:
return deepcopy(item)
raise KeyError(item_key)
def _find_item_index(items: list[dict[str, Any]], item_key: str) -> int:
for index, item in enumerate(items):
if isinstance(item, dict) and str(item.get('name', '')).strip() == item_key:
return index
raise KeyError(item_key)
def _clean_value(value: Any) -> Any:
if isinstance(value, dict):
cleaned = {}
for key, subvalue in value.items():
candidate = _clean_value(subvalue)
if candidate in ('', None, {}, []):
continue
cleaned[key] = candidate
return cleaned
if isinstance(value, list):
cleaned_list = [_clean_value(v) for v in value]
return [v for v in cleaned_list if v not in ('', None, {}, [])]
return value
def _parse_number(value: Any) -> Any:
if value is None:
return None
text = str(value).strip()
if text == '':
return None
try:
if any(ch in text for ch in ('.', 'e', 'E')):
number = float(text)
return int(number) if number.is_integer() else number
return int(text)
except ValueError:
raise DomainsError(f'Valeur numérique invalide: {text}')
def _coerce_bool(value: Any) -> bool:
return str(value).strip().lower() in {'1', 'true', 'yes', 'on'}
def _validate_choice(label: str, value: str, allowed: list[str]) -> str:
if value not in allowed:
raise DomainsError(f'{label} invalide: {value}')
return value
def normalize_item_payload(form: dict[str, Any], existing_item: dict[str, Any] | None = None) -> dict[str, Any]:
base = deepcopy(existing_item) if existing_item else {}
name = str(form.get('name', base.get('name', ''))).strip()
if not name:
raise DomainsError("Le champ 'name' est obligatoire.")
item: dict[str, Any] = {'name': name}
date_value = str(form.get('date', base.get('date', ''))).strip()
if date_value:
item['date'] = date_value
for field in ['title', 'summary', 'notes', 'instructions', 'notes_url', 'instructions_url', 'action_url']:
raw = form.get(field, base.get(field, ''))
value = str(raw).strip() if raw is not None else ''
if value:
item[field] = value
probe_type = str(form.get('probe_type', base.get('probe', {}).get('type', ''))).strip()
source_type = str(form.get('probe_source_type', base.get('probe', {}).get('source', {}).get('type', ''))).strip()
inputs_file = str(form.get('probe_inputs_file', base.get('probe', {}).get('source', {}).get('inputs_file', ''))).strip()
source_item_key = str(form.get('probe_item_key', base.get('probe', {}).get('source', {}).get('item_key', ''))).strip()
metric_unit = str(form.get('metric_unit', base.get('probe', {}).get('metric', {}).get('unit', ''))).strip()
on_error = str(form.get('policy_on_error', base.get('probe', {}).get('policy', {}).get('on_error', ''))).strip()
_validate_choice('probe.type', probe_type, ALLOWED_PROBE_TYPES)
_validate_choice('probe.source.type', source_type, ALLOWED_SOURCE_TYPES)
_validate_choice('metric.unit', metric_unit, ALLOWED_METRIC_UNITS)
_validate_choice('policy.on_error', on_error, ALLOWED_ON_ERROR)
thresholds: dict[str, Any] = {}
base_thresholds = base.get('probe', {}).get('thresholds', {}) if isinstance(base.get('probe'), dict) else {}
for field in THRESHOLD_FIELDS:
raw = form.get(field, base_thresholds.get(field, ''))
parsed = _parse_number(raw)
if parsed is not None:
thresholds[field] = parsed
if probe_type or source_type or inputs_file or source_item_key or metric_unit or thresholds or on_error:
probe: dict[str, Any] = {}
if probe_type:
probe['type'] = probe_type
source: dict[str, Any] = {}
if source_type:
source['type'] = source_type
if inputs_file:
source['inputs_file'] = inputs_file
if source_item_key:
source['item_key'] = source_item_key
if source:
probe['source'] = source
if metric_unit:
probe['metric'] = {'unit': metric_unit}
if thresholds:
probe['thresholds'] = thresholds
if on_error:
probe['policy'] = {'on_error': on_error}
item['probe'] = probe
form_mode = str(form.get('ui_form_mode', base.get('ui', {}).get('form_mode', ''))).strip()
_validate_choice('ui.form_mode', form_mode, ALLOWED_FORM_MODES)
allow_complete = _coerce_bool(form.get('ui_allow_complete', base.get('ui', {}).get('allow_complete', False)))
allow_manual_edit = _coerce_bool(form.get('ui_allow_manual_edit', base.get('ui', {}).get('allow_manual_edit', False)))
if form_mode or allow_complete or allow_manual_edit:
ui: dict[str, Any] = {}
if form_mode:
ui['form_mode'] = form_mode
if allow_complete:
ui['allow_complete'] = True
if allow_manual_edit:
ui['allow_manual_edit'] = True
item['ui'] = ui
normalized = _clean_value(item)
_validate_item_structure(normalized)
return normalized
def _validate_item_structure(item: dict[str, Any]) -> None:
if 'name' not in item or not str(item['name']).strip():
raise DomainsError("Le champ 'name' est obligatoire.")
probe = item.get('probe')
if probe is None:
return
if not isinstance(probe, dict):
raise DomainsError('probe doit être un objet')
if 'type' not in probe:
raise DomainsError("probe.type est requis dès qu'un probe est défini")
source = probe.get('source')
if source is not None and not isinstance(source, dict):
raise DomainsError('probe.source doit être un objet')
metric = probe.get('metric')
if metric is not None and not isinstance(metric, dict):
raise DomainsError('probe.metric doit être un objet')
thresholds = probe.get('thresholds')
if thresholds is not None and not isinstance(thresholds, dict):
raise DomainsError('probe.thresholds doit être un objet')
def upsert_item(domain: str, item: dict[str, Any], original_item_key: str | None = None) -> Path:
doc = load_domains_document()
items = doc['domains'].get(domain)
if not isinstance(items, list):
raise KeyError(domain)
existing_names = [str(entry.get('name', '')).strip() for entry in items if isinstance(entry, dict)]
new_name = str(item['name']).strip()
if new_name in existing_names and original_item_key != new_name:
raise DomainsConflictError(f"Un item nommé '{new_name}' existe déjà dans le domaine '{domain}'.")
if original_item_key:
index = _find_item_index(items, original_item_key)
items[index] = item
else:
items.append(item)
return save_domains_document(doc)
def delete_item(domain: str, item_key: str) -> Path:
doc = load_domains_document()
items = doc['domains'].get(domain)
if not isinstance(items, list):
raise KeyError(domain)
index = _find_item_index(items, item_key)
items.pop(index)
return save_domains_document(doc)
def reorder_item(domain: str, item_key: str, direction: str) -> Path:
if direction not in {'up', 'down'}:
raise DomainsError('direction invalide')
doc = load_domains_document()
items = doc['domains'].get(domain)
if not isinstance(items, list):
raise KeyError(domain)
index = _find_item_index(items, item_key)
if direction == 'up' and index > 0:
items[index - 1], items[index] = items[index], items[index - 1]
elif direction == 'down' and index < len(items) - 1:
items[index + 1], items[index] = items[index], items[index + 1]
return save_domains_document(doc)
def item_to_form_values(item: dict[str, Any] | None, domain: str = '') -> dict[str, Any]:
item = deepcopy(item) if item else {}
probe = item.get('probe', {}) if isinstance(item.get('probe'), dict) else {}
source = probe.get('source', {}) if isinstance(probe.get('source'), dict) else {}
metric = probe.get('metric', {}) if isinstance(probe.get('metric'), dict) else {}
thresholds = probe.get('thresholds', {}) if isinstance(probe.get('thresholds'), dict) else {}
policy = probe.get('policy', {}) if isinstance(probe.get('policy'), dict) else {}
ui = item.get('ui', {}) if isinstance(item.get('ui'), dict) else {}
values = {
'domain': domain,
'name': item.get('name', ''),
'date': item.get('date', ''),
'title': item.get('title', ''),
'summary': item.get('summary', ''),
'notes': item.get('notes', ''),
'instructions': item.get('instructions', ''),
'notes_url': item.get('notes_url', ''),
'instructions_url': item.get('instructions_url', ''),
'action_url': item.get('action_url', ''),
'probe_type': probe.get('type', ''),
'probe_source_type': source.get('type', ''),
'probe_inputs_file': source.get('inputs_file', ''),
'probe_item_key': source.get('item_key', ''),
'metric_unit': metric.get('unit', ''),
'policy_on_error': policy.get('on_error', ''),
'ui_form_mode': ui.get('form_mode', ''),
'ui_allow_complete': bool(ui.get('allow_complete', False)),
'ui_allow_manual_edit': bool(ui.get('allow_manual_edit', False)),
}
for field in THRESHOLD_FIELDS:
values[field] = thresholds.get(field, '')
return values

View file

@ -1,223 +0,0 @@
from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
import yaml
INPUTS_DIR = Path("data/inputs")
DOMAINS_FILE = Path("domains.yaml")
def utc_now_iso() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def utc_today_date() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%d")
def domain_file(domain: str) -> Path:
return INPUTS_DIR / f"{domain}.yaml"
def load_domain(domain: str) -> dict:
path = domain_file(domain)
if not path.exists():
return {}
data = yaml.safe_load(path.read_text(encoding="utf-8"))
if data is None:
return {}
if not isinstance(data, dict):
raise ValueError(f"Fichier invalide: {path}")
return data
def save_domain(domain: str, data: dict) -> Path:
path = domain_file(domain)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
yaml.safe_dump(data, sort_keys=False, allow_unicode=True),
encoding="utf-8",
)
return path
def list_items(domain: str) -> list[str]:
return list(load_domain(domain).keys())
def get_item(domain: str, item_key: str) -> dict:
data = load_domain(domain)
if item_key not in data:
raise KeyError(item_key)
item = data[item_key]
if not isinstance(item, dict):
raise ValueError(f"Entrée invalide pour {item_key}")
return item
def set_item(domain: str, item_key: str, value: str, origin: str = "manual") -> dict:
data = load_domain(domain)
data[item_key] = {
"value": value,
"captured_at": utc_now_iso(),
"origin": origin,
}
save_domain(domain, data)
return data[item_key]
def set_counter_pair(domain: str, item_key: str, current_value: str, reference_value: str, origin: str = "manual") -> dict:
data = load_domain(domain)
data[item_key] = {
"value": current_value,
"reference_value": reference_value,
"captured_at": utc_now_iso(),
"origin": origin,
}
save_domain(domain, data)
return data[item_key]
def complete_item(domain: str, item_key: str, origin: str = "manual") -> dict:
return set_item(domain, item_key, utc_today_date(), origin=origin)
def load_domains_definition() -> dict:
if not DOMAINS_FILE.exists():
raise ValueError(f"Fichier introuvable: {DOMAINS_FILE}")
data = yaml.safe_load(DOMAINS_FILE.read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise ValueError("domains.yaml invalide")
domains = data.get("domains")
if not isinstance(domains, dict):
raise ValueError("domains.yaml invalide: clé 'domains' absente ou invalide")
return domains
def get_defined_service(domain: str, item_key: str) -> dict:
domains = load_domains_definition()
items = domains.get(domain)
if not isinstance(items, list):
raise KeyError(domain)
for item in items:
if isinstance(item, dict) and item.get("name") == item_key:
return item
raise KeyError(item_key)
def compute_state_for_item(domain: str, item_key: str) -> str:
service = get_defined_service(domain, item_key)
probe = service.get("probe")
if not isinstance(probe, dict):
return "MOCK"
probe_type = str(probe.get("type", "")).strip()
source = probe.get("source", {})
thresholds = probe.get("thresholds", {})
metric = probe.get("metric", {})
source_type = str(source.get("type", "")).strip()
metric_unit = str(metric.get("unit", "")).strip()
item = get_item(domain, item_key)
if probe_type in {"elapsed_time", "days_until_due"}:
if source_type != "manual_date":
return "CRITICAL"
if metric_unit != "days":
return "CRITICAL"
value = str(item.get("value", "")).strip()
dt = datetime.strptime(value, "%Y-%m-%d").replace(tzinfo=timezone.utc)
now = datetime.now(timezone.utc)
if probe_type == "elapsed_time":
days = (now - dt).total_seconds() / 86400.0
if "critical_gte" in thresholds and days >= float(thresholds["critical_gte"]):
return "CRITICAL"
if "warning_gte" in thresholds and days >= float(thresholds["warning_gte"]):
return "WARNING"
if "ok_gte" in thresholds and days >= float(thresholds["ok_gte"]):
return "OK"
if "unknown_lt" in thresholds and days < float(thresholds["unknown_lt"]):
return "UNKNOWN"
return "CRITICAL"
days = (dt - now).total_seconds() / 86400.0
if "critical_lt" in thresholds and days < float(thresholds["critical_lt"]):
return "CRITICAL"
if "warning_lt" in thresholds and days < float(thresholds["warning_lt"]):
return "WARNING"
if "ok_lt" in thresholds and days < float(thresholds["ok_lt"]):
return "OK"
if "unknown_gte" in thresholds and days >= float(thresholds["unknown_gte"]):
return "UNKNOWN"
return "CRITICAL"
if probe_type == "elapsed_distance":
if source_type != "manual_counter":
return "CRITICAL"
if metric_unit != "km":
return "CRITICAL"
current_value = float(str(item.get("value", "")).strip())
reference_value = float(str(item.get("reference_value", "")).strip())
distance = current_value - reference_value
if "unknown_lt" in thresholds and distance < float(thresholds["unknown_lt"]):
return "UNKNOWN"
if "critical_gte" in thresholds and distance >= float(thresholds["critical_gte"]):
return "CRITICAL"
if "warning_gte" in thresholds and distance >= float(thresholds["warning_gte"]):
return "WARNING"
if "ok_gte" in thresholds and distance >= float(thresholds["ok_gte"]):
return "OK"
return "CRITICAL"
if probe_type == "remaining_quantity":
if source_type != "manual_value":
return "CRITICAL"
if metric_unit not in {"%", "units", "litres"}:
return "CRITICAL"
value = float(str(item.get("value", "")).strip())
if "critical_lt" in thresholds and value < float(thresholds["critical_lt"]):
return "CRITICAL"
if "warning_lt" in thresholds and value < float(thresholds["warning_lt"]):
return "WARNING"
if "ok_gte" in thresholds and value >= float(thresholds["ok_gte"]):
return "OK"
if "unknown_gte" in thresholds and value >= float(thresholds["unknown_gte"]):
return "UNKNOWN"
return "CRITICAL"
if probe_type == "current_value":
if source_type != "manual_value":
return "CRITICAL"
if metric_unit not in {"%", "units", "litres", "volts", "watts"}:
return "CRITICAL"
value = float(str(item.get("value", "")).strip())
if "critical_lt" in thresholds and value < float(thresholds["critical_lt"]):
return "CRITICAL"
if "critical_gte" in thresholds and value >= float(thresholds["critical_gte"]):
return "CRITICAL"
if "warning_lt" in thresholds and value < float(thresholds["warning_lt"]):
return "WARNING"
if "warning_gte" in thresholds and value >= float(thresholds["warning_gte"]):
return "WARNING"
if "ok_gte" in thresholds and value >= float(thresholds["ok_gte"]):
return "OK"
if "ok_lt" in thresholds and value < float(thresholds["ok_lt"]):
return "OK"
if "unknown_gte" in thresholds and value >= float(thresholds["unknown_gte"]):
return "UNKNOWN"
if "unknown_lt" in thresholds and value < float(thresholds["unknown_lt"]):
return "UNKNOWN"
return "CRITICAL"
return "CRITICAL"

3
lifenoc/__init__.py Normal file
View file

@ -0,0 +1,3 @@
"""Life-NOC : un système de pilotage personnel. Voir README.md."""
__version__ = "1.0.0"

99
lifenoc/__main__.py Normal file
View file

@ -0,0 +1,99 @@
"""Life-NOC en ligne de commande. `python3 -m lifenoc --help`."""
from __future__ import annotations
import argparse
import sys
from . import moteur
from .donnees import Donnees, trier
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(prog="lifenoc", description="Life-NOC — voir clair, prioriser juste, "
"agir au bon endroit. Données : $LIFENOC_DONNEES (défaut ./donnees).")
ap.add_argument("--donnees", help="dossier des données (remplace $LIFENOC_DONNEES)")
sous = ap.add_subparsers(dest="commande", required=True)
s = sous.add_parser("servir", help="servir les deux écrans")
s.add_argument("--hote", default="127.0.0.1")
s.add_argument("--port", type=int, default=8787)
sous.add_parser("personnes", help="lister les personnes suivies")
a = sous.add_parser("ajouter", help="ajouter une personne")
a.add_argument("ident", help="identifiant (minuscules, chiffres, tirets)")
a.add_argument("nom", help="nom affiché")
e = sous.add_parser("etat", help="les états d'une personne, dans le terminal")
e.add_argument("personne")
e.add_argument("--tout", action="store_true", help="inclure ce qui n'est pas encore dû")
n = sous.add_parser("noter", help="noter un geste : fait, echeance, valeur, compteur, entretien, reference")
n.add_argument("personne")
n.add_argument("element", help="domaine/element")
n.add_argument("geste")
n.add_argument("saisie", nargs="?", default="")
sous.add_parser("verifier", help="relire toutes les données (code 1 si faute)")
m = sous.add_parser("migrer", help="verser l'ancien Life-NOC (domains.yaml) dans la réserve")
m.add_argument("ancien", help="chemin de l'ancien dépôt")
args = ap.parse_args(argv)
d = Donnees(args.donnees)
try:
if args.commande == "servir":
from .web import servir
servir(args.hote, args.port, d)
elif args.commande == "personnes":
for p in d.personnes():
print(f"{p.id:20} {p.nom}")
elif args.commande == "ajouter":
print(f"ajoutée : {d.creer_personne(args.ident, args.nom).id}")
elif args.commande == "etat":
for l in trier(d.personne(args.personne).lignes()):
if args.tout or l.etat.couleur != moteur.GRIS:
print(f"{l.etat.couleur.upper():7} {l.cle:55} {l.etat.message}")
elif args.commande == "noter":
p = d.personne(args.personne)
domaine, _, nom = args.element.partition("/")
p.noter(domaine, nom, args.geste, args.saisie, par="terminal")
print(p.ligne(domaine, nom).etat.message)
elif args.commande == "verifier":
return _verifier(d)
elif args.commande == "migrer":
from .migrer import migrer
for ligne in migrer(args.ancien, d):
print(ligne)
except KeyError as exc:
print(f"introuvable : {exc.args[0] if exc.args else ''}", file=sys.stderr)
return 1
except (ValueError, OSError) as exc:
print(f"refusé : {exc}", file=sys.stderr)
return 1
return 0
def _verifier(d: Donnees) -> int:
fautes = []
for domaine, items in d.reserve().items():
fautes += [f"réserve {domaine}/{nom} : {f}" for nom, e in items.items() for f in moteur.verifier_element(e)]
total = 0
for p in d.personnes():
elements = p.elements()
for domaine, items in elements.items():
total += len(items)
fautes += [f"{p.id} {domaine}/{nom} : {f}" for nom, e in items.items() for f in moteur.verifier_element(e)]
cles = {f"{dm}/{n}" for dm, items in elements.items() for n in items}
for o in sorted(set(p.intrants()) - cles):
print(f"ORPHELIN {p.id} {o} : une valeur sans élément (retiré à la main ?)")
for f in fautes:
print(f"FAUTE {f}")
print(f"{len(d.personnes())} personne(s), {total} élément(s) suivis, {len(fautes)} faute(s)")
return 1 if fautes else 0
if __name__ == "__main__":
sys.exit(main())

295
lifenoc/donnees.py Normal file
View file

@ -0,0 +1,295 @@
"""Les données de Life-NOC : des fichiers texte, lisibles à la main, un dossier par personne.
donnees/ ($LIFENOC_DONNEES, défaut ./donnees)
reserve.yaml des éléments prêts à l'emploi, où l'on puise
personnes/<id>/
personne.yaml {nom: Daniel}
elements.yaml ce qui est suivi pour cette personne (l'écran de configuration)
intrants.yaml la dernière valeur de chaque élément (les gestes)
journal.tsv chaque geste, une ligne, jamais réécrit
Les fichiers sont relus à chaque demande : une modification à la main ne demande aucun
redémarrage.
"""
from __future__ import annotations
import os
import re
import threading
import unicodedata
from dataclasses import dataclass
from datetime import date, datetime, timezone
from pathlib import Path
from zoneinfo import ZoneInfo
import yaml
from . import moteur
FUSEAU = ZoneInfo(os.environ.get("LIFENOC_FUSEAU", "America/Toronto"))
IDENT = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$")
_verrou = threading.RLock()
ENTETE_ELEMENTS = """\
# Life-NOC — ce qui est suivi. Modifiable par l'écran de configuration ou à la main.
#
# domaine:
# nom-de-l-element:
# titre: Ce que la personne lit
# notes: Une phrase, sur la carte
# instructions: Les étapes, dans les mots de la personne
# liens: {Mode d'emploi: https://…}
# UNE mesure, trois seuils [à faire, pressé, en retard] :
# depuis: [5, 7, 10] jours depuis la dernière fois
# avant: [30, 14, 7] jours avant l'échéance notée
# km: [7000, 8000, 9000] km depuis le dernier entretien
# reste: [50, 25, 10] ce qui reste (avec `unite: "%"`, "V", …)
# si_erreur: gris (facultatif ; par défaut une donnée illisible est rouge)
"""
def aujourdhui() -> date:
"""La date du jour à l'heure de la personne, pas à celle du serveur (souvent UTC)."""
return datetime.now(FUSEAU).date()
def maintenant_utc() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def identifiant(texte: str) -> str:
"""« Vérification du propane » → « verification-du-propane »."""
t = unicodedata.normalize("NFKD", texte).encode("ascii", "ignore").decode().lower()
return re.sub(r"[^a-z0-9]+", "-", t).strip("-")[:63]
class _Dumper(yaml.SafeDumper):
pass
_Dumper.add_representer(list, lambda d, data: d.represent_sequence(
"tag:yaml.org,2002:seq", data, flow_style=all(isinstance(x, (int, float)) for x in data)))
def dump_elements(elements: dict) -> str:
return ENTETE_ELEMENTS + yaml.dump(elements, Dumper=_Dumper, allow_unicode=True,
sort_keys=False, width=100)
def _lire_yaml(chemin: Path, defaut):
if not chemin.exists():
return defaut
return yaml.safe_load(chemin.read_text(encoding="utf-8")) or defaut
def _ecrire(chemin: Path, texte: str) -> None:
"""Écriture atomique : un fichier à moitié écrit ne remplace jamais le bon."""
chemin.parent.mkdir(parents=True, exist_ok=True)
tmp = chemin.with_suffix(chemin.suffix + ".tmp")
tmp.write_text(texte, encoding="utf-8")
os.replace(tmp, chemin)
def _forme_elements(data, chemin) -> dict[str, dict[str, dict]]:
if not isinstance(data, dict) or not all(
isinstance(d, str) and isinstance(items, dict) for d, items in data.items()):
raise ValueError(f"{chemin} : attendu {{domaine: {{élément: définition}}}}")
return {d: {str(n): (e or {}) for n, e in items.items()} for d, items in data.items()}
@dataclass(frozen=True)
class Ligne:
domaine: str
nom: str
element: dict
intrant: dict | None
etat: moteur.Etat
@property
def cle(self) -> str:
return f"{self.domaine}/{self.nom}"
@property
def titre(self) -> str:
return self.element.get("titre") or self.nom.replace("-", " ").capitalize()
def trier(lignes: list[Ligne]) -> list[Ligne]:
return sorted(lignes, key=lambda l: (moteur.ORDRE[l.etat.couleur], -l.etat.poids))
class Personne:
"""Le dossier d'une personne : ce qui est suivi pour elle, et ce qu'elle a fait."""
def __init__(self, dossier: Path):
self.dossier = dossier
self.id = dossier.name
self.f_personne = dossier / "personne.yaml"
self.f_elements = dossier / "elements.yaml"
self.f_intrants = dossier / "intrants.yaml"
self.f_journal = dossier / "journal.tsv"
@property
def nom(self) -> str:
return str(_lire_yaml(self.f_personne, {}).get("nom") or self.id)
# --- lecture -----------------------------------------------------------------------------
def elements(self) -> dict[str, dict[str, dict]]:
return _forme_elements(_lire_yaml(self.f_elements, {}), self.f_elements)
def intrants(self) -> dict[str, dict]:
data = _lire_yaml(self.f_intrants, {})
if not isinstance(data, dict):
raise ValueError(f"{self.f_intrants} : attendu {{domaine/élément: intrant}}")
return data
def lignes(self, jour: date | None = None) -> list[Ligne]:
jour = jour or aujourdhui()
intrants = self.intrants()
return [Ligne(d, n, e, intrants.get(f"{d}/{n}"), moteur.evaluer(e, intrants.get(f"{d}/{n}"), jour))
for d, items in self.elements().items() for n, e in items.items()]
def ligne(self, domaine: str, nom: str, jour: date | None = None) -> Ligne:
element = self.elements().get(domaine, {}).get(nom)
if element is None:
raise KeyError(f"{domaine}/{nom}")
intrant = self.intrants().get(f"{domaine}/{nom}")
return Ligne(domaine, nom, element, intrant, moteur.evaluer(element, intrant, jour or aujourdhui()))
def journal(self, cle: str | None = None, combien: int = 20) -> list[list[str]]:
"""Les derniers gestes (d'un élément, ou de tous), le plus récent d'abord."""
if not self.f_journal.exists():
return []
lignes = [l.split("\t") for l in self.f_journal.read_text(encoding="utf-8").splitlines()]
return [l for l in lignes if len(l) >= 4 and (cle is None or l[1] == cle)][-combien:][::-1]
# --- les gestes ----------------------------------------------------------------------------
def noter(self, domaine: str, nom: str, geste: str, saisie: str = "", par: str = "page") -> dict:
"""Applique un geste ; garde l'intrant précédent pour pouvoir annuler. Lève KeyError / ValueError."""
with _verrou:
element = self.elements().get(domaine, {}).get(nom)
if element is None:
raise KeyError(f"{domaine}/{nom}")
cle = f"{domaine}/{nom}"
intrants = self.intrants()
ancien = intrants.get(cle)
nouveau = moteur.noter(element, ancien, geste, saisie, aujourdhui())
nouveau.update(le=maintenant_utc(), par=par[:40],
precedent={k: v for k, v in ancien.items() if k != "precedent"} if ancien else None)
intrants[cle] = nouveau
self._ecrire_intrants(intrants)
self._journaliser(cle, geste, nouveau.get("valeur", nouveau.get("reference", "")), par)
return nouveau
def annuler(self, domaine: str, nom: str, par: str = "page") -> None:
"""Revient à l'intrant d'avant le dernier geste (un seul niveau)."""
with _verrou:
cle = f"{domaine}/{nom}"
intrants = self.intrants()
if cle not in intrants or "precedent" not in intrants[cle]:
raise ValueError("rien à annuler")
precedent = intrants[cle]["precedent"]
if precedent is None:
del intrants[cle]
else:
intrants[cle] = precedent
self._ecrire_intrants(intrants)
self._journaliser(cle, "annuler", (precedent or {}).get("valeur", ""), par)
# --- la configuration ----------------------------------------------------------------------
def ecrire_elements(self, elements: dict) -> None:
with _verrou:
_ecrire(self.f_elements, dump_elements(elements))
def poser_element(self, domaine: str, nom: str, element: dict, ancien: tuple[str, str] | None = None) -> None:
"""Ajoute ou remplace un élément. `ancien` : sa place d'avant, s'il change de domaine."""
fautes = moteur.verifier_element(element)
if fautes:
raise ValueError(" ; ".join(fautes))
if not IDENT.match(domaine) or not IDENT.match(nom):
raise ValueError("domaine et nom : lettres minuscules, chiffres et tirets")
with _verrou:
elements = self.elements()
if ancien and ancien != (domaine, nom):
elements.get(ancien[0], {}).pop(ancien[1], None)
if not elements.get(ancien[0]):
elements.pop(ancien[0], None)
intrants = self.intrants()
if f"{ancien[0]}/{ancien[1]}" in intrants:
intrants[f"{domaine}/{nom}"] = intrants.pop(f"{ancien[0]}/{ancien[1]}")
self._ecrire_intrants(intrants)
elif ancien is None and nom in elements.get(domaine, {}):
raise ValueError(f"« {domaine}/{nom} » existe déjà")
elements.setdefault(domaine, {})[nom] = element
self.ecrire_elements(elements)
def retirer_element(self, domaine: str, nom: str) -> None:
"""Retire un élément et sa dernière valeur ; le journal garde l'histoire."""
with _verrou:
elements = self.elements()
if nom not in elements.get(domaine, {}):
raise KeyError(f"{domaine}/{nom}")
del elements[domaine][nom]
if not elements[domaine]:
del elements[domaine]
self.ecrire_elements(elements)
intrants = self.intrants()
if intrants.pop(f"{domaine}/{nom}", None) is not None:
self._ecrire_intrants(intrants)
self._journaliser(f"{domaine}/{nom}", "retirer", "", "configuration")
# --- interne -------------------------------------------------------------------------------
def _ecrire_intrants(self, intrants: dict) -> None:
_ecrire(self.f_intrants, yaml.safe_dump(intrants, allow_unicode=True, sort_keys=True))
def _journaliser(self, cle: str, geste: str, valeur, par: str) -> None:
self.dossier.mkdir(parents=True, exist_ok=True)
with self.f_journal.open("a", encoding="utf-8") as j:
j.write("\t".join([maintenant_utc(), cle, geste, str(valeur), par[:40]]) + "\n")
class Donnees:
"""La racine : les personnes suivies, et la réserve où l'on puise des éléments."""
def __init__(self, racine: str | Path | None = None):
self.racine = Path(racine or os.environ.get("LIFENOC_DONNEES", "donnees"))
self.f_reserve = self.racine / "reserve.yaml"
self.d_personnes = self.racine / "personnes"
def personnes(self) -> list[Personne]:
if not self.d_personnes.is_dir():
return []
return sorted((Personne(d) for d in self.d_personnes.iterdir() if d.is_dir() and IDENT.match(d.name)),
key=lambda p: p.nom.lower())
def personne(self, ident: str) -> Personne:
"""Lève KeyError si l'identifiant est invalide ou inconnu (jamais de chemin hors du dossier)."""
if not IDENT.match(ident or "") or not (self.d_personnes / ident).is_dir():
raise KeyError(ident)
return Personne(self.d_personnes / ident)
def creer_personne(self, ident: str, nom: str) -> Personne:
if not IDENT.match(ident or ""):
raise ValueError("identifiant : lettres minuscules, chiffres et tirets")
if not (nom or "").strip():
raise ValueError("le nom manque")
with _verrou:
if (self.d_personnes / ident).exists():
raise ValueError(f"« {ident} » existe déjà")
p = Personne(self.d_personnes / ident)
_ecrire(p.f_personne, yaml.safe_dump({"nom": nom.strip()}, allow_unicode=True))
return p
def reserve(self) -> dict[str, dict[str, dict]]:
return _forme_elements(_lire_yaml(self.f_reserve, {}), self.f_reserve)
def ecrire_reserve(self, elements: dict) -> None:
with _verrou:
_ecrire(self.f_reserve, dump_elements(elements).replace(
"ce qui est suivi. Modifiable", "la réserve : des éléments prêts à l'emploi. Modifiable", 1))

105
lifenoc/gabarit.py Normal file
View file

@ -0,0 +1,105 @@
"""Le gabarit commun des pages : styles, en-tête, dates en mots. Aucun script : la page marche
sans JavaScript, et la politique de sécurité du contenu l'interdit de toute façon."""
from __future__ import annotations
from datetime import date
from html import escape
from urllib.parse import quote
from .moteur import GRIS, ORANGE, ROUGE, VERT
JOURS = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"]
MOIS = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août",
"septembre", "octobre", "novembre", "décembre"]
# Ce que lit la personne aidée : des mots, pas seulement des couleurs.
MOTS = {ROUGE: "En retard", ORANGE: "À faire vite", VERT: "À faire", GRIS: "Pas encore"}
CSS = """
:root{--fond:#f3f5f8;--carte:#fff;--trait:#d5dce6;--texte:#15202c;--doux:#56616f;
--rouge:#c33232;--orange:#c46f0c;--vert:#22804a;--gris:#7b8594;--lien:#1a5aa0;--accent:#1a5aa0}
@media (prefers-color-scheme:dark){:root{--fond:#0e141b;--carte:#17212c;--trait:#283544;
--texte:#e6ebf1;--doux:#9aa7b6;--rouge:#e65b5b;--orange:#ec9a3c;--vert:#45b878;--gris:#77838f;
--lien:#86b8ef;--accent:#86b8ef}}
*{box-sizing:border-box}
body{margin:0;background:var(--fond);color:var(--texte);font:16px/1.45 system-ui,sans-serif}
main{max-width:900px;margin:0 auto;padding:16px}
a{color:var(--lien)}
h1{font-size:1.4rem;margin:0}h2{font-size:1.05rem;margin:24px 0 8px;color:var(--doux)}
.c-rouge{--c:var(--rouge)}.c-orange{--c:var(--orange)}.c-vert{--c:var(--vert)}.c-gris{--c:var(--gris)}
.pastille{display:inline-block;padding:2px 10px;border-radius:99px;background:var(--c);color:#fff;
font-size:.85em;font-weight:600;white-space:nowrap}
.bloc{background:var(--carte);border:1px solid var(--trait);border-radius:10px;padding:12px 16px;margin:10px 0}
.bloc p{margin:.3em 0;white-space:pre-line}
.doux{color:var(--doux)}
button,.bouton{font:inherit;padding:8px 16px;border-radius:8px;border:1px solid var(--trait);
background:var(--carte);color:var(--texte);cursor:pointer;text-decoration:none;display:inline-block}
button.principal,.bouton.principal{background:var(--accent);border-color:var(--accent);color:var(--fond);font-weight:600}
input,select,textarea{font:inherit;padding:8px 10px;border-radius:8px;border:1px solid var(--trait);
background:var(--fond);color:var(--texte);max-width:100%}
form.ligne{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:8px 0}
.bandeau{background:var(--carte);border:2px solid var(--vert);border-radius:10px;padding:10px 14px;
display:flex;gap:12px;align-items:center;justify-content:space-between;flex-wrap:wrap}
.bandeau form{margin:0}
/* --- l'écran de la personne aidée : grand, peu de choses, des mots --- */
body.aidee{font-size:20px}
.aidee main{max-width:560px}
.aidee .salut{margin:4px 0 16px}.aidee .salut h1{font-size:1.5rem}.aidee .salut p{margin:0;color:var(--doux)}
.carte{background:var(--carte);border:1px solid var(--trait);border-left:10px solid var(--c);
border-radius:14px;padding:14px 16px;margin:0 0 14px}
.carte h2{color:var(--texte);font-size:1.15em;margin:6px 0 2px}
.carte h2 a{color:inherit;text-decoration:none}
.carte p{margin:4px 0;color:var(--doux)}
.aidee button,.aidee .bouton{min-height:56px;padding:10px 22px;border-radius:12px;font-size:1em}
.aidee .fait{width:100%;margin-top:10px}
.aidee input{min-height:52px;font-size:1em}
.repos{text-align:center;padding:28px 16px}.repos b{display:block;font-size:1.3em;margin-bottom:6px}
.pied{text-align:center;margin:24px 0;font-size:.85em}
/* --- l'écran de configuration et de supervision --- */
.entete{display:flex;justify-content:space-between;align-items:baseline;flex-wrap:wrap;gap:4px 16px;
border-bottom:1px solid var(--trait);padding-bottom:10px;margin-bottom:8px}
.entete nav a{margin-left:12px}
.compte{display:flex;gap:8px;flex-wrap:wrap;margin:12px 0}
.compte span{flex:1;min-width:100px;background:var(--carte);border:1px solid var(--trait);
border-left:6px solid var(--c);border-radius:8px;padding:6px 12px}.compte b{font-size:1.4rem;display:block}
table{border-collapse:collapse;width:100%}
td,th{padding:6px 8px;border-top:1px solid var(--trait);text-align:left;vertical-align:top}
th{color:var(--doux);font-weight:600;font-size:.9rem}
td.etat{border-left:5px solid var(--c);white-space:nowrap;width:9em}
table.fixe{table-layout:fixed}td.date{width:7em}
label.choix{display:inline;margin:0;font-weight:normal}
.outils{display:flex;gap:8px;flex-wrap:wrap;margin:12px 0}
label{display:block;margin:12px 0 4px;font-weight:600}
.aide{font-weight:normal;color:var(--doux);font-size:.9rem}
.seuils{display:flex;gap:8px;flex-wrap:wrap}.seuils input{width:8em}
.fautes{border-color:var(--rouge)}
.etiquettes{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px}
.etiquette{border:1px dashed var(--trait);border-radius:8px;padding:10px;text-align:center;break-inside:avoid}
.etiquette svg{width:150px;height:150px}.etiquette b{display:block;margin-top:6px}
@media print{.entete nav,.outils,.non-imprime{display:none}body{background:#fff;color:#000}
.etiquette{border-color:#999}}
"""
def url(*parties: str) -> str:
return "/" + "/".join(quote(str(p), safe="") for p in parties)
def date_en_mots(d: date, avec_jour: bool = True) -> str:
texte = f"{d.day} {MOIS[d.month - 1]}"
return f"{JOURS[d.weekday()]} {texte}" if avec_jour else texte
def page(titre: str, corps: str, classe: str = "", rafraichir: bool = False) -> str:
meta = '<meta http-equiv="refresh" content="300">' if rafraichir else ""
return (f'<!doctype html><html lang="fr"><head><meta charset="utf-8">'
f'<meta name="viewport" content="width=device-width,initial-scale=1">{meta}'
f'<title>{escape(titre)}</title><style>{CSS}</style></head>'
f'<body class="{classe}"><main>{corps}</main></body></html>')
def cache(nom: str, valeur: str) -> str:
return f'<input type="hidden" name="{escape(nom)}" value="{escape(valeur)}">'

94
lifenoc/migrer.py Normal file
View file

@ -0,0 +1,94 @@
"""Verse les définitions de l'ancien Life-NOC (domains.yaml) dans la réserve de la v1.
Ne modifie pas l'ancien dépôt. Refuse d'écraser une réserve qui a déjà des éléments.
ancien v1
probe.type elapsed_time [ok_gte, warning_gte, critical_gte] → depuis: [a, p, r]
probe.type elapsed_distance [ok_gte, warning_gte, critical_gte] → km: [a, p, r]
probe.type days_until_due [ok_lt, warning_lt, critical_lt] → avant: [a, p, r]
probe.type remaining_quantity / current_value
[ok_gte, warning_lt, critical_lt] → reste: [a, p, r]
policy.on_error unknown → si_erreur: gris
title / summary + notes / instructions / *_url → titre / notes / instructions / liens
"""
from __future__ import annotations
from pathlib import Path
import yaml
from . import moteur
from .donnees import Donnees
CORRESPONDANCE = {
"elapsed_time": ("depuis", ("ok_gte", "warning_gte", "critical_gte")),
"elapsed_distance": ("km", ("ok_gte", "warning_gte", "critical_gte")),
"days_until_due": ("avant", ("ok_lt", "warning_lt", "critical_lt")),
"remaining_quantity": ("reste", ("ok_gte", "warning_lt", "critical_lt")),
"current_value": ("reste", ("ok_gte", "warning_lt", "critical_lt")),
}
UNITES = {"%": "%", "volts": "V", "units": "unités", "litres": "litres"}
LIENS = (("notes_url", "Notes"), ("instructions_url", "Instructions"), ("action_url", "Action"))
def _nombre(x):
x = float(x)
return int(x) if x.is_integer() else x
def convertir_element(ancien: dict) -> dict:
e: dict = {}
if ancien.get("title"):
e["titre"] = ancien["title"]
notes = [str(ancien[k]).strip() for k in ("summary", "notes") if str(ancien.get(k) or "").strip()]
if notes:
e["notes"] = "\n".join(dict.fromkeys(notes))
if str(ancien.get("instructions") or "").strip():
e["instructions"] = str(ancien["instructions"]).strip()
liens = {libelle: ancien[k] for k, libelle in LIENS if str(ancien.get(k) or "").startswith("http")}
if liens:
e["liens"] = liens
probe = ancien.get("probe")
if isinstance(probe, dict):
mesure, cles = CORRESPONDANCE[probe["type"]]
seuils = probe.get("thresholds", {})
e[mesure] = [_nombre(seuils[c]) for c in cles]
if mesure == "reste":
unite = str(probe.get("metric", {}).get("unit", ""))
e["unite"] = UNITES.get(unite, unite)
if probe.get("policy", {}).get("on_error") == "unknown":
e["si_erreur"] = moteur.GRIS
return e
def migrer(ancien_depot: str | Path, donnees: Donnees) -> list[str]:
"""Verse les définitions de l'ancien Life-NOC dans la réserve ; rend le compte rendu.
Les anciennes valeurs ne sont pas reprises : elles n'ont jamais été réelles (preuve de concept).
On puise ensuite dans la réserve, par l'écran de configuration, ce qui sera vraiment suivi.
"""
ancien_depot = Path(ancien_depot)
if donnees.reserve():
raise ValueError(f"{donnees.f_reserve} contient déjà des éléments : je n'écrase rien")
domaines = yaml.safe_load((ancien_depot / "domains.yaml").read_text(encoding="utf-8"))["domains"]
reserve: dict = {}
sans_mesure, fautes = [], []
for domaine, items in domaines.items():
reserve[domaine] = {}
for ancien in items:
nom = ancien["name"]
e = convertir_element(ancien)
reserve[domaine][nom] = e
fautes += [f"{domaine}/{nom} : {f}" for f in moteur.verifier_element(e)]
if moteur.mesure_de(e) is None:
sans_mesure.append(f"{domaine}/{nom}")
if fautes:
raise ValueError("conversion invalide :\n " + "\n ".join(fautes))
donnees.ecrire_reserve(reserve)
n = sum(len(i) for i in reserve.values())
rapport = [f"{len(reserve)} domaines, {n} éléments versés dans la réserve", f"écrit : {donnees.f_reserve}"]
if sans_mesure:
rapport.append(f"{len(sans_mesure)} sans mesure (simulés dans l'ancien) : " + ", ".join(sans_mesure))
return rapport

232
lifenoc/moteur.py Normal file
View file

@ -0,0 +1,232 @@
"""Le moteur de Life-NOC : un élément, son dernier intrant, la date du jour → un état.
Quatre mesures, une seule règle : trois seuils [à faire, pressé, en retard].
depuis: [a, p, r] jours écoulés depuis la dernière fois (monte avec l'urgence)
km: [a, p, r] kilomètres depuis le dernier entretien (monte avec l'urgence)
avant: [a, p, r] jours qui restent avant l'échéance (baisse avec l'urgence)
reste: [a, p, r] ce qui reste d'un stock, d'une charge, etc. (baisse avec l'urgence)
Les états gardent le sens de Life-NOC :
GRIS pas encore dû — rien à faire, l'écran le tait
VERT c'est le bon moment pour s'en occuper
ORANGE il faut presser
ROUGE en retard, ou impossible à évaluer
Un élément jamais noté est VERT et `a_noter` : c'est le moment de dire quand on l'a fait la
dernière fois, pas une alarme. Une donnée illisible est ROUGE (sauf `si_erreur: gris`) : une
erreur ne doit jamais rester invisible. Ce module ne lit ni n'écrit aucun fichier.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
GRIS, VERT, ORANGE, ROUGE = "gris", "vert", "orange", "rouge"
ORDRE = {ROUGE: 0, ORANGE: 1, VERT: 2, GRIS: 3}
MONTANTES = ("depuis", "km")
DESCENDANTES = ("avant", "reste")
MESURES = MONTANTES + DESCENDANTES
# Ce qu'un élément peut porter. Une clé inconnue est refusée : une faute de frappe ne passe pas.
CLES = {"titre", "notes", "instructions", "liens", "unite", "si_erreur", *MESURES}
# Les gestes possibles pour chaque mesure.
GESTES = {
"depuis": ("fait",), # « c'est fait » (aujourd'hui, ou à la date donnée)
"avant": ("echeance",), # « la prochaine échéance est le … »
"km": ("compteur", "entretien", "reference"), # compteur actuel / entretien fait / dernier entretien
"reste": ("valeur",), # « il en reste … »
}
@dataclass(frozen=True)
class Etat:
couleur: str
message: str
# Pour trier : plus c'est grand, plus c'est loin dans l'urgence (dans une même couleur).
poids: float = 0.0
# Jamais noté : la personne doit d'abord dire où elle en est.
a_noter: bool = False
def mesure_de(element: dict) -> str | None:
"""Le mot-clé de mesure que porte l'élément, ou None s'il n'en porte aucun."""
presentes = [m for m in MESURES if m in element]
return presentes[0] if len(presentes) == 1 else None
def verifier_element(element) -> list[str]:
"""Les fautes de définition d'un élément ; une liste vide veut dire qu'il est bon."""
if not isinstance(element, dict):
return ["un élément doit être un dictionnaire"]
fautes = [f"clé inconnue : `{c}`" for c in sorted(set(element) - CLES)]
presentes = [m for m in MESURES if m in element]
if len(presentes) > 1:
fautes.append(f"une seule mesure par élément, pas {', '.join(presentes)}")
for m in presentes:
seuils = element[m]
if (not isinstance(seuils, list) or len(seuils) != 3
or not all(isinstance(s, (int, float)) and not isinstance(s, bool) for s in seuils)):
fautes.append(f"`{m}` : trois nombres attendus, [à faire, pressé, en retard]")
continue
a, p, r = seuils
if m in MONTANTES and not a <= p <= r:
fautes.append(f"`{m}` : les seuils doivent monter (à faire ≤ pressé ≤ en retard), reçu {seuils}")
if m in DESCENDANTES and not a >= p >= r:
fautes.append(f"`{m}` : les seuils doivent descendre (à faire ≥ pressé ≥ en retard), reçu {seuils}")
if element.get("si_erreur", ROUGE) not in (ROUGE, GRIS):
fautes.append("`si_erreur` : `rouge` (défaut) ou `gris`")
liens = element.get("liens", {})
if not isinstance(liens, dict) or not all(
isinstance(u, str) and u.startswith(("https://", "http://")) for u in liens.values()):
fautes.append("`liens` : un dictionnaire libellé → adresse http(s)")
return fautes
def jours(n: float) -> str:
n = int(n)
return f"{n} jour" if abs(n) <= 1 else f"{n} jours"
def nombre(x: float) -> str:
return f"{x:g}"
def lire_date(valeur) -> date:
if isinstance(valeur, date):
return valeur
return date.fromisoformat(str(valeur).strip())
def _classer_montant(v: float, seuils: list) -> tuple[str, float]:
a, p, r = seuils
if v >= r:
return ROUGE, v - r
if v >= p:
return ORANGE, v - p
if v >= a:
return VERT, v - a
return GRIS, v - a
def _classer_descendant(v: float, seuils: list) -> tuple[str, float]:
a, p, r = seuils
if v < r:
return ROUGE, r - v
if v < p:
return ORANGE, p - v
if v < a:
return VERT, a - v
return GRIS, a - v
A_NOTER = {
"depuis": "jamais noté — quand l'avez-vous fait la dernière fois ?",
"avant": "échéance à noter",
"km": "compteur à noter",
"reste": "quantité à noter",
}
def evaluer(element: dict, intrant: dict | None, aujourdhui: date) -> Etat:
"""L'état d'un élément. Ne lève jamais : une erreur devient un état."""
fautes = verifier_element(element)
if fautes:
return Etat(ROUGE, "définition invalide : " + " ; ".join(fautes), 1e9)
mesure = mesure_de(element)
if mesure is None:
return Etat(GRIS, "aucune mesure définie", -1e9)
if not intrant or intrant.get("valeur") in (None, ""):
return Etat(VERT, A_NOTER[mesure], 0.0, a_noter=True)
if mesure == "km" and intrant.get("reference") in (None, ""):
return Etat(VERT, "compteur du dernier entretien à noter", 0.0, a_noter=True)
try:
return _evaluer(mesure, element, intrant, aujourdhui)
except (KeyError, TypeError, ValueError) as exc:
couleur = GRIS if element.get("si_erreur") == GRIS else ROUGE
return Etat(couleur, f"donnée illisible ({exc})", 1e9 if couleur == ROUGE else -1e9)
def _evaluer(mesure: str, element: dict, intrant: dict, aujourdhui: date) -> Etat:
seuils = element[mesure]
a, p, r = seuils
if mesure == "depuis":
ecoules = (aujourdhui - lire_date(intrant["valeur"])).days
if ecoules < 0:
return Etat(ROUGE, f"date dans le futur ({intrant['valeur']})", 1e9)
couleur, poids = _classer_montant(ecoules, seuils)
base = "fait aujourd'hui" if ecoules == 0 else f"fait il y a {jours(ecoules)}"
suite = {
GRIS: f"à faire dans {jours(a - ecoules)}",
VERT: f"pressé dans {jours(p - ecoules)}",
ORANGE: f"en retard dans {jours(r - ecoules)}",
ROUGE: f"en retard de {jours(ecoules - r)}" if ecoules > r else "en retard",
}[couleur]
return Etat(couleur, f"{base} — {suite}", poids)
if mesure == "avant":
restants = (lire_date(intrant["valeur"]) - aujourdhui).days
couleur, poids = _classer_descendant(restants, seuils)
if restants < 0:
base = f"échéance dépassée de {jours(-restants)}"
elif restants == 0:
base = "échéance aujourd'hui"
else:
base = f"échéance dans {jours(restants)}"
if couleur == GRIS:
base += f" — à faire dans {jours(restants - a + 1)}"
return Etat(couleur, base, poids)
if mesure == "km":
distance = float(intrant["valeur"]) - float(intrant["reference"])
if distance < 0:
return Etat(ROUGE, "compteur plus bas que celui du dernier entretien", 1e9)
couleur, poids = _classer_montant(distance, seuils)
suite = {
GRIS: f"à faire dans {nombre(a - distance)} km",
VERT: f"pressé dans {nombre(p - distance)} km",
ORANGE: f"en retard dans {nombre(r - distance)} km",
ROUGE: "en retard",
}[couleur]
return Etat(couleur, f"{nombre(distance)} km depuis le dernier entretien — {suite}", poids)
# reste
valeur = float(intrant["valeur"])
unite = element.get("unite", "")
texte = f"{nombre(valeur)} {unite}".strip()
couleur, poids = _classer_descendant(valeur, seuils)
return Etat(couleur, f"il reste {texte}", poids)
def noter(element: dict, intrant: dict | None, geste: str, saisie: str, aujourdhui: date) -> dict:
"""Le nouvel intrant après un geste. Lève ValueError si le geste ou la saisie ne va pas."""
mesure = mesure_de(element)
if mesure is None or geste not in GESTES[mesure]:
raise ValueError(f"geste « {geste} » impossible pour cet élément")
saisie = (saisie or "").strip()
nouveau = {k: v for k, v in (intrant or {}).items() if k in ("valeur", "reference")}
if geste == "fait":
jour = lire_date(saisie) if saisie else aujourdhui
if jour > aujourdhui:
raise ValueError("on ne peut pas avoir fait une chose demain")
nouveau["valeur"] = jour.isoformat()
elif geste == "echeance":
if not saisie:
raise ValueError("la date de l'échéance manque")
nouveau["valeur"] = lire_date(saisie).isoformat()
else:
if not saisie:
raise ValueError("le nombre manque")
n = float(saisie.replace(",", ".").replace(" ", ""))
if geste == "reference":
nouveau["reference"] = nombre(n)
else:
nouveau["valeur"] = nombre(n)
if geste == "entretien":
nouveau["reference"] = nombre(n)
return nouveau

141
lifenoc/vue_aidee.py Normal file
View file

@ -0,0 +1,141 @@
"""L'écran de la personne aidée : le petit écran du téléphone.
Elle ne voit ni seuil, ni domaine, ni configuration : ce qui est à faire maintenant, en mots,
et un gros bouton. Quand rien n'est dû, l'écran le dit. Un geste se défait d'un toucher.
"""
from __future__ import annotations
from html import escape
from . import moteur
from .donnees import Ligne, Personne, aujourdhui, trier
from .gabarit import MOTS, cache, date_en_mots, page, url
from .moteur import GRIS
def _court(l: Ligne) -> str:
"""Le message sans la mécanique des seuils : « fait il y a 8 jours »."""
if l.etat.a_noter:
return {"depuis": "Quand l'avez-vous fait la dernière fois ?", "avant": "Quelle est la prochaine date ?",
"km": "Que dit le compteur ?", "reste": "Combien en reste-t-il ?"}.get(
moteur.mesure_de(l.element), l.etat.message)
texte = l.etat.message.split(" — ")[0]
return texte[:1].upper() + texte[1:]
def _cible(p: Personne, l: Ligne) -> str:
return url("p", p.id, "e", l.domaine, l.nom)
def _carte(p: Personne, l: Ligne) -> str:
mesure = moteur.mesure_de(l.element)
retour = cache("retour", url("p", p.id) + "/")
if mesure == "depuis" and l.etat.a_noter:
action = (f'<form method="post" action="{_cible(p, l)}">{retour}'
f'<button class="principal fait" name="geste" value="fait">C\'est fait aujourd\'hui</button></form>'
f'<form class="ligne" method="post" action="{_cible(p, l)}">{retour}<span class="doux">ou le</span>'
f'<input type="date" name="saisie" required max="{aujourdhui().isoformat()}" '
f'aria-label="date de la dernière fois"><button name="geste" value="fait">Noter</button></form>')
elif mesure == "depuis":
action = (f'<form method="post" action="{_cible(p, l)}">{retour}'
f'<button class="principal fait" name="geste" value="fait">C\'est fait</button></form>')
else:
action = f'<a class="bouton principal fait" href="{_cible(p, l)}">Noter</a>'
notes = f"<p>{escape(str(l.element['notes']))}</p>" if l.element.get("notes") else ""
return (f'<section class="carte c-{l.etat.couleur}"><span class="pastille">{MOTS[l.etat.couleur]}</span>'
f'<h2><a href="{_cible(p, l)}">{escape(l.titre)}</a></h2>{notes}'
f"<p>{escape(_court(l))}</p>{action}</section>")
def _bandeau(p: Personne, cle: str | None) -> str:
if not cle or "/" not in cle:
return ""
domaine, _, nom = cle.partition("/")
try:
titre = p.ligne(domaine, nom).titre
except KeyError:
return ""
return (f'<div class="bandeau" role="status"><span>Noté : {escape(titre)}.</span>'
f'<form method="post" action="{url("p", p.id, "annuler")}">{cache("cle", cle)}'
f"<button>Annuler</button></form></div><p></p>")
def accueil(p: Personne, note: str | None = None) -> str:
lignes = p.lignes()
actifs = trier([l for l in lignes if l.etat.couleur != GRIS])
salut = (f'<div class="salut"><h1>Bonjour {escape(p.nom)}</h1>'
f"<p>{date_en_mots(aujourdhui()).capitalize()}</p></div>")
if actifs:
corps = "".join(_carte(p, l) for l in actifs)
else:
prochains = [l for l in lignes if l.etat.couleur == GRIS and " — " in l.etat.message
and moteur.mesure_de(l.element) in ("depuis", "avant")]
suite = ""
if prochains:
l = max(prochains, key=lambda l: l.etat.poids)
quand = l.etat.message.split(" — ")[1].replace("à faire ", "")
suite = f'<p class="doux">Prochaine chose : {escape(l.titre)}, {escape(quand)}.</p>'
vide = "Rien n'est suivi pour l'instant." if not lignes else "Tout est fait pour aujourd'hui."
corps = f'<section class="carte c-vert repos"><b>{vide}</b>{suite}</section>'
pied = f'<p class="pied"><a href="{url("p", p.id, "tout")}">Tout voir</a></p>'
return page(f"Life-NOC — {p.nom}", salut + _bandeau(p, note) + corps + pied, "aidee", rafraichir=True)
def tout(p: Personne) -> str:
rangs = "".join(
f'<section class="carte c-{l.etat.couleur}"><span class="pastille">{MOTS[l.etat.couleur]}</span>'
f'<h2><a href="{_cible(p, l)}">{escape(l.titre)}</a></h2><p>{escape(_court(l))}</p></section>'
for l in trier(p.lignes()))
return page(f"Life-NOC — {p.nom}",
f'<p><a href="{url("p", p.id)}/">← Retour</a></p><div class="salut"><h1>Tout</h1></div>{rangs}',
"aidee")
def _formulaire(p: Personne, l: Ligne, geste: str, etiquette: str, champ: str, principal: bool = True) -> str:
classe = ' class="principal"' if principal else ""
return (f'<form class="ligne" method="post" action="{_cible(p, l)}">{cache("retour", url("p", p.id) + "/")}'
f'{champ}<button{classe} name="geste" value="{geste}">{etiquette}</button></form>')
def element(p: Personne, domaine: str, nom: str) -> str:
l = p.ligne(domaine, nom)
mesure = moteur.mesure_de(l.element)
max_ = aujourdhui().isoformat()
nombre = '<input name="saisie" inputmode="decimal" required size="8" aria-label="{}">'
gestes = ""
if mesure == "depuis":
gestes = (_formulaire(p, l, "fait", "C'est fait aujourd'hui", "")
+ _formulaire(p, l, "fait", "Noter cette date",
f'<input type="date" name="saisie" required max="{max_}" aria-label="autre date">',
principal=False))
elif mesure == "avant":
gestes = _formulaire(p, l, "echeance", "Noter",
'<input type="date" name="saisie" required aria-label="prochaine échéance">')
elif mesure == "km":
gestes = (_formulaire(p, l, "compteur", "Noter le compteur", nombre.format("compteur") + " km")
+ _formulaire(p, l, "entretien", "Entretien fait à ce compteur",
nombre.format("compteur de l'entretien") + " km", principal=False))
if not (l.intrant or {}).get("reference"):
gestes += _formulaire(p, l, "reference", "Noter le dernier entretien",
nombre.format("compteur au dernier entretien") + " km", principal=False)
elif mesure == "reste":
unite = escape(str(l.element.get("unite", "")))
gestes = _formulaire(p, l, "valeur", "Noter", nombre.format("ce qui reste") + f" {unite}")
derniere = ""
if l.intrant and l.intrant.get("valeur") and mesure in ("depuis",):
try:
derniere = f'<p class="doux">Dernière fois : {date_en_mots(moteur.lire_date(l.intrant["valeur"]))}</p>'
except ValueError:
pass
morceaux = [f'<p><a href="{url("p", p.id)}/">← Retour</a></p>',
f'<section class="carte c-{l.etat.couleur}"><span class="pastille">{MOTS[l.etat.couleur]}</span>'
f"<h2>{escape(l.titre)}</h2><p>{escape(_court(l))}</p>{derniere}{gestes}</section>"]
for cle in ("notes", "instructions"):
if l.element.get(cle):
morceaux.append(f'<div class="bloc"><p>{escape(str(l.element[cle]))}</p></div>')
if l.element.get("liens"):
morceaux.append('<div class="bloc">' + "<br>".join(
f'<a href="{escape(u)}" rel="noopener">{escape(n)}</a>' for n, u in l.element["liens"].items())
+ "</div>")
return page(l.titre, "".join(morceaux), "aidee")

249
lifenoc/vue_config.py Normal file
View file

@ -0,0 +1,249 @@
"""L'écran de configuration et de supervision : pour la personne qui configure (souvent un proche
aidant). Elle crée et règle les éléments, puise dans la réserve, imprime les codes QR, et voit
où en est la personne aidée. Elle voit seulement : aucune notification ne part d'ici.
"""
from __future__ import annotations
from collections import Counter
from html import escape
from . import moteur
from .donnees import Donnees, Personne, identifiant, trier
from .gabarit import MOTS, cache, page, url
from .moteur import GRIS, ORANGE, ORDRE, ROUGE, VERT
MESURES = {
"": ("Aucune mesure", ""),
"depuis": ("Revient régulièrement", "jours depuis la dernière fois : à faire à partir de…, pressé à…, en retard à…"),
"avant": ("Échéance", "jours avant l'échéance : à faire quand il en reste moins de…, pressé sous…, en retard sous…"),
"km": ("Kilométrage", "km depuis le dernier entretien : à faire à partir de…, pressé à…, en retard à…"),
"reste": ("Quantité qui reste", "ce qui reste : à faire sous…, pressé sous…, en retard sous…"),
}
GESTES = {"fait": "Fait", "echeance": "Échéance", "valeur": "Valeur", "compteur": "Compteur",
"entretien": "Entretien", "reference": "Dernier entretien", "annuler": "Annulé", "retirer": "Retiré"}
def _entete(titre: str, p: Personne | None = None) -> str:
nav = '<a href="/config/">Personnes</a>'
if p is not None:
nav += (f'<a href="{url("config", p.id)}/">Supervision</a>'
f'<a href="{url("p", p.id)}/">Écran de {escape(p.nom)} ↗</a>')
return f'<div class="entete"><h1>{escape(titre)}</h1><nav>{nav}</nav></div>'
def _comptes(lignes) -> str:
c = Counter(l.etat.couleur for l in lignes)
return '<div class="compte">' + "".join(
f'<span class="c-{k}"><b>{c.get(k, 0)}</b>{MOTS[k].lower()}</span>' for k in (ROUGE, ORANGE, VERT, GRIS)) + "</div>"
def _fautes(fautes: list[str]) -> str:
if not fautes:
return ""
return '<div class="bloc fautes"><b>À corriger</b>' + "".join(f"<p>{escape(f)}</p>" for f in fautes) + "</div>"
# --- les personnes ---------------------------------------------------------------------------
def personnes(d: Donnees, fautes: list[str] | None = None, valeurs: dict | None = None) -> str:
valeurs = valeurs or {}
rangs = []
for p in d.personnes():
try:
lignes = p.lignes()
pire = min((l.etat.couleur for l in lignes), key=ORDRE.get, default=GRIS)
resume = ", ".join(f"{n} {MOTS[k].lower()}" for k in (ROUGE, ORANGE, VERT)
if (n := sum(1 for l in lignes if l.etat.couleur == k))) or "rien à faire"
except ValueError as exc:
pire, resume = ROUGE, f"données illisibles : {exc}"
rangs.append(f'<tr><td class="etat c-{pire}"><a href="{url("config", p.id)}/">{escape(p.nom)}</a></td>'
f'<td>{escape(resume)}</td><td><a href="{url("p", p.id)}/">son écran ↗</a></td></tr>')
table = (f"<table><tr><th>Personne</th><th>Maintenant</th><th></th></tr>{''.join(rangs)}</table>"
if rangs else '<p class="doux">Aucune personne pour l’instant.</p>')
ajout = (f'<h2>Ajouter une personne</h2>{_fautes(fautes or [])}<form method="post" action="/config/">'
f'<label>Nom affiché<input name="nom" required value="{escape(valeurs.get("nom", ""))}"></label>'
f'<label>Identifiant <span class="aide">(dans les adresses ; laissé vide, il vient du nom)</span>'
f'<input name="ident" pattern="[a-z0-9][a-z0-9-]*" value="{escape(valeurs.get("ident", ""))}"></label>'
f'<p><button class="principal">Ajouter</button></p></form>')
return page("Life-NOC — configuration", _entete("Personnes suivies") + table + ajout)
# --- la supervision d'une personne ------------------------------------------------------------
def supervision(p: Personne) -> str:
lignes = p.lignes()
outils = (f'<div class="outils"><a class="bouton principal" href="{url("config", p.id, "nouveau")}">'
f'Ajouter un élément</a><a class="bouton" href="{url("config", p.id, "reserve")}">Puiser dans la réserve</a>'
f'<a class="bouton" href="{url("config", p.id, "qr")}">Codes QR</a>'
f'<a class="bouton" href="{url("config", p.id, "journal")}">Journal</a></div>')
groupes: dict[str, list] = {}
for l in lignes:
groupes.setdefault(l.domaine, []).append(l)
corps = []
for domaine, ls in groupes.items():
rangs = "".join(
f'<tr><td class="etat c-{l.etat.couleur}">{MOTS[l.etat.couleur]}</td>'
f'<td><a href="{url("config", p.id, "e", l.domaine, l.nom)}">{escape(l.titre)}</a>'
f'<br><span class="doux">{escape(l.etat.message)}</span></td>'
f'<td class="doux date">{escape(str((l.intrant or {}).get("le", ""))[:10])}</td></tr>'
for l in trier(ls))
corps.append(f'<h2>{escape(domaine)}</h2><table class="fixe">{rangs}</table>')
if not lignes:
corps.append('<p class="doux">Rien n’est suivi. Ajoutez un élément, ou puisez dans la réserve.</p>')
return page(f"Supervision — {p.nom}", _entete(p.nom, p) + _comptes(lignes) + outils + "".join(corps))
def journal(p: Personne) -> str:
titres = {l.cle: l.titre for l in p.lignes()}
rangs = "".join(f"<tr><td>{escape(j[0].replace('T', ' ').rstrip('Z'))}</td>"
f"<td>{escape(titres.get(j[1], j[1]))}</td><td>{escape(GESTES.get(j[2], j[2]))}</td>"
f"<td>{escape(j[3])}</td><td class=\"doux\">{escape(j[4] if len(j) > 4 else '')}</td></tr>"
for j in p.journal(combien=200))
table = (f"<table><tr><th>Quand (UTC)</th><th>Élément</th><th>Geste</th><th>Valeur</th><th>Par</th></tr>{rangs}</table>"
if rangs else '<p class="doux">Aucun geste pour l’instant.</p>')
return page(f"Journal — {p.nom}", _entete(f"Journal — {p.nom}", p) + table)
# --- un élément : créer, modifier, retirer ----------------------------------------------------
def formulaire(p: Personne, domaine: str = "", nom: str = "", element: dict | None = None,
fautes: list[str] | None = None, nouveau: bool = True) -> str:
e = element or {}
mesure = moteur.mesure_de(e) or ""
seuils = e.get(mesure, ["", "", ""]) if mesure else ["", "", ""]
liens = "\n".join(f"{n} {u}" for n, u in (e.get("liens") or {}).items())
domaines = "".join(f'<option value="{escape(d)}">' for d in p.elements())
choix = "".join(f'<option value="{k}"{" selected" if k == mesure else ""}>{escape(v[0])}</option>'
for k, v in MESURES.items())
aides = "".join(f"<br>• <b>{escape(v[0])}</b> : {escape(v[1])}" for k, v in MESURES.items() if k)
action = url("config", p.id, "nouveau") if nouveau else url("config", p.id, "e", domaine, nom)
ident = ("" if nouveau else f'<p class="doux">Identifiant : {escape(domaine)}/{escape(nom)} '
"(il ne change pas : les codes QR imprimés en dépendent)</p>")
champs = (
f'{_fautes(fautes or [])}<form method="post" action="{action}">{ident}'
f'<label>Titre <span class="aide">(ce que la personne lit)</span>'
f'<input name="titre" required size="50" value="{escape(str(e.get("titre", "")))}"></label>'
f'<label>Domaine <span class="aide">(pour ranger : maison, santé, voiture…)</span>'
f'<input name="domaine" list="domaines" required value="{escape(domaine)}"{"" if nouveau else " readonly"}></label>'
f'<datalist id="domaines">{domaines}</datalist>'
f'<label>Note courte <span class="aide">(une phrase, sur la carte)</span>'
f'<input name="notes" size="60" value="{escape(str(e.get("notes", "")))}"></label>'
f'<label>Instructions <span class="aide">(les étapes, dans les mots de la personne)</span>'
f'<textarea name="instructions" rows="4" cols="60">{escape(str(e.get("instructions", "")))}</textarea></label>'
f'<label>Mesure<select name="mesure">{choix}</select></label>'
f'<p class="aide">{aides[4:]}</p>'
f'<label>Seuils <span class="aide">(à faire, pressé, en retard)</span></label><div class="seuils">'
+ "".join(f'<input name="s{i}" inputmode="decimal" aria-label="{t}" placeholder="{t}" value="{escape(str(seuils[i]))}">'
for i, t in enumerate(("à faire", "pressé", "en retard")))
+ f'</div><label>Unité <span class="aide">(pour une quantité : %, litres, V…)</span>'
f'<input name="unite" size="10" value="{escape(str(e.get("unite", "")))}"></label>'
f'<label>Liens <span class="aide">(un par ligne : libellé puis adresse)</span>'
f'<textarea name="liens" rows="2" cols="60">{escape(liens)}</textarea></label>'
+ (cache("si_erreur", e["si_erreur"]) if e.get("si_erreur") else "")
+ '<p><button class="principal">Enregistrer</button></p></form>')
retrait = ""
if not nouveau:
retrait = (f'<h2>Retirer cet élément</h2><form class="ligne" method="post" '
f'action="{url("config", p.id, "e", domaine, nom, "retirer")}">'
f'<label class="aide"><input type="checkbox" name="confirmer" value="oui" required> '
f"je confirme (sa dernière valeur part avec lui ; le journal reste)</label>"
f"<button>Retirer</button></form>")
titre = "Nouvel élément" if nouveau else str(e.get("titre") or nom)
return page(titre, _entete(titre, p) + champs + retrait)
def lire_formulaire(champs: dict) -> tuple[str, str, dict]:
"""(domaine, nom, élément) depuis le formulaire. Lève ValueError avec les fautes."""
fautes = []
titre = champs.get("titre", "").strip()
domaine = identifiant(champs.get("domaine", ""))
if not titre:
fautes.append("le titre manque")
if not domaine:
fautes.append("le domaine manque")
e: dict = {"titre": titre}
for cle in ("notes", "instructions"):
if champs.get(cle, "").strip():
e[cle] = champs[cle].strip().replace("\r\n", "\n")
liens = {}
for ligne in champs.get("liens", "").splitlines():
if ligne.strip():
libelle, _, adresse = ligne.strip().rpartition(" ")
if not adresse.startswith(("https://", "http://")):
fautes.append(f"lien sans adresse http(s) : « {ligne.strip()} »")
else:
liens[libelle.strip() or adresse] = adresse
if liens:
e["liens"] = liens
mesure = champs.get("mesure", "")
if mesure:
if mesure not in moteur.MESURES:
fautes.append("mesure inconnue")
else:
try:
e[mesure] = [_nombre(champs.get(f"s{i}", "")) for i in range(3)]
except ValueError:
fautes.append("seuils : trois nombres (à faire, pressé, en retard)")
if mesure == "reste" and champs.get("unite", "").strip():
e["unite"] = champs["unite"].strip()
if champs.get("si_erreur"):
e["si_erreur"] = champs["si_erreur"]
if not fautes:
fautes = moteur.verifier_element(e)
if fautes:
raise ValueError(*fautes)
return domaine, identifiant(titre), e
def _nombre(texte: str):
n = float(texte.strip().replace(",", "."))
return int(n) if n.is_integer() else n
# --- la réserve ---------------------------------------------------------------------------------
def reserve(d: Donnees, p: Personne) -> str:
deja = p.elements()
corps = []
for domaine, items in d.reserve().items():
rangs = "".join(
f'<tr><td><label class="choix"><input type="checkbox" name="cle" '
f'value="{escape(domaine)}/{escape(nom)}"{" disabled" if nom in deja.get(domaine, {}) else ""}> '
f'{escape(str(e.get("titre") or nom.replace("-", " ").capitalize()))}</label></td>'
f'<td class="doux">{escape(str(e.get("notes", "")))}'
f'{" — déjà suivi" if nom in deja.get(domaine, {}) else ""}</td></tr>'
for nom, e in items.items())
corps.append(f"<h2>{escape(domaine)}</h2><table>{rangs}</table>")
if not corps:
return page("Réserve", _entete("Réserve", p) + f'<p class="doux">La réserve est vide '
f"(<code>{escape(str(d.f_reserve))}</code>).</p>")
return page("Réserve", _entete(f"Réserve — pour {p.nom}", p)
+ f'<form method="post" action="{url("config", p.id, "reserve")}">'
+ '<p class="aide">Cocher ce qui sera suivi. Commencer petit : une dizaine suffit.</p>'
+ "".join(corps) + '<p><button class="principal">Ajouter la sélection</button></p></form>')
# --- les codes QR -----------------------------------------------------------------------------
def codes_qr(p: Personne, base: str) -> str:
try:
import segno
except ImportError:
return page("Codes QR", _entete("Codes QR", p) + '<div class="bloc"><p>Les codes QR demandent le paquet '
"Debian <code>python3-segno</code> : <code>sudo apt install python3-segno</code>.</p></div>")
etiquettes = []
for l in p.lignes():
cible = base + url("p", p.id, "e", l.domaine, l.nom)
svg = segno.make(cible, error="m").svg_inline(scale=4, border=4, dark="#000", light="#fff")
etiquettes.append(f'<div class="etiquette">{svg}<b>{escape(l.titre)}</b>'
f'<span class="doux">{escape(p.nom)}</span></div>')
aide = ('<p class="non-imprime aide">Imprimer cette page, découper, coller chaque étiquette là où '
"la chose se fait. Le code ouvre la page de l’élément sur le téléphone.</p>")
hote = base.split("://", 1)[-1].split(":")[0].strip("[]")
if hote in ("localhost", "127.0.0.1", "::1") or hote.startswith("127."):
aide += (f'<div class="bloc fautes non-imprime"><b>Ne pas imprimer depuis cette adresse.</b>'
f"<p>Ces codes pointent vers {escape(base)}, qu’un téléphone ne peut pas ouvrir. Ouvrir cette "
"page par l’adresse que le téléphone utilise, puis imprimer.</p></div>")
return page("Codes QR", _entete(f"Codes QR — {p.nom}", p) + aide
+ f'<div class="etiquettes">{"".join(etiquettes)}</div>')

268
lifenoc/web.py Normal file
View file

@ -0,0 +1,268 @@
"""Le serveur de Life-NOC : bibliothèque standard seulement, aucun framework.
La personne aidée (le téléphone)
GET /p/<id>/ ce qui est à faire maintenant
GET /p/<id>/tout tout, le pas-encore compris
GET /p/<id>/e/<domaine>/<élément> un élément (la cible d'un code QR)
POST /p/<id>/e/<domaine>/<élément> un geste : fait, echeance, valeur, compteur, entretien, reference
POST /p/<id>/annuler défaire le dernier geste d'un élément
La personne qui configure (et supervise, sans notification)
GET/POST /config/ les personnes ; en ajouter une
GET /config/<id>/ la supervision
GET /config/<id>/journal les gestes
GET/POST /config/<id>/nouveau ajouter un élément
GET/POST /config/<id>/e/<d>/<é> modifier ; POST …/retirer pour le retirer
GET/POST /config/<id>/reserve puiser dans la réserve
GET /config/<id>/qr les étiquettes à imprimer
Machines
GET /sante 200 si toutes les données se lisent, 500 sinon
GET /api/<id>/etats les états, en JSON
POST /api/<id>/element/<d>/<é> un geste en JSON : {"geste", "saisie", "par"}
Aucune authentification ici : l'application écoute en 127.0.0.1, et c'est ce qui la sert
(nginx, le frontal, un tunnel) qui décide qui la joint.
"""
from __future__ import annotations
import json
from html import escape
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, quote, unquote, urlsplit
from . import vue_aidee, vue_config
from .donnees import Donnees, identifiant
from .gabarit import page, url
def _choix(d: Donnees) -> str:
liens = "".join(f'<p><a class="bouton principal" href="{url("p", p.id)}/">{escape(p.nom)}</a></p>'
for p in d.personnes())
return page("Life-NOC", '<div class="salut"><h1>Life-NOC</h1><p>Voir clair, prioriser juste, agir au bon '
f'endroit</p></div>{liens}<p class="pied"><a href="/config/">Configuration</a></p>', "aidee")
class Gestionnaire(BaseHTTPRequestHandler):
donnees: Donnees = Donnees()
server_version = "life-noc"
def log_message(self, fmt, *args): # une ligne par requête, sans horodatage (journald l'a)
print(f"{self.address_string()} {fmt % args}", flush=True)
# --- réponses ------------------------------------------------------------------------------
def _envoyer(self, statut: int, corps: str, type_: str = "text/html; charset=utf-8",
entetes: dict | None = None) -> None:
donnees = corps.encode("utf-8")
self.send_response(statut)
self.send_header("Content-Type", type_)
self.send_header("Content-Length", str(len(donnees)))
self.send_header("Cache-Control", "no-store")
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Referrer-Policy", "no-referrer")
self.send_header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; "
"img-src data:; form-action 'self'; frame-ancestors 'none'")
for k, v in (entetes or {}).items():
self.send_header(k, v)
self.end_headers()
if self.command != "HEAD":
self.wfile.write(donnees)
def _rediriger(self, cible: str) -> None:
self._envoyer(303, "", entetes={"Location": cible})
def _json(self, statut: int, objet) -> None:
self._envoyer(statut, json.dumps(objet, ensure_ascii=False, indent=1), "application/json; charset=utf-8")
def _erreur(self, statut: int, message: str) -> None:
if self.path.startswith("/api/"):
return self._json(statut, {"erreur": message})
self._envoyer(statut, page("Erreur", f'<div class="bloc"><p>{escape(message)}</p>'
f'<p><a href="/">← Accueil</a></p></div>'))
def _morceaux(self) -> tuple[list[str], dict]:
parties = urlsplit(self.path)
return ([unquote(p) for p in parties.path.split("/") if p],
{k: v[0] for k, v in parse_qs(parties.query).items()})
def _base(self) -> str:
"""L'adresse publique, telle que la voit le navigateur (pour les codes QR)."""
schema = self.headers.get("X-Forwarded-Proto", "http").split(",")[0].strip() or "http"
return f"{schema}://{self.headers.get('Host', 'localhost')}"
# --- GET -----------------------------------------------------------------------------------
def do_HEAD(self):
self.do_GET()
def do_GET(self):
m, q = self._morceaux()
d = self.donnees
try:
if m == []:
return self._rediriger("/config/") if not d.personnes() else self._envoyer(200, _choix(d))
if m == ["sante"]:
n = 0
d.reserve()
for p in d.personnes():
n += len(p.lignes())
return self._envoyer(200, f"ok — {len(d.personnes())} personne(s), {n} élément(s)\n",
"text/plain; charset=utf-8")
if m[0] == "p" and len(m) >= 2:
p = d.personne(m[1])
if len(m) == 2:
return self._envoyer(200, vue_aidee.accueil(p, q.get("note")))
if m[2:] == ["tout"]:
return self._envoyer(200, vue_aidee.tout(p))
if len(m) == 5 and m[2] == "e":
return self._envoyer(200, vue_aidee.element(p, m[3], m[4]))
if m[0] == "config":
if len(m) == 1:
return self._envoyer(200, vue_config.personnes(d))
p = d.personne(m[1])
reste = m[2:]
if reste == []:
return self._envoyer(200, vue_config.supervision(p))
if reste == ["journal"]:
return self._envoyer(200, vue_config.journal(p))
if reste == ["nouveau"]:
return self._envoyer(200, vue_config.formulaire(p, domaine=q.get("domaine", "")))
if reste == ["reserve"]:
return self._envoyer(200, vue_config.reserve(d, p))
if reste == ["qr"]:
return self._envoyer(200, vue_config.codes_qr(p, self._base()))
if len(reste) == 3 and reste[0] == "e":
element = p.elements().get(reste[1], {}).get(reste[2])
if element is None:
raise KeyError(f"{reste[1]}/{reste[2]}")
return self._envoyer(200, vue_config.formulaire(p, reste[1], reste[2], element, nouveau=False))
if m[0] == "api" and len(m) == 3 and m[2] == "etats":
p = d.personne(m[1])
return self._json(200, [{"cle": l.cle, "titre": l.titre, "couleur": l.etat.couleur,
"message": l.etat.message, "a_noter": l.etat.a_noter,
"intrant": {k: v for k, v in (l.intrant or {}).items() if k != "precedent"}}
for l in p.lignes()])
self._erreur(404, "Page introuvable.")
except KeyError as exc:
self._erreur(404, f"Introuvable : {exc.args[0] if exc.args else ''}")
except (ValueError, OSError) as exc: # données illisibles : la sonde doit le voir
self._erreur(500, f"Données illisibles : {exc}")
# --- POST ----------------------------------------------------------------------------------
def do_POST(self):
# Un formulaire posté depuis un autre site ne doit rien changer.
if self.headers.get("Sec-Fetch-Site") == "cross-site":
return self._erreur(403, "Refusé : la demande vient d'un autre site.")
longueur = int(self.headers.get("Content-Length") or 0)
if longueur > 20_000:
return self._erreur(413, "Demande trop grosse.")
brut = self.rfile.read(longueur).decode("utf-8", "replace")
m, _ = self._morceaux()
d = self.donnees
try:
if m[:1] == ["api"]:
return self._post_api(d, m, brut)
champs = {k: v[0] for k, v in parse_qs(brut, keep_blank_values=True).items()}
if m[:1] == ["p"] and len(m) >= 3:
return self._post_aidee(d, m, champs)
if m[:1] == ["config"]:
return self._post_config(d, m, champs, parse_qs(brut).get("cle", []))
self._erreur(404, "Page introuvable.")
except KeyError as exc:
self._erreur(404, f"Introuvable : {exc.args[0] if exc.args else ''}")
except ValueError as exc:
self._erreur(400, f"Refusé : {'; '.join(map(str, exc.args))}")
def _post_aidee(self, d: Donnees, m: list[str], champs: dict) -> None:
p = d.personne(m[1])
if m[2:] == ["annuler"]:
domaine, _, nom = champs.get("cle", "").partition("/")
p.annuler(domaine, nom, par="téléphone")
return self._rediriger(url("p", p.id) + "/")
if len(m) == 5 and m[2] == "e":
p.noter(m[3], m[4], champs.get("geste", ""), champs.get("saisie", ""), par="téléphone")
return self._rediriger(url("p", p.id) + "/?note=" + quote(f"{m[3]}/{m[4]}"))
self._erreur(404, "Page introuvable.")
def _post_config(self, d: Donnees, m: list[str], champs: dict, cles: list[str]) -> None:
if len(m) == 1:
nom = champs.get("nom", "").strip()
ident = champs.get("ident", "").strip() or identifiant(nom)
try:
p = d.creer_personne(ident, nom)
except ValueError as exc:
return self._envoyer(400, vue_config.personnes(d, list(exc.args), champs))
return self._rediriger(url("config", p.id) + "/")
p = d.personne(m[1])
reste = m[2:]
if reste == ["nouveau"]:
try:
domaine, nom, element = vue_config.lire_formulaire(champs)
p.poser_element(domaine, nom, element)
except ValueError as exc:
return self._envoyer(400, vue_config.formulaire(
p, identifiant(champs.get("domaine", "")), "", _brouillon(champs), list(exc.args)))
return self._rediriger(url("config", p.id) + "/")
if len(reste) == 3 and reste[0] == "e":
if reste[2] not in p.elements().get(reste[1], {}):
raise KeyError(f"{reste[1]}/{reste[2]}")
try:
_, _, element = vue_config.lire_formulaire({**champs, "domaine": reste[1]})
p.poser_element(reste[1], reste[2], element, ancien=(reste[1], reste[2]))
except ValueError as exc:
return self._envoyer(400, vue_config.formulaire(
p, reste[1], reste[2], _brouillon(champs), list(exc.args), nouveau=False))
return self._rediriger(url("config", p.id) + "/")
if len(reste) == 4 and reste[0] == "e" and reste[3] == "retirer":
if champs.get("confirmer") != "oui":
raise ValueError("cocher la confirmation")
p.retirer_element(reste[1], reste[2])
return self._rediriger(url("config", p.id) + "/")
if reste == ["reserve"]:
reserve = d.reserve()
for cle in cles:
domaine, _, nom = cle.partition("/")
if nom in reserve.get(domaine, {}) and nom not in p.elements().get(domaine, {}):
p.poser_element(domaine, nom, reserve[domaine][nom])
return self._rediriger(url("config", p.id) + "/")
self._erreur(404, "Page introuvable.")
def _post_api(self, d: Donnees, m: list[str], brut: str) -> None:
if len(m) != 5 or m[2] != "element":
return self._erreur(404, "Page introuvable.")
p = d.personne(m[1])
corps = json.loads(brut or "{}")
if not isinstance(corps, dict):
raise ValueError("objet JSON attendu")
intrant = p.noter(m[3], m[4], str(corps.get("geste", "")), str(corps.get("saisie", "")),
par=str(corps.get("par", "api")))
self._json(200, {k: v for k, v in intrant.items() if k != "precedent"})
def _brouillon(champs: dict) -> dict:
"""Ce qui a été saisi, pour réafficher le formulaire sans rien perdre."""
e: dict = {k: champs[k] for k in ("titre", "notes", "instructions", "unite", "si_erreur") if champs.get(k)}
mesure = champs.get("mesure", "")
if mesure:
e[mesure] = [champs.get(f"s{i}", "") for i in range(3)]
liens = {}
for ligne in champs.get("liens", "").splitlines():
libelle, _, adresse = ligne.strip().rpartition(" ")
if adresse:
liens[libelle or adresse] = adresse
if liens:
e["liens"] = liens
return e
def servir(hote: str, port: int, donnees: Donnees | None = None) -> None:
Gestionnaire.donnees = donnees or Donnees()
serveur = ThreadingHTTPServer((hote, port), Gestionnaire)
print(f"Life-NOC sur http://{hote}:{port}/ — données : {Gestionnaire.donnees.racine}", flush=True)
try:
serveur.serve_forever()
except KeyboardInterrupt:
pass

View file

@ -1,142 +0,0 @@
#!/usr/bin/env python3
from pathlib import Path
import re
import sys
import yaml
INPUT_FILE = Path("domains.yaml")
OUTPUT_DIR = Path("bpm")
OUTPUT_FILE = OUTPUT_DIR / "Life-NOC.conf"
HOST_NAME = "life-noc"
TITLE = "Life-NOC"
OWNER = "icingadmin"
def slugify(value: str) -> str:
value = value.strip().lower()
replacements = {
"à": "a", "â": "a", "ä": "a",
"ç": "c",
"é": "e", "è": "e", "ê": "e", "ë": "e",
"î": "i", "ï": "i",
"ô": "o", "ö": "o",
"ù": "u", "û": "u", "ü": "u",
"ÿ": "y",
"œ": "oe",
"æ": "ae",
"'": "",
"’": "",
}
for old, new in replacements.items():
value = value.replace(old, new)
value = re.sub(r"[^a-z0-9\-]+", "-", value)
value = re.sub(r"-{2,}", "-", value)
return value.strip("-")
def aliasify(value: str) -> str:
value = value.strip().upper()
replacements = {
"À": "A", "Â": "A", "Ä": "A",
"Ç": "C",
"É": "E", "È": "E", "Ê": "E", "Ë": "E",
"Î": "I", "Ï": "I",
"Ô": "O", "Ö": "O",
"Ù": "U", "Û": "U", "Ü": "U",
"Ÿ": "Y",
"Œ": "OE",
"Æ": "AE",
"'": "",
"’": "",
}
for old, new in replacements.items():
value = value.replace(old, new)
value = re.sub(r"[^A-Z0-9\-]+", "-", value)
value = re.sub(r"-{2,}", "-", value)
return value.strip("-")
def header() -> str:
return f"""### Business Process Config File ###
#
# Title : {TITLE}
# Description :
# Owner : {OWNER}
# AddToMenu : yes
# Backend :
# Statetype : soft
#
###################################
"""
def main() -> int:
if not INPUT_FILE.exists():
print(f"Erreur: fichier introuvable: {INPUT_FILE}", file=sys.stderr)
return 1
with INPUT_FILE.open("r", encoding="utf-8") as f:
data = yaml.safe_load(f)
if not isinstance(data, dict) or "domains" not in data:
print("Erreur: le YAML doit contenir une clé racine 'domains'.", file=sys.stderr)
return 1
domains = data["domains"]
if not isinstance(domains, dict):
print("Erreur: 'domains' doit être un objet YAML.", file=sys.stderr)
return 1
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
lines = [header()]
aliases = []
for raw_domain, items in domains.items():
if not isinstance(items, list):
print(f"Erreur: le domaine '{raw_domain}' doit contenir une liste.", file=sys.stderr)
return 1
domain_slug = slugify(str(raw_domain))
domain_alias = aliasify(str(raw_domain))
services = []
for idx, item in enumerate(items, start=1):
if not isinstance(item, dict):
print(f"Erreur: entrée invalide dans '{raw_domain}' à la position {idx}.", file=sys.stderr)
return 1
if "name" not in item:
print(f"Erreur: dans le domaine '{raw_domain}', entrée {idx}, champ manquant: name", file=sys.stderr)
return 1
item_name = slugify(str(item["name"]))
services.append(f"{HOST_NAME};{domain_slug}-{item_name}")
if not services:
print(f"Erreur: le domaine '{raw_domain}' ne contient aucun item.", file=sys.stderr)
return 1
expr = " & ".join(services)
lines.append(f"{domain_alias} = {expr}\n")
aliases.append((domain_alias, str(raw_domain).upper()))
lines.append("\n")
for alias, label in aliases:
lines.append(f"display 1;{alias};{label}\n")
OUTPUT_FILE.write_text("".join(lines), encoding="utf-8")
print(f"BPM généré: {OUTPUT_FILE}")
print("Processus générés :")
print(" - LIFE-NOC")
for alias, _label in aliases:
print(f" - {alias}")
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -1,357 +0,0 @@
#!/usr/bin/env python3
from pathlib import Path
import re
import os
import sys
import yaml
INPUT_FILE = Path("domains.yaml")
OUTPUT_DIR = Path("icinga/services")
SERVICEGROUPS_DIR = Path("icinga/servicegroups")
SERVICEGROUPS_FILE = SERVICEGROUPS_DIR / "life-noc.conf"
HOST_NAME = "life-noc"
SERVICE_TEMPLATE = "service_echeance"
PROBE_TEMPLATE = "service_life_noc_probe"
DEFAULT_MOCK_STATE = "OK"
DEFAULT_MOCK_MESSAGE = "Sous contrôle"
LIFE_NOC_PUBLIC_BASE_URL = os.environ.get("LIFE_NOC_PUBLIC_BASE_URL", "").rstrip("/")
def absolutize_url(url: str) -> str:
url = (url or "").strip()
if not url:
return url
if url.startswith("http://") or url.startswith("https://"):
return url
if LIFE_NOC_PUBLIC_BASE_URL:
if not url.startswith("/"):
url = "/" + url
return LIFE_NOC_PUBLIC_BASE_URL + url
return url
def slugify(value: str) -> str:
value = value.strip().lower()
replacements = {
"à": "a", "â": "a", "ä": "a",
"ç": "c",
"é": "e", "è": "e", "ê": "e", "ë": "e",
"î": "i", "ï": "i",
"ô": "o", "ö": "o",
"ù": "u", "û": "u", "ü": "u",
"ÿ": "y",
"œ": "oe",
"æ": "ae",
"'": "",
"’": "",
}
for old, new in replacements.items():
value = value.replace(old, new)
value = re.sub(r"[^a-z0-9\-]+", "-", value)
value = re.sub(r"-{2,}", "-", value)
return value.strip("-")
def aliasify(value: str) -> str:
value = value.strip().upper()
replacements = {
"À": "A", "Â": "A", "Ä": "A",
"Ç": "C",
"É": "E", "È": "E", "Ê": "E", "Ë": "E",
"Î": "I", "Ï": "I",
"Ô": "O", "Ö": "O",
"Ù": "U", "Û": "U", "Ü": "U",
"Ÿ": "Y",
"Œ": "OE",
"Æ": "AE",
"'": "",
"’": "",
}
for old, new in replacements.items():
value = value.replace(old, new)
value = re.sub(r"[^A-Z0-9\-]+", "-", value)
value = re.sub(r"-{2,}", "-", value)
return value.strip("-")
def icinga_escape(value: str) -> str:
return value.replace("\\", "\\\\").replace('"', '\\"')
def normalize_mock_state(value: str) -> str:
state = str(value).strip().upper()
allowed = {"OK", "WARNING", "CRITICAL"}
if state not in allowed:
raise ValueError(
f"mock_state invalide: {value}. Valeurs permises: {', '.join(sorted(allowed))}"
)
return state
def render_mock_service(domain: str, group_name: str, item: dict) -> str:
name = item["name"].strip()
date = str(item["date"]).strip()
notes = item.get("notes", "").strip()
notes_url = item.get("notes_url", "").strip()
instructions_url = item.get("instructions_url", "").strip()
if not instructions_url:
instructions_url = f"/life-noc/item/{domain}/{name}"
instructions_url = absolutize_url(instructions_url)
action_url = item.get("action_url", "").strip()
mock_state = normalize_mock_state(item.get("mock_state", DEFAULT_MOCK_STATE))
mock_message = item.get("mock_message", DEFAULT_MOCK_MESSAGE).strip() or DEFAULT_MOCK_MESSAGE
service_name = f"{domain}-{name}"
lines = [
f'apply Service "{icinga_escape(service_name)}" {{',
f' import "{SERVICE_TEMPLATE}"',
f' vars.date_echeance = "{icinga_escape(date)}"',
f' vars.mock_state = "{icinga_escape(mock_state)}"',
f' vars.mock_message = "{icinga_escape(mock_message)}"',
f' groups = [ "{icinga_escape(group_name)}" ]',
]
if notes:
lines.append(f' notes = "{icinga_escape(notes)}"')
if notes_url:
lines.append(f' notes_url = "{icinga_escape(notes_url)}"')
if instructions_url:
lines.append(f' vars.instructions_url = "{icinga_escape(instructions_url)}"')
if action_url:
lines.append(f' action_url = "{icinga_escape(action_url)}"')
lines.append(f' assign where host.name == "{HOST_NAME}"')
lines.append("}")
lines.append("")
return "\n".join(lines)
def render_probe_service(domain: str, group_name: str, item: dict) -> str:
name = item["name"].strip()
notes = item.get("notes", "").strip()
notes_url = item.get("notes_url", "").strip()
instructions_url = item.get("instructions_url", "").strip()
if not instructions_url:
instructions_url = f"/life-noc/item/{domain}/{name}"
action_url = item.get("action_url", "").strip()
instructions_url = absolutize_url(instructions_url)
probe = item["probe"]
probe_type = str(probe["type"]).strip()
source = probe["source"]
metric = probe["metric"]
thresholds = probe["thresholds"]
policy = probe.get("policy", {})
service_name = f"{domain}-{name}"
lines = [
f'apply Service "{icinga_escape(service_name)}" {{',
f' import "{PROBE_TEMPLATE}"',
f' vars.life_noc_probe_type = "{icinga_escape(probe_type)}"',
f' vars.life_noc_source_type = "{icinga_escape(str(source["type"]).strip())}"',
f' vars.life_noc_source_value = "{icinga_escape(str(source.get("value", "")).strip())}"',
f' vars.life_noc_inputs_file = "{icinga_escape(str(source.get("inputs_file", "")).strip())}"',
f' vars.life_noc_item_key = "{icinga_escape(str(source.get("item_key", name)).strip())}"',
f' vars.life_noc_metric_unit = "{icinga_escape(str(metric["unit"]).strip())}"',
f' vars.life_noc_label = "{icinga_escape(name)}"',
f' groups = [ "{icinga_escape(group_name)}" ]',
]
if "unknown_lt" in thresholds:
lines.append(f' vars.life_noc_threshold_unknown_lt = "{icinga_escape(str(thresholds["unknown_lt"]))}"')
if "ok_gte" in thresholds:
lines.append(f' vars.life_noc_threshold_ok_gte = "{icinga_escape(str(thresholds["ok_gte"]))}"')
if "warning_gte" in thresholds:
lines.append(f' vars.life_noc_threshold_warning_gte = "{icinga_escape(str(thresholds["warning_gte"]))}"')
if "critical_gte" in thresholds:
lines.append(f' vars.life_noc_threshold_critical_gte = "{icinga_escape(str(thresholds["critical_gte"]))}"')
if "unknown_gte" in thresholds:
lines.append(f' vars.life_noc_threshold_unknown_gte = "{icinga_escape(str(thresholds["unknown_gte"]))}"')
if "ok_lt" in thresholds:
lines.append(f' vars.life_noc_threshold_ok_lt = "{icinga_escape(str(thresholds["ok_lt"]))}"')
if "warning_lt" in thresholds:
lines.append(f' vars.life_noc_threshold_warning_lt = "{icinga_escape(str(thresholds["warning_lt"]))}"')
if "critical_lt" in thresholds:
lines.append(f' vars.life_noc_threshold_critical_lt = "{icinga_escape(str(thresholds["critical_lt"]))}"')
on_error = str(policy.get("on_error", "critical")).strip()
lines.append(f' vars.life_noc_on_error = "{icinga_escape(on_error)}"')
if notes:
lines.append(f' notes = "{icinga_escape(notes)}"')
if notes_url:
lines.append(f' notes_url = "{icinga_escape(notes_url)}"')
if instructions_url:
lines.append(f' vars.instructions_url = "{icinga_escape(instructions_url)}"')
if action_url:
lines.append(f' action_url = "{icinga_escape(action_url)}"')
lines.append(f' assign where host.name == "{HOST_NAME}"')
lines.append("}")
lines.append("")
return "\n".join(lines)
def validate_probe(item: dict) -> None:
probe = item["probe"]
if not isinstance(probe, dict):
raise ValueError("probe doit être un objet")
probe_type = str(probe.get("type", "")).strip()
if probe_type not in {"elapsed_time", "days_until_due", "elapsed_distance", "remaining_quantity", "current_value"}:
raise ValueError("seuls probe.type=elapsed_time, days_until_due, elapsed_distance, remaining_quantity et current_value sont supportés")
source = probe.get("source")
if not isinstance(source, dict):
raise ValueError("probe.source doit être un objet")
source_type = str(source.get("type", "")).strip()
has_inline_value = "value" in source
has_store_ref = "inputs_file" in source and "item_key" in source
if probe_type in {"elapsed_time", "days_until_due"}:
if source_type != "manual_date":
raise ValueError("seul probe.source.type=manual_date est supporté pour les sondes de date")
if not has_inline_value and not has_store_ref:
raise ValueError("probe.source.value ou probe.source.inputs_file + item_key requis")
elif probe_type == "elapsed_distance":
if source_type != "manual_counter":
raise ValueError("seul probe.source.type=manual_counter est supporté pour elapsed_distance")
if not has_store_ref:
raise ValueError("probe.source.inputs_file + item_key requis pour elapsed_distance")
elif probe_type == "remaining_quantity":
if source_type != "manual_value":
raise ValueError("seul probe.source.type=manual_value est supporté pour remaining_quantity")
if not has_store_ref:
raise ValueError("probe.source.inputs_file + item_key requis pour remaining_quantity")
elif probe_type == "current_value":
if source_type != "manual_value":
raise ValueError("seul probe.source.type=manual_value est supporté pour current_value")
if not has_store_ref:
raise ValueError("probe.source.inputs_file + item_key requis pour current_value")
metric = probe.get("metric")
if not isinstance(metric, dict):
raise ValueError("probe.metric doit être un objet")
metric_unit = str(metric.get("unit", "")).strip()
if probe_type in {"elapsed_time", "days_until_due"} and metric_unit != "days":
raise ValueError("seul probe.metric.unit=days est supporté pour les sondes de date")
if probe_type == "elapsed_distance" and metric_unit != "km":
raise ValueError("seul probe.metric.unit=km est supporté pour elapsed_distance")
if probe_type == "remaining_quantity" and metric_unit not in {"%", "units", "litres"}:
raise ValueError("probe.metric.unit doit être %, units ou litres pour remaining_quantity")
if probe_type == "current_value" and metric_unit not in {"%", "units", "litres", "volts", "watts"}:
raise ValueError("probe.metric.unit doit être %, units, litres, volts ou watts pour current_value")
thresholds = probe.get("thresholds")
if not isinstance(thresholds, dict):
raise ValueError("probe.thresholds doit être un objet")
def render_servicegroup(group_name: str) -> str:
return "\n".join([
f'object ServiceGroup "{icinga_escape(group_name)}" {{',
f' display_name = "{icinga_escape(group_name)}"',
"}",
"",
])
def main() -> int:
if not INPUT_FILE.exists():
print(f"Erreur: fichier introuvable: {INPUT_FILE}", file=sys.stderr)
return 1
with INPUT_FILE.open("r", encoding="utf-8") as f:
data = yaml.safe_load(f)
if not isinstance(data, dict) or "domains" not in data:
print("Erreur: le YAML doit contenir une clé racine 'domains'.", file=sys.stderr)
return 1
domains = data["domains"]
if not isinstance(domains, dict):
print("Erreur: 'domains' doit être un objet YAML.", file=sys.stderr)
return 1
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
SERVICEGROUPS_DIR.mkdir(parents=True, exist_ok=True)
for existing_conf in OUTPUT_DIR.glob("*.conf"):
existing_conf.unlink()
if SERVICEGROUPS_FILE.exists():
SERVICEGROUPS_FILE.unlink()
generated_files = []
servicegroup_content = [
"/*",
" AUTO-GENERATED FILE - SERVICE GROUPS",
" Ne pas modifier manuellement.",
" Source: domains.yaml",
"*/",
"",
]
for raw_domain, services in domains.items():
domain = slugify(str(raw_domain))
group_name = aliasify(str(raw_domain))
if not isinstance(services, list):
print(f"Erreur: le domaine '{raw_domain}' doit contenir une liste.", file=sys.stderr)
return 1
output_file = OUTPUT_DIR / f"{domain}.conf"
content = [
"/*",
f" AUTO-GENERATED FILE - DOMAIN: {raw_domain}",
" Ne pas modifier manuellement.",
" Source: domains.yaml",
"*/",
"",
]
servicegroup_content.append(render_servicegroup(group_name))
for idx, item in enumerate(services, start=1):
if not isinstance(item, dict):
print(f"Erreur: entrée invalide dans '{raw_domain}' à la position {idx}.", file=sys.stderr)
return 1
missing = [key for key in ("name", "date", "notes") if key not in item]
if missing:
print(
f"Erreur: dans le domaine '{raw_domain}', entrée {idx}, champs manquants: {', '.join(missing)}",
file=sys.stderr,
)
return 1
try:
if "probe" in item:
validate_probe(item)
content.append(render_probe_service(domain, group_name, item))
else:
content.append(render_mock_service(domain, group_name, item))
except ValueError as exc:
print(f"Erreur dans '{raw_domain}', entrée {idx}: {exc}", file=sys.stderr)
return 1
output_file.write_text("\n".join(content).rstrip() + "\n", encoding="utf-8")
generated_files.append(str(output_file))
SERVICEGROUPS_FILE.write_text("\n".join(servicegroup_content).rstrip() + "\n", encoding="utf-8")
generated_files.append(str(SERVICEGROUPS_FILE))
print("Fichiers générés :")
for file_path in generated_files:
print(f" - {file_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -1,307 +0,0 @@
#!/usr/bin/env python3
from pathlib import Path
import re
import sys
import yaml
INPUT_FILE = Path("domains.yaml")
OUTPUT_DIR = Path("icinga/services")
SERVICEGROUPS_DIR = Path("icinga/servicegroups")
SERVICEGROUPS_FILE = SERVICEGROUPS_DIR / "life-noc.conf"
HOST_NAME = "life-noc"
SERVICE_TEMPLATE = "service_echeance"
PROBE_TEMPLATE = "service_life_noc_probe"
DEFAULT_MOCK_STATE = "OK"
DEFAULT_MOCK_MESSAGE = "Sous contrôle"
def slugify(value: str) -> str:
value = value.strip().lower()
replacements = {
"à": "a", "â": "a", "ä": "a",
"ç": "c",
"é": "e", "è": "e", "ê": "e", "ë": "e",
"î": "i", "ï": "i",
"ô": "o", "ö": "o",
"ù": "u", "û": "u", "ü": "u",
"ÿ": "y",
"œ": "oe",
"æ": "ae",
"'": "",
"’": "",
}
for old, new in replacements.items():
value = value.replace(old, new)
value = re.sub(r"[^a-z0-9\-]+", "-", value)
value = re.sub(r"-{2,}", "-", value)
return value.strip("-")
def aliasify(value: str) -> str:
value = value.strip().upper()
replacements = {
"À": "A", "Â": "A", "Ä": "A",
"Ç": "C",
"É": "E", "È": "E", "Ê": "E", "Ë": "E",
"Î": "I", "Ï": "I",
"Ô": "O", "Ö": "O",
"Ù": "U", "Û": "U", "Ü": "U",
"Ÿ": "Y",
"Œ": "OE",
"Æ": "AE",
"'": "",
"’": "",
}
for old, new in replacements.items():
value = value.replace(old, new)
value = re.sub(r"[^A-Z0-9\-]+", "-", value)
value = re.sub(r"-{2,}", "-", value)
return value.strip("-")
def icinga_escape(value: str) -> str:
return value.replace("\\", "\\\\").replace('"', '\\"')
def normalize_mock_state(value: str) -> str:
state = str(value).strip().upper()
allowed = {"OK", "WARNING", "CRITICAL"}
if state not in allowed:
raise ValueError(
f"mock_state invalide: {value}. Valeurs permises: {', '.join(sorted(allowed))}"
)
return state
def render_mock_service(domain: str, group_name: str, item: dict) -> str:
name = item["name"].strip()
date = str(item["date"]).strip()
notes = item.get("notes", "").strip()
notes_url = item.get("notes_url", "").strip()
action_url = item.get("action_url", "").strip()
mock_state = normalize_mock_state(item.get("mock_state", DEFAULT_MOCK_STATE))
mock_message = item.get("mock_message", DEFAULT_MOCK_MESSAGE).strip() or DEFAULT_MOCK_MESSAGE
service_name = f"{domain}-{name}"
lines = [
f'apply Service "{icinga_escape(service_name)}" {{',
f' import "{SERVICE_TEMPLATE}"',
f' vars.date_echeance = "{icinga_escape(date)}"',
f' vars.mock_state = "{icinga_escape(mock_state)}"',
f' vars.mock_message = "{icinga_escape(mock_message)}"',
f' groups = [ "{icinga_escape(group_name)}" ]',
]
if notes:
lines.append(f' notes = "{icinga_escape(notes)}"')
if notes_url:
lines.append(f' notes_url = "{icinga_escape(notes_url)}"')
if action_url:
lines.append(f' action_url = "{icinga_escape(action_url)}"')
lines.append(f' assign where host.name == "{HOST_NAME}"')
lines.append("}")
lines.append("")
return "\n".join(lines)
def render_probe_service(domain: str, group_name: str, item: dict) -> str:
name = item["name"].strip()
notes = item.get("notes", "").strip()
notes_url = item.get("notes_url", "").strip()
action_url = item.get("action_url", "").strip()
probe = item["probe"]
probe_type = str(probe["type"]).strip()
source = probe["source"]
metric = probe["metric"]
thresholds = probe["thresholds"]
policy = probe.get("policy", {})
service_name = f"{domain}-{name}"
lines = [
f'apply Service "{icinga_escape(service_name)}" {{',
f' import "{PROBE_TEMPLATE}"',
f' vars.life_noc_probe_type = "{icinga_escape(probe_type)}"',
f' vars.life_noc_source_type = "{icinga_escape(str(source["type"]).strip())}"',
f' vars.life_noc_source_value = "{icinga_escape(str(source.get("value", "")).strip())}"',
f' vars.life_noc_inputs_file = "{icinga_escape(str(source.get("inputs_file", "")).strip())}"',
f' vars.life_noc_item_key = "{icinga_escape(str(source.get("item_key", name)).strip())}"',
f' vars.life_noc_metric_unit = "{icinga_escape(str(metric["unit"]).strip())}"',
f' vars.life_noc_label = "{icinga_escape(name)}"',
f' groups = [ "{icinga_escape(group_name)}" ]',
]
if "unknown_lt" in thresholds:
lines.append(f' vars.life_noc_threshold_unknown_lt = "{icinga_escape(str(thresholds["unknown_lt"]))}"')
if "ok_gte" in thresholds:
lines.append(f' vars.life_noc_threshold_ok_gte = "{icinga_escape(str(thresholds["ok_gte"]))}"')
if "warning_gte" in thresholds:
lines.append(f' vars.life_noc_threshold_warning_gte = "{icinga_escape(str(thresholds["warning_gte"]))}"')
if "critical_gte" in thresholds:
lines.append(f' vars.life_noc_threshold_critical_gte = "{icinga_escape(str(thresholds["critical_gte"]))}"')
if "unknown_gte" in thresholds:
lines.append(f' vars.life_noc_threshold_unknown_gte = "{icinga_escape(str(thresholds["unknown_gte"]))}"')
if "ok_lt" in thresholds:
lines.append(f' vars.life_noc_threshold_ok_lt = "{icinga_escape(str(thresholds["ok_lt"]))}"')
if "warning_lt" in thresholds:
lines.append(f' vars.life_noc_threshold_warning_lt = "{icinga_escape(str(thresholds["warning_lt"]))}"')
if "critical_lt" in thresholds:
lines.append(f' vars.life_noc_threshold_critical_lt = "{icinga_escape(str(thresholds["critical_lt"]))}"')
on_error = str(policy.get("on_error", "critical")).strip()
lines.append(f' vars.life_noc_on_error = "{icinga_escape(on_error)}"')
if notes:
lines.append(f' notes = "{icinga_escape(notes)}"')
if notes_url:
lines.append(f' notes_url = "{icinga_escape(notes_url)}"')
if action_url:
lines.append(f' action_url = "{icinga_escape(action_url)}"')
lines.append(f' assign where host.name == "{HOST_NAME}"')
lines.append("}")
lines.append("")
return "\n".join(lines)
def validate_probe(item: dict) -> None:
probe = item["probe"]
if not isinstance(probe, dict):
raise ValueError("probe doit être un objet")
probe_type = str(probe.get("type", "")).strip()
if probe_type not in {"elapsed_time", "days_until_due"}:
raise ValueError("seuls probe.type=elapsed_time et days_until_due sont supportés")
source = probe.get("source")
if not isinstance(source, dict):
raise ValueError("probe.source doit être un objet")
if str(source.get("type", "")).strip() != "manual_date":
raise ValueError("seul probe.source.type=manual_date est supporté en v1")
has_inline_value = "value" in source
has_store_ref = "inputs_file" in source and "item_key" in source
if not has_inline_value and not has_store_ref:
raise ValueError("probe.source.value ou probe.source.inputs_file + item_key requis")
metric = probe.get("metric")
if not isinstance(metric, dict):
raise ValueError("probe.metric doit être un objet")
if str(metric.get("unit", "")).strip() != "days":
raise ValueError("seul probe.metric.unit=days est supporté en v1")
thresholds = probe.get("thresholds")
if not isinstance(thresholds, dict):
raise ValueError("probe.thresholds doit être un objet")
def render_servicegroup(group_name: str) -> str:
return "\n".join([
f'object ServiceGroup "{icinga_escape(group_name)}" {{',
f' display_name = "{icinga_escape(group_name)}"',
"}",
"",
])
def main() -> int:
if not INPUT_FILE.exists():
print(f"Erreur: fichier introuvable: {INPUT_FILE}", file=sys.stderr)
return 1
with INPUT_FILE.open("r", encoding="utf-8") as f:
data = yaml.safe_load(f)
if not isinstance(data, dict) or "domains" not in data:
print("Erreur: le YAML doit contenir une clé racine 'domains'.", file=sys.stderr)
return 1
domains = data["domains"]
if not isinstance(domains, dict):
print("Erreur: 'domains' doit être un objet YAML.", file=sys.stderr)
return 1
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
SERVICEGROUPS_DIR.mkdir(parents=True, exist_ok=True)
for existing_conf in OUTPUT_DIR.glob("*.conf"):
existing_conf.unlink()
if SERVICEGROUPS_FILE.exists():
SERVICEGROUPS_FILE.unlink()
generated_files = []
servicegroup_content = [
"/*",
" AUTO-GENERATED FILE - SERVICE GROUPS",
" Ne pas modifier manuellement.",
" Source: domains.yaml",
"*/",
"",
]
for raw_domain, services in domains.items():
domain = slugify(str(raw_domain))
group_name = aliasify(str(raw_domain))
if not isinstance(services, list):
print(f"Erreur: le domaine '{raw_domain}' doit contenir une liste.", file=sys.stderr)
return 1
output_file = OUTPUT_DIR / f"{domain}.conf"
content = [
"/*",
f" AUTO-GENERATED FILE - DOMAIN: {raw_domain}",
" Ne pas modifier manuellement.",
" Source: domains.yaml",
"*/",
"",
]
servicegroup_content.append(render_servicegroup(group_name))
for idx, item in enumerate(services, start=1):
if not isinstance(item, dict):
print(f"Erreur: entrée invalide dans '{raw_domain}' à la position {idx}.", file=sys.stderr)
return 1
missing = [key for key in ("name", "date", "notes") if key not in item]
if missing:
print(
f"Erreur: dans le domaine '{raw_domain}', entrée {idx}, champs manquants: {', '.join(missing)}",
file=sys.stderr,
)
return 1
try:
if "probe" in item:
validate_probe(item)
content.append(render_probe_service(domain, group_name, item))
else:
content.append(render_mock_service(domain, group_name, item))
except ValueError as exc:
print(f"Erreur dans '{raw_domain}', entrée {idx}: {exc}", file=sys.stderr)
return 1
output_file.write_text("\n".join(content).rstrip() + "\n", encoding="utf-8")
generated_files.append(str(output_file))
SERVICEGROUPS_FILE.write_text("\n".join(servicegroup_content).rstrip() + "\n", encoding="utf-8")
generated_files.append(str(SERVICEGROUPS_FILE))
print("Fichiers générés :")
for file_path in generated_files:
print(f" - {file_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -1,91 +0,0 @@
#!/usr/bin/env python3
from __future__ import annotations
from pathlib import Path
import sys
import argparse
import yaml
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from lib.life_noc_inputs import list_items, get_item, set_item, complete_item
def cmd_set(args: argparse.Namespace) -> int:
set_item(args.domain, args.item_key, args.value, origin=args.origin)
print(f"Mis à jour: {args.domain} -> {args.item_key}")
return 0
def cmd_complete(args: argparse.Namespace) -> int:
complete_item(args.domain, args.item_key, origin=args.origin)
print(f"Complété: {args.domain} -> {args.item_key}")
return 0
def cmd_get(args: argparse.Namespace) -> int:
try:
item = get_item(args.domain, args.item_key)
except KeyError:
print(f"Item introuvable: {args.item_key}", file=sys.stderr)
return 1
print(
yaml.safe_dump(
{args.item_key: item},
sort_keys=False,
allow_unicode=True,
).strip()
)
return 0
def cmd_list(args: argparse.Namespace) -> int:
for key in list_items(args.domain):
print(key)
return 0
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Gestion des intrants Life-NOC")
sub = parser.add_subparsers(dest="command", required=True)
p_set = sub.add_parser("set", help="Met à jour un intrant")
p_set.add_argument("domain")
p_set.add_argument("item_key")
p_set.add_argument("value")
p_set.add_argument("--origin", default="manual")
p_set.set_defaults(func=cmd_set)
p_complete = sub.add_parser("complete", help="Marque un item comme complété maintenant")
p_complete.add_argument("domain")
p_complete.add_argument("item_key")
p_complete.add_argument("--origin", default="manual")
p_complete.set_defaults(func=cmd_complete)
p_get = sub.add_parser("get", help="Lit un intrant")
p_get.add_argument("domain")
p_get.add_argument("item_key")
p_get.set_defaults(func=cmd_get)
p_list = sub.add_parser("list", help="Liste les intrants d’un domaine")
p_list.add_argument("domain")
p_list.set_defaults(func=cmd_list)
return parser
def main() -> int:
parser = build_parser()
args = parser.parse_args()
try:
return args.func(args)
except ValueError as exc:
print(f"Erreur: {exc}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -1,989 +0,0 @@
#!/usr/bin/env python3
from __future__ import annotations
from pathlib import Path
from urllib.parse import quote
import os
import sys
from fastapi import FastAPI, HTTPException, Form
from fastapi.responses import HTMLResponse, RedirectResponse
from pydantic import BaseModel
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from lib.life_noc_domains import ( # noqa: E402
ALLOWED_FORM_MODES,
ALLOWED_METRIC_UNITS,
ALLOWED_ON_ERROR,
ALLOWED_PROBE_TYPES,
ALLOWED_SOURCE_TYPES,
THRESHOLD_FIELDS,
DomainsConflictError,
DomainsError,
delete_item,
get_domain_item,
item_to_form_values,
list_domain_items,
list_domains,
normalize_item_payload,
reorder_item,
upsert_item,
)
from lib.life_noc_inputs import ( # noqa: E402
list_items,
get_item,
set_item,
set_counter_pair,
complete_item,
get_defined_service,
compute_state_for_item,
)
class SetInputRequest(BaseModel):
value: str
origin: str = "manual"
class CompleteInputRequest(BaseModel):
origin: str = "manual"
class CounterPairInputRequest(BaseModel):
current_value: str
reference_value: str
origin: str = "manual"
app = FastAPI(title="Life-NOC Input API", version="1.1.0")
ADMIN_UI_ENABLED = os.environ.get("LIFE_NOC_ADMIN_UI_ENABLED", "0").strip().lower() in {
"1",
"true",
"yes",
"on",
}
BASE_CSS = """
:root {
color-scheme: light;
--bg: #f5f7fb;
--card: #ffffff;
--border: #d9e0ea;
--text: #112033;
--muted: #5a697b;
--accent: #164c96;
--accent-soft: #eaf2ff;
--danger: #8b1e1e;
--ok: #0f6b3d;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: Arial, sans-serif;
line-height: 1.45;
}
main {
max-width: 920px;
margin: 0 auto;
padding: 1rem;
}
.stack { display: grid; gap: 1rem; }
.card {
background: var(--card);
border: 1px solid var(--border);
border-radius: 16px;
padding: 1rem;
box-shadow: 0 1px 2px rgba(0,0,0,0.03);
}
.hero { padding: 1rem; }
.muted { color: var(--muted); }
.state { font-size: 1.15rem; font-weight: bold; }
h1, h2, h3 { margin-top: 0; }
ul { padding-left: 1.2rem; }
code {
background: #eef2f7;
padding: 0.15rem 0.35rem;
border-radius: 6px;
}
a { color: var(--accent); text-decoration: none; }
a:hover { text-decoration: underline; }
.toolbar, .actions {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
align-items: center;
}
.actions form, .inline-form { display: inline-flex; margin: 0; }
.pill {
display: inline-block;
padding: 0.25rem 0.55rem;
border-radius: 999px;
background: var(--accent-soft);
color: var(--accent);
font-size: 0.9rem;
}
.button, button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
min-height: 44px;
padding: 0.75rem 1rem;
border-radius: 12px;
border: 1px solid #335b94;
background: #ffffff;
color: #163454;
font-size: 1rem;
cursor: pointer;
text-decoration: none;
}
.button.primary, button.primary {
background: var(--accent);
color: #fff;
border-color: var(--accent);
}
.button.danger, button.danger {
border-color: #b64b4b;
color: var(--danger);
}
.grid-cards {
display: grid;
gap: 0.9rem;
}
.row-between {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
}
.item-title {
font-size: 1.05rem;
font-weight: bold;
margin: 0 0 0.35rem 0;
}
.form-grid {
display: grid;
gap: 0.85rem;
}
.form-grid.two { grid-template-columns: 1fr; }
label {
display: grid;
gap: 0.35rem;
font-size: 0.95rem;
font-weight: bold;
}
input[type="text"], input[type="date"], textarea, select {
width: 100%;
min-height: 44px;
padding: 0.75rem 0.8rem;
border-radius: 12px;
border: 1px solid #aebacc;
font: inherit;
background: #fff;
color: var(--text);
}
textarea { min-height: 100px; resize: vertical; }
.checks {
display: grid;
gap: 0.55rem;
}
.check {
display: flex;
align-items: center;
gap: 0.6rem;
font-weight: normal;
}
.check input { width: 20px; height: 20px; }
.section-title {
margin-bottom: 0.5rem;
font-size: 1.02rem;
}
details {
border: 1px solid var(--border);
border-radius: 14px;
background: #fcfdff;
padding: 0.15rem 0.85rem 0.85rem 0.85rem;
}
details + details { margin-top: 0.8rem; }
summary {
cursor: pointer;
font-weight: bold;
list-style: none;
padding: 0.9rem 0 0.6rem 0;
}
summary::-webkit-details-marker { display: none; }
.alert {
border: 1px solid #f2c5c5;
background: #fff4f4;
color: #7a1a1a;
border-radius: 12px;
padding: 0.85rem 1rem;
}
pre.yaml-preview {
white-space: pre-wrap;
word-break: break-word;
background: #0f1720;
color: #e8eef6;
padding: 1rem;
border-radius: 14px;
overflow-x: auto;
}
.mobile-sticky {
position: sticky;
bottom: 0;
background: rgba(245,247,251,0.96);
padding-top: 0.7rem;
}
@media (min-width: 760px) {
.form-grid.two { grid-template-columns: 1fr 1fr; }
.grid-cards { grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); }
}
"""
def html_escape(value: object) -> str:
return (
str(value)
.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace('"', "&quot;")
)
def link_row(label: str, url: str) -> str:
if not url:
return ""
u = html_escape(url)
l = html_escape(label)
return f'<li><a href="{u}" target="_blank" rel="noopener">{l}</a></li>'
def resolve_instructions_url(domain: str, item_key: str, service: dict) -> str:
explicit = str(service.get("instructions_url", "")).strip()
if explicit:
return explicit
return f"/life-noc/item/{domain}/{item_key}"
def page_shell(title: str, body: str) -> HTMLResponse:
html = f"""<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{html_escape(title)}</title>
<style>{BASE_CSS}</style>
</head>
<body>
<main>{body}</main>
</body>
</html>"""
return HTMLResponse(content=html)
def require_admin_enabled() -> None:
if not ADMIN_UI_ENABLED:
raise HTTPException(status_code=404, detail="interface admin désactivée")
def bool_attr(value: bool) -> str:
return " checked" if value else ""
def option_tags(options: list[str], selected: str) -> str:
tags = []
for value in options:
label = value if value else "—"
sel = " selected" if value == selected else ""
tags.append(f'<option value="{html_escape(value)}"{sel}>{html_escape(label)}</option>')
return "".join(tags)
def render_alert(message: str) -> str:
if not message:
return ""
return f'<div class="alert">{html_escape(message)}</div>'
def render_domain_card(domain: str, items: list[dict]) -> str:
probed = sum(1 for item in items if isinstance(item, dict) and isinstance(item.get("probe"), dict))
return f"""
<article class="card">
<div class="row-between">
<div>
<p class="item-title">{html_escape(domain)}</p>
<p class="muted">{len(items)} item(s) · {probed} avec sonde réelle</p>
</div>
<a class="button primary" href="/life-noc/admin/domain/{html_escape(domain)}">Ouvrir</a>
</div>
</article>
"""
def render_item_card(domain: str, item: dict, index: int, total: int) -> str:
name = str(item.get("name", "")).strip()
title = str(item.get("title") or name or "Item").strip()
summary = str(item.get("summary") or item.get("notes") or "").strip()
probe_type = str(item.get("probe", {}).get("type", "mock") if isinstance(item.get("probe"), dict) else "mock")
probe_badge = f'<span class="pill">{html_escape(probe_type)}</span>'
move_up = f"""
<form method="post" action="/life-noc/admin/domain/{html_escape(domain)}/{html_escape(name)}/move">
<input type="hidden" name="direction" value="up">
<button title="Monter" {'disabled' if index == 0 else ''}>↑</button>
</form>
""" if total > 1 else ""
move_down = f"""
<form method="post" action="/life-noc/admin/domain/{html_escape(domain)}/{html_escape(name)}/move">
<input type="hidden" name="direction" value="down">
<button title="Descendre" {'disabled' if index == total - 1 else ''}>↓</button>
</form>
""" if total > 1 else ""
return f"""
<article class="card">
<div class="row-between">
<div>
<p class="item-title">{html_escape(title)}</p>
<p class="muted"><code>{html_escape(name)}</code></p>
<p class="muted">{html_escape(summary)}</p>
</div>
<div>{probe_badge}</div>
</div>
<div class="actions">
<a class="button" href="/life-noc/admin/item/{html_escape(domain)}/{html_escape(name)}">Voir</a>
<a class="button primary" href="/life-noc/admin/item/{html_escape(domain)}/{html_escape(name)}/edit">Modifier</a>
{move_up}
{move_down}
</div>
</article>
"""
def render_item_editor(domain: str, values: dict, action_url: str, heading: str, error_message: str = "") -> str:
thresholds_html = "".join(
f'''<label>{html_escape(field)}<input type="text" name="{html_escape(field)}" value="{html_escape(values.get(field, ''))}"></label>'''
for field in THRESHOLD_FIELDS
)
yaml_preview = render_yaml_preview(values)
return f"""
<section class="stack">
<div class="hero card">
<div class="toolbar">
<a class="button" href="/life-noc/admin/domain/{html_escape(domain)}">← Domaine</a>
<a class="button" href="/life-noc/admin">Accueil admin</a>
</div>
<h1>{html_escape(heading)}</h1>
<p class="muted">Éditeur mobile-first optionnel de <code>domains.yaml</code>. Sauvegarde explicite, sans changer le flux runtime existant.</p>
</div>
{render_alert(error_message)}
<form method="post" action="{html_escape(action_url)}" class="stack">
<details open>
<summary>Identité</summary>
<div class="form-grid two">
<label>Domaine
<input type="text" name="domain" value="{html_escape(domain)}" readonly>
</label>
<label>name
<input type="text" name="name" value="{html_escape(values.get('name', ''))}" required>
</label>
<label>Date de référence
<input type="date" name="date" value="{html_escape(values.get('date', ''))}">
</label>
<label>title
<input type="text" name="title" value="{html_escape(values.get('title', ''))}">
</label>
</div>
<div class="form-grid">
<label>summary
<textarea name="summary">{html_escape(values.get('summary', ''))}</textarea>
</label>
</div>
</details>
<details>
<summary>Contexte et contenu</summary>
<div class="form-grid">
<label>notes
<textarea name="notes">{html_escape(values.get('notes', ''))}</textarea>
</label>
<label>instructions
<textarea name="instructions">{html_escape(values.get('instructions', ''))}</textarea>
</label>
</div>
</details>
<details>
<summary>Liens</summary>
<div class="form-grid">
<label>notes_url<input type="text" name="notes_url" value="{html_escape(values.get('notes_url', ''))}"></label>
<label>instructions_url<input type="text" name="instructions_url" value="{html_escape(values.get('instructions_url', ''))}"></label>
<label>action_url<input type="text" name="action_url" value="{html_escape(values.get('action_url', ''))}"></label>
</div>
</details>
<details>
<summary>Sonde</summary>
<div class="form-grid two">
<label>probe.type
<select name="probe_type">{option_tags(ALLOWED_PROBE_TYPES, str(values.get('probe_type', '')))}</select>
</label>
<label>probe.source.type
<select name="probe_source_type">{option_tags(ALLOWED_SOURCE_TYPES, str(values.get('probe_source_type', '')))}</select>
</label>
<label>probe.source.inputs_file
<input type="text" name="probe_inputs_file" value="{html_escape(values.get('probe_inputs_file', ''))}">
</label>
<label>probe.source.item_key
<input type="text" name="probe_item_key" value="{html_escape(values.get('probe_item_key', ''))}">
</label>
<label>metric.unit
<select name="metric_unit">{option_tags(ALLOWED_METRIC_UNITS, str(values.get('metric_unit', '')))}</select>
</label>
<label>policy.on_error
<select name="policy_on_error">{option_tags(ALLOWED_ON_ERROR, str(values.get('policy_on_error', '')))}</select>
</label>
</div>
</details>
<details>
<summary>Seuils</summary>
<div class="form-grid two">
{thresholds_html}
</div>
</details>
<details>
<summary>Comportement UI</summary>
<div class="form-grid two">
<label>ui.form_mode
<select name="ui_form_mode">{option_tags(ALLOWED_FORM_MODES, str(values.get('ui_form_mode', '')))}</select>
</label>
</div>
<div class="checks">
<label class="check"><input type="checkbox" name="ui_allow_complete" value="1"{bool_attr(bool(values.get('ui_allow_complete', False)))}> ui.allow_complete</label>
<label class="check"><input type="checkbox" name="ui_allow_manual_edit" value="1"{bool_attr(bool(values.get('ui_allow_manual_edit', False)))}> ui.allow_manual_edit</label>
</div>
</details>
<details>
<summary>Aperçu YAML</summary>
<pre class="yaml-preview">{html_escape(yaml_preview)}</pre>
</details>
<div class="mobile-sticky">
<div class="card">
<div class="actions">
<button class="primary" type="submit">Écrire dans domains.yaml</button>
<a class="button" href="/life-noc/admin/domain/{html_escape(domain)}">Annuler</a>
</div>
</div>
</div>
</form>
</section>
"""
def render_yaml_preview(values: dict) -> str:
try:
payload = normalize_item_payload(values)
except Exception:
payload = {k: v for k, v in values.items() if k not in {"domain"}}
import yaml
return yaml.safe_dump(payload, sort_keys=False, allow_unicode=True, width=1000)
@app.get("/health")
def health() -> dict:
return {"status": "ok", "admin_ui_enabled": ADMIN_UI_ENABLED}
@app.get("/inputs/{domain}")
def api_list_inputs(domain: str) -> dict:
return {"domain": domain, "items": list_items(domain)}
@app.get("/inputs/{domain}/{item_key}")
def api_get_input(domain: str, item_key: str) -> dict:
try:
item = get_item(domain, item_key)
except KeyError:
raise HTTPException(status_code=404, detail="item introuvable")
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return {"domain": domain, "item_key": item_key, **item}
@app.post("/inputs/{domain}/{item_key}")
def api_set_input(domain: str, item_key: str, req: SetInputRequest) -> dict:
item = set_item(domain, item_key, req.value, origin=req.origin)
return {"domain": domain, "item_key": item_key, **item}
@app.post("/inputs/{domain}/{item_key}/complete")
def api_complete_input(domain: str, item_key: str, req: CompleteInputRequest | None = None) -> dict:
origin = "manual" if req is None else req.origin
item = complete_item(domain, item_key, origin=origin)
return {"domain": domain, "item_key": item_key, **item}
@app.post("/inputs/{domain}/{item_key}/counter")
def api_set_counter_pair(domain: str, item_key: str, req: CounterPairInputRequest) -> dict:
item = set_counter_pair(
domain,
item_key,
current_value=req.current_value,
reference_value=req.reference_value,
origin=req.origin or "manual",
)
return {"domain": domain, "item_key": item_key, **item}
@app.get("/life-noc/item/{domain}/{item_key}", response_class=HTMLResponse)
def page_item(domain: str, item_key: str) -> HTMLResponse:
try:
service = get_defined_service(domain, item_key)
except KeyError:
raise HTTPException(status_code=404, detail="item introuvable")
try:
current_input = get_item(domain, item_key)
except KeyError:
current_input = {}
try:
state = compute_state_for_item(domain, item_key)
except (KeyError, ValueError):
state = "UNKNOWN"
title = service.get("title") or service.get("display_name") or item_key.replace("-", " ").capitalize()
summary = service.get("summary", "")
notes = service.get("notes", "")
instructions = service.get("instructions", "")
notes_url = service.get("notes_url", "")
instructions_url = resolve_instructions_url(domain, item_key, service)
action_url = service.get("action_url", "")
probe_type = service.get("probe", {}).get("type", "unknown")
ui = service.get("ui", {}) if isinstance(service.get("ui", {}), dict) else {}
form_mode = ui.get("form_mode", "")
allow_complete = bool(ui.get("allow_complete", probe_type == "elapsed_time"))
allow_manual_edit = bool(ui.get("allow_manual_edit", True))
links_html = "".join(
fragment for fragment in [
link_row("Notes", notes_url),
link_row("Instructions", instructions_url),
link_row("Action", action_url),
] if fragment
) or "<li class=\"muted\">Aucun lien défini.</li>"
summary_html = f'<p><strong>Résumé :</strong> {html_escape(summary)}</p>' if summary else ""
instructions_html = ""
if instructions:
instructions_html = f"""
<section class="card">
<h2>Instructions</h2>
<pre style="white-space: pre-wrap; font-family: Arial, sans-serif;">{html_escape(instructions)}</pre>
</section>
"""
manual_form_html = ""
if allow_manual_edit and form_mode in {"complete_date", "due_date"}:
form_title = "Mettre à jour la date" if form_mode == "complete_date" else "Définir l’échéance"
field_label = "Date" if form_mode == "complete_date" else "Date d’échéance"
form_hint = ""
if form_mode == "due_date":
form_hint = '<p class="muted">Saisir la date cible de cette échéance.</p>'
manual_form_html = f"""
<section class="card">
<h2>{html_escape(form_title)}</h2>
{form_hint}
<form method="post" action="/life-noc/item/{html_escape(domain)}/{html_escape(item_key)}/set" class="form-grid">
<label>{html_escape(field_label)}
<input type="date" name="value" value="{html_escape(current_input.get('value', ''))}" required>
</label>
<input type="hidden" name="origin" value="manual">
<div class="actions">
<button type="submit">Enregistrer</button>
</div>
</form>
</section>
"""
elif allow_manual_edit and form_mode == "counter_pair":
manual_form_html = f"""
<section class="card">
<h2>Mettre à jour les compteurs</h2>
<p class="muted">Saisir le compteur courant et le compteur au dernier entretien.</p>
<form method="post" action="/life-noc/item/{html_escape(domain)}/{html_escape(item_key)}/counter" class="form-grid two">
<label>Compteur courant
<input type="text" inputmode="decimal" name="current_value" value="{html_escape(current_input.get('value', ''))}" required>
</label>
<label>Compteur au dernier entretien
<input type="text" inputmode="decimal" name="reference_value" value="{html_escape(current_input.get('reference_value', ''))}" required>
</label>
<input type="hidden" name="origin" value="manual">
<div class="actions">
<button type="submit">Enregistrer</button>
</div>
</form>
</section>
"""
elif allow_manual_edit and form_mode == "remaining_quantity":
unit = str(service.get("probe", {}).get("metric", {}).get("unit", "")).strip()
unit_hint = f" ({html_escape(unit)})" if unit else ""
manual_form_html = f"""
<section class="card">
<h2>Mettre à jour la quantité restante</h2>
<p class="muted">Saisir la quantité actuellement disponible{unit_hint}.</p>
<form method="post" action="/life-noc/item/{html_escape(domain)}/{html_escape(item_key)}/set" class="form-grid">
<label>Quantité restante{unit_hint}
<input type="text" inputmode="decimal" name="value" value="{html_escape(current_input.get('value', ''))}" required>
</label>
<input type="hidden" name="origin" value="manual">
<div class="actions">
<button type="submit">Enregistrer</button>
</div>
</form>
</section>
"""
elif allow_manual_edit and form_mode == "numeric_value":
unit = str(service.get("probe", {}).get("metric", {}).get("unit", "")).strip()
unit_hint = f" ({html_escape(unit)})" if unit else ""
manual_form_html = f"""
<section class="card">
<h2>Mettre à jour la valeur</h2>
<p class="muted">Saisir la valeur observée{unit_hint}.</p>
<form method="post" action="/life-noc/item/{html_escape(domain)}/{html_escape(item_key)}/set" class="form-grid">
<label>Valeur courante{unit_hint}
<input type="text" inputmode="decimal" name="value" value="{html_escape(current_input.get('value', ''))}" required>
</label>
<input type="hidden" name="origin" value="manual">
<div class="actions">
<button type="submit">Enregistrer</button>
</div>
</form>
</section>
"""
complete_form_html = ""
if allow_complete:
complete_form_html = f"""
<section class="card">
<h2>Action rapide</h2>
<form method="post" action="/life-noc/item/{html_escape(domain)}/{html_escape(item_key)}/complete">
<button type="submit" class="primary">Compléter</button>
</form>
</section>
"""
admin_link = ""
if ADMIN_UI_ENABLED:
admin_link = f'<a class="button" href="/life-noc/admin/item/{html_escape(domain)}/{html_escape(item_key)}">Admin</a>'
body = f"""
<section class="hero card">
<div class="toolbar">
<a class="button" href="/life-noc/item/{html_escape(domain)}/{html_escape(item_key)}">Actualiser</a>
{admin_link}
</div>
<h1>{html_escape(title)}</h1>
<p class="state">État actuel : {html_escape(state)}</p>
<p><strong>Type de sonde :</strong> {html_escape(probe_type)}</p>
{summary_html}
</section>
<section class="card">
<h2>Dernier intrant</h2>
<p><strong>Valeur :</strong> {html_escape(current_input.get('value', ''))}</p>
{f'<p><strong>Valeur de référence :</strong> {html_escape(current_input.get("reference_value", ""))}</p>' if 'reference_value' in current_input else ''}
<p><strong>Capturé le :</strong> {html_escape(current_input.get('captured_at', ''))}</p>
<p><strong>Origine :</strong> {html_escape(current_input.get('origin', ''))}</p>
</section>
<section class="card">
<h2>Contexte</h2>
<p><strong>Domaine :</strong> {html_escape(domain)}</p>
<p><strong>Item key :</strong> <code>{html_escape(item_key)}</code></p>
<p><strong>Notes :</strong> {html_escape(notes)}</p>
</section>
{instructions_html}
<section class="card">
<h2>Liens utiles</h2>
<ul>{links_html}</ul>
</section>
{manual_form_html}
{complete_form_html}
"""
return page_shell(f"Life-NOC — {title}", body)
@app.post("/life-noc/item/{domain}/{item_key}/set")
def page_set_item(domain: str, item_key: str, value: str = Form(...), origin: str = Form(default="manual")) -> RedirectResponse:
try:
set_item(domain, item_key, value=value, origin=origin)
except KeyError:
raise HTTPException(status_code=404, detail="item introuvable")
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return RedirectResponse(url=f"/life-noc/item/{domain}/{item_key}", status_code=303)
@app.post("/life-noc/item/{domain}/{item_key}/counter")
def page_set_counter(domain: str, item_key: str, current_value: str = Form(...), reference_value: str = Form(...), origin: str = Form(default="manual")) -> RedirectResponse:
try:
set_counter_pair(domain, item_key, current_value=current_value, reference_value=reference_value, origin=origin)
except KeyError:
raise HTTPException(status_code=404, detail="item introuvable")
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return RedirectResponse(url=f"/life-noc/item/{domain}/{item_key}", status_code=303)
@app.post("/life-noc/item/{domain}/{item_key}/complete")
def page_complete_item(domain: str, item_key: str, origin: str = Form(default="manual")) -> RedirectResponse:
try:
complete_item(domain, item_key, origin=origin)
except KeyError:
raise HTTPException(status_code=404, detail="item introuvable")
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return RedirectResponse(url=f"/life-noc/item/{domain}/{item_key}", status_code=303)
@app.get("/life-noc/admin", response_class=HTMLResponse)
def admin_home() -> HTMLResponse:
require_admin_enabled()
domain_cards = []
for domain in list_domains():
items = list_domain_items(domain)
domain_cards.append(render_domain_card(domain, items))
body = f"""
<section class="hero card">
<h1>Life-NOC Admin</h1>
<p class="muted">Interface web optionnelle pour administrer <code>domains.yaml</code> sans casser le pipeline existant.</p>
</section>
<section class="grid-cards">{''.join(domain_cards)}</section>
"""
return page_shell("Life-NOC Admin", body)
@app.get("/life-noc/admin/domain/{domain}", response_class=HTMLResponse)
def admin_domain(domain: str, error: str = "") -> HTMLResponse:
require_admin_enabled()
try:
items = list_domain_items(domain)
except KeyError:
raise HTTPException(status_code=404, detail="domaine introuvable")
cards = [render_item_card(domain, item, idx, len(items)) for idx, item in enumerate(items)]
body = f"""
<section class="hero card">
<div class="toolbar">
<a class="button" href="/life-noc/admin">← Accueil admin</a>
<a class="button primary" href="/life-noc/admin/domain/{html_escape(domain)}/new">Créer un item</a>
</div>
<h1>Domaine : {html_escape(domain)}</h1>
<p class="muted">{len(items)} item(s). Les boutons ↑ et ↓ réordonnent l’ordre des items dans <code>domains.yaml</code>.</p>
</section>
{render_alert(error)}
<section class="stack">{''.join(cards)}</section>
"""
return page_shell(f"Life-NOC Admin — {domain}", body)
@app.post("/life-noc/admin/domain/{domain}/{item_key}/move")
def admin_move_item(domain: str, item_key: str, direction: str = Form(...)) -> RedirectResponse:
require_admin_enabled()
try:
reorder_item(domain, item_key, direction)
except (DomainsError, KeyError) as exc:
target = f"/life-noc/admin/domain/{domain}?error={quote(str(exc))}"
return RedirectResponse(url=target, status_code=303)
return RedirectResponse(url=f"/life-noc/admin/domain/{domain}", status_code=303)
@app.get("/life-noc/admin/item/{domain}/{item_key}", response_class=HTMLResponse)
def admin_item(domain: str, item_key: str) -> HTMLResponse:
require_admin_enabled()
try:
item = get_domain_item(domain, item_key)
except KeyError:
raise HTTPException(status_code=404, detail="item introuvable")
values = item_to_form_values(item, domain)
yaml_preview = render_yaml_preview(values)
body = f"""
<section class="hero card">
<div class="toolbar">
<a class="button" href="/life-noc/admin/domain/{html_escape(domain)}">← Domaine</a>
<a class="button primary" href="/life-noc/admin/item/{html_escape(domain)}/{html_escape(item_key)}/edit">Modifier</a>
<a class="button" href="/life-noc/item/{html_escape(domain)}/{html_escape(item_key)}">Page item</a>
</div>
<h1>{html_escape(values.get('title') or item_key)}</h1>
<p class="muted"><code>{html_escape(item_key)}</code></p>
</section>
<section class="card">
<h2>Résumé</h2>
<p>{html_escape(values.get('summary') or values.get('notes') or '')}</p>
<p class="muted">probe.type = {html_escape(values.get('probe_type') or 'mock')}</p>
</section>
<section class="card">
<h2>Aperçu YAML</h2>
<pre class="yaml-preview">{html_escape(yaml_preview)}</pre>
</section>
<section class="card">
<form method="post" action="/life-noc/admin/item/{html_escape(domain)}/{html_escape(item_key)}/delete" onsubmit="return confirm('Supprimer cet item de domains.yaml ?');">
<button class="danger" type="submit">Supprimer l’item</button>
</form>
</section>
"""
return page_shell(f"Life-NOC Admin — {item_key}", body)
@app.get("/life-noc/admin/domain/{domain}/new", response_class=HTMLResponse)
def admin_new_item_form(domain: str, error: str = "") -> HTMLResponse:
require_admin_enabled()
try:
list_domain_items(domain)
except KeyError:
raise HTTPException(status_code=404, detail="domaine introuvable")
values = item_to_form_values(None, domain)
body = render_item_editor(domain, values, f"/life-noc/admin/domain/{domain}/new", f"Créer un item dans {domain}", error)
return page_shell(f"Life-NOC Admin — nouveau item {domain}", body)
@app.post("/life-noc/admin/domain/{domain}/new")
def admin_new_item_submit(
domain: str,
name: str = Form(...),
date: str = Form(default=""),
title: str = Form(default=""),
summary: str = Form(default=""),
notes: str = Form(default=""),
instructions: str = Form(default=""),
notes_url: str = Form(default=""),
instructions_url: str = Form(default=""),
action_url: str = Form(default=""),
probe_type: str = Form(default=""),
probe_source_type: str = Form(default=""),
probe_inputs_file: str = Form(default=""),
probe_item_key: str = Form(default=""),
metric_unit: str = Form(default=""),
policy_on_error: str = Form(default=""),
unknown_lt: str = Form(default=""),
ok_gte: str = Form(default=""),
warning_gte: str = Form(default=""),
critical_gte: str = Form(default=""),
unknown_gte: str = Form(default=""),
ok_lt: str = Form(default=""),
warning_lt: str = Form(default=""),
critical_lt: str = Form(default=""),
ui_form_mode: str = Form(default=""),
ui_allow_complete: str = Form(default=""),
ui_allow_manual_edit: str = Form(default=""),
) -> RedirectResponse:
require_admin_enabled()
form_values = {
key: value
for key, value in locals().items()
if key not in {"domain"}
}
try:
item = normalize_item_payload(form_values)
upsert_item(domain, item, original_item_key=None)
except (DomainsError, DomainsConflictError, KeyError) as exc:
return RedirectResponse(url=f"/life-noc/admin/domain/{domain}/new?error={quote(str(exc))}", status_code=303)
return RedirectResponse(url=f"/life-noc/admin/item/{domain}/{item['name']}", status_code=303)
@app.get("/life-noc/admin/item/{domain}/{item_key}/edit", response_class=HTMLResponse)
def admin_edit_item_form(domain: str, item_key: str, error: str = "") -> HTMLResponse:
require_admin_enabled()
try:
item = get_domain_item(domain, item_key)
except KeyError:
raise HTTPException(status_code=404, detail="item introuvable")
values = item_to_form_values(item, domain)
body = render_item_editor(domain, values, f"/life-noc/admin/item/{domain}/{item_key}/edit", f"Modifier {item_key}", error)
return page_shell(f"Life-NOC Admin — modifier {item_key}", body)
@app.post("/life-noc/admin/item/{domain}/{item_key}/edit")
def admin_edit_item_submit(
domain: str,
item_key: str,
name: str = Form(...),
date: str = Form(default=""),
title: str = Form(default=""),
summary: str = Form(default=""),
notes: str = Form(default=""),
instructions: str = Form(default=""),
notes_url: str = Form(default=""),
instructions_url: str = Form(default=""),
action_url: str = Form(default=""),
probe_type: str = Form(default=""),
probe_source_type: str = Form(default=""),
probe_inputs_file: str = Form(default=""),
probe_item_key: str = Form(default=""),
metric_unit: str = Form(default=""),
policy_on_error: str = Form(default=""),
unknown_lt: str = Form(default=""),
ok_gte: str = Form(default=""),
warning_gte: str = Form(default=""),
critical_gte: str = Form(default=""),
unknown_gte: str = Form(default=""),
ok_lt: str = Form(default=""),
warning_lt: str = Form(default=""),
critical_lt: str = Form(default=""),
ui_form_mode: str = Form(default=""),
ui_allow_complete: str = Form(default=""),
ui_allow_manual_edit: str = Form(default=""),
) -> RedirectResponse:
require_admin_enabled()
try:
existing = get_domain_item(domain, item_key)
except KeyError:
raise HTTPException(status_code=404, detail="item introuvable")
form_values = {
key: value
for key, value in locals().items()
if key not in {"domain", "item_key", "existing"}
}
try:
item = normalize_item_payload(form_values, existing_item=existing)
upsert_item(domain, item, original_item_key=item_key)
except (DomainsError, DomainsConflictError, KeyError) as exc:
return RedirectResponse(url=f"/life-noc/admin/item/{domain}/{item_key}/edit?error={quote(str(exc))}", status_code=303)
return RedirectResponse(url=f"/life-noc/admin/item/{domain}/{item['name']}", status_code=303)
@app.post("/life-noc/admin/item/{domain}/{item_key}/delete")
def admin_delete_item(domain: str, item_key: str) -> RedirectResponse:
require_admin_enabled()
try:
delete_item(domain, item_key)
except (DomainsError, KeyError) as exc:
return RedirectResponse(url=f"/life-noc/admin/domain/{domain}?error={quote(str(exc))}", status_code=303)
return RedirectResponse(url=f"/life-noc/admin/domain/{domain}", status_code=303)

View file

@ -1,227 +0,0 @@
#!/usr/bin/env python3
from __future__ import annotations
from pathlib import Path
import sys
from fastapi import FastAPI, HTTPException, Form
from fastapi.responses import HTMLResponse, RedirectResponse
from pydantic import BaseModel
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from lib.life_noc_inputs import ( # noqa: E402
list_items,
get_item,
set_item,
complete_item,
get_defined_service,
compute_state_for_item,
)
class SetInputRequest(BaseModel):
value: str
origin: str = "manual"
class CompleteInputRequest(BaseModel):
origin: str = "manual"
app = FastAPI(title="Life-NOC Input API", version="1.0.0")
def html_escape(value: str) -> str:
return (
str(value)
.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace('"', "&quot;")
)
def link_row(label: str, url: str) -> str:
if not url:
return ""
u = html_escape(url)
l = html_escape(label)
return f'<li><a href="{u}" target="_blank" rel="noopener">{l}</a></li>'
def resolve_instructions_url(domain: str, item_key: str, service: dict) -> str:
explicit = str(service.get("instructions_url", "")).strip()
if explicit:
return explicit
return f"/life-noc/item/{domain}/{item_key}"
@app.get("/health")
def health() -> dict:
return {"status": "ok"}
@app.get("/inputs/{domain}")
def api_list_inputs(domain: str) -> dict:
return {"domain": domain, "items": list_items(domain)}
@app.get("/inputs/{domain}/{item_key}")
def api_get_input(domain: str, item_key: str) -> dict:
try:
item = get_item(domain, item_key)
except KeyError:
raise HTTPException(status_code=404, detail="item introuvable")
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return {"domain": domain, "item_key": item_key, **item}
@app.post("/inputs/{domain}/{item_key}")
def api_set_input(domain: str, item_key: str, req: SetInputRequest) -> dict:
item = set_item(domain, item_key, req.value, origin=req.origin)
return {"domain": domain, "item_key": item_key, **item}
@app.post("/inputs/{domain}/{item_key}/complete")
def api_complete_input(domain: str, item_key: str, req: CompleteInputRequest | None = None) -> dict:
origin = "manual" if req is None else req.origin
item = complete_item(domain, item_key, origin=origin)
return {"domain": domain, "item_key": item_key, **item}
@app.get("/life-noc/item/{domain}/{item_key}", response_class=HTMLResponse)
def page_item(domain: str, item_key: str) -> HTMLResponse:
try:
service = get_defined_service(domain, item_key)
current_input = get_item(domain, item_key)
state = compute_state_for_item(domain, item_key)
except KeyError:
raise HTTPException(status_code=404, detail="item introuvable")
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
title = service.get("title") or service.get("display_name") or item_key.replace("-", " ").capitalize()
summary = service.get("summary", "")
notes = service.get("notes", "")
instructions = service.get("instructions", "")
notes_url = service.get("notes_url", "")
instructions_url = resolve_instructions_url(domain, item_key, service)
action_url = service.get("action_url", "")
probe_type = service.get("probe", {}).get("type", "unknown")
ui = service.get("ui", {}) if isinstance(service.get("ui", {}), dict) else {}
form_mode = ui.get("form_mode", "")
allow_complete = bool(ui.get("allow_complete", probe_type == "elapsed_time"))
allow_manual_edit = bool(ui.get("allow_manual_edit", True))
html = f"""<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Life-NOC — {html_escape(title)}</title>
<style>
body {{
font-family: Arial, sans-serif;
max-width: 760px;
margin: 0 auto;
padding: 1rem;
line-height: 1.45;
}}
.card {{
border: 1px solid #ccc;
border-radius: 10px;
padding: 1rem;
margin-bottom: 1rem;
}}
.state {{
font-size: 1.2rem;
font-weight: bold;
}}
button {{
font-size: 1rem;
padding: 0.9rem 1.2rem;
border-radius: 8px;
border: 1px solid #444;
cursor: pointer;
}}
ul {{
padding-left: 1.25rem;
}}
code {{
background: #f3f3f3;
padding: 0.1rem 0.3rem;
border-radius: 4px;
}}
</style>
</head>
<body>
<main>
<section class="card">
<h1>{html_escape(title)}</h1>
<p class="state">État actuel : {html_escape(state)}</p>
<p><strong>Type de sonde :</strong> {html_escape(probe_type)}</p>
</section>
<section class="card">
<h2>Dernier intrant</h2>
<p><strong>Valeur :</strong> {html_escape(current_input.get("value", ""))}</p>
<p><strong>Capturé le :</strong> {html_escape(current_input.get("captured_at", ""))}</p>
<p><strong>Origine :</strong> {html_escape(current_input.get("origin", ""))}</p>
</section>
<section class="card">
<h2>Contexte</h2>
<p><strong>Domaine :</strong> {html_escape(domain)}</p>
<p><strong>Item key :</strong> <code>{html_escape(item_key)}</code></p>
<p><strong>Notes :</strong> {html_escape(notes)}</p>
</section>
<section class="card">
<h2>Liens utiles</h2>
<ul>
{link_row("Notes", notes_url)}
{link_row("Instructions", instructions_url)}
{link_row("Action", action_url)}
</ul>
</section>
<section class="card">
<h2>Action</h2>
<form method="post" action="/life-noc/item/{html_escape(domain)}/{html_escape(item_key)}/complete">
<button type="submit">Compléter</button>
</form>
</section>
</main>
</body>
</html>"""
return HTMLResponse(content=html)
@app.post("/life-noc/item/{domain}/{item_key}/set")
def page_set_item(domain: str, item_key: str, value: str = Form(...), origin: str = Form(default="manual")) -> RedirectResponse:
try:
set_item(domain, item_key, value=value, origin=origin)
except KeyError:
raise HTTPException(status_code=404, detail="item introuvable")
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return RedirectResponse(
url=f"/life-noc/item/{domain}/{item_key}",
status_code=303,
)
@app.post("/life-noc/item/{domain}/{item_key}/complete")
def page_complete_item(domain: str, item_key: str, origin: str = Form(default="manual")) -> RedirectResponse:
try:
complete_item(domain, item_key, origin=origin)
except KeyError:
raise HTTPException(status_code=404, detail="item introuvable")
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return RedirectResponse(
url=f"/life-noc/item/{domain}/{item_key}",
status_code=303,
)

10
setops-app.yml Normal file
View file

@ -0,0 +1,10 @@
# Le contrat de Life-NOC avec Set-OPS (norme 1). Il décrit l'application, jamais l'infrastructure.
norme: 1
execution: python
version_runtime: "3.13"
demarrer: python3 -m lifenoc servir --hote 127.0.0.1 --port {port}
sante: /sante
etat:
dossier: donnees # réserve et un dossier par personne : sauvegardés, jamais dans git
dependances: debian
paquets: [python3-yaml, python3-segno, tzdata] # segno : les codes QR

254
tests/test_lifenoc.py Normal file
View file

@ -0,0 +1,254 @@
"""Tests de Life-NOC : `make tests` (bibliothèque standard seulement)."""
from __future__ import annotations
import json
import tempfile
import threading
import unittest
import urllib.error
import urllib.parse
import urllib.request
from datetime import date
from http.server import ThreadingHTTPServer
from pathlib import Path
from lifenoc import moteur, web
from lifenoc.donnees import Donnees, aujourdhui
from lifenoc.moteur import GRIS, ORANGE, ROUGE, VERT, evaluer
J = date(2026, 11, 15)
def couleur(element, valeur, reference=None):
intrant = None if valeur is None else {"valeur": valeur, **({"reference": reference} if reference else {})}
return evaluer(element, intrant, J).couleur
class Moteur(unittest.TestCase):
def test_depuis_les_quatre_couleurs_et_leurs_bornes(self):
e = {"depuis": [5, 7, 10]}
self.assertEqual(couleur(e, "2026-11-11"), GRIS) # 4 jours
self.assertEqual(couleur(e, "2026-11-10"), VERT) # 5 jours : à faire
self.assertEqual(couleur(e, "2026-11-08"), ORANGE) # 7 jours : pressé
self.assertEqual(couleur(e, "2026-11-05"), ROUGE) # 10 jours : en retard
def test_depuis_annonce_la_suite(self):
self.assertIn("à faire dans 1 jour", evaluer({"depuis": [5, 7, 10]}, {"valeur": "2026-11-11"}, J).message)
def test_avant_echeance(self):
e = {"avant": [30, 14, 7]}
self.assertEqual(couleur(e, "2026-12-15"), GRIS) # 30 jours restants
self.assertEqual(couleur(e, "2026-12-14"), VERT) # 29
self.assertEqual(couleur(e, "2026-11-28"), ORANGE) # 13
self.assertEqual(couleur(e, "2026-11-21"), ROUGE) # 6
self.assertEqual(couleur(e, "2026-11-01"), ROUGE) # dépassée
def test_km(self):
e = {"km": [4000, 5000, 6000]}
self.assertEqual(couleur(e, "103999", "100000"), GRIS)
self.assertEqual(couleur(e, "104000", "100000"), VERT)
self.assertEqual(couleur(e, "105000", "100000"), ORANGE)
self.assertEqual(couleur(e, "106000", "100000"), ROUGE)
self.assertEqual(couleur(e, "99000", "100000"), ROUGE) # compteur incohérent
def test_reste(self):
e = {"reste": [50, 50, 25], "unite": "%"}
self.assertEqual(couleur(e, "80"), GRIS)
self.assertEqual(couleur(e, "49"), ORANGE)
self.assertEqual(couleur(e, "24"), ROUGE)
self.assertEqual(couleur({"reste": [60, 40, 20]}, "55"), VERT)
def test_jamais_note_est_vert_et_a_noter(self):
for e in ({"depuis": [1, 2, 3]}, {"avant": [3, 2, 1]}, {"reste": [3, 2, 1]}, {"km": [1, 2, 3]}):
etat = evaluer(e, None, J)
self.assertEqual((etat.couleur, etat.a_noter), (VERT, True), e)
self.assertTrue(evaluer({"km": [1, 2, 3]}, {"valeur": "10"}, J).a_noter) # dernier entretien manquant
def test_illisible_est_rouge_sauf_si_erreur_gris(self):
self.assertEqual(couleur({"depuis": [1, 2, 3]}, "pas une date"), ROUGE)
self.assertEqual(couleur({"depuis": [1, 2, 3], "si_erreur": "gris"}, "pas une date"), GRIS)
self.assertEqual(couleur({"depuis": [1, 2, 3]}, "2026-12-01"), ROUGE) # futur
def test_definitions_invalides(self):
self.assertTrue(moteur.verifier_element({"depuis": [10, 7, 5]}))
self.assertTrue(moteur.verifier_element({"avant": [5, 7, 10]}))
self.assertTrue(moteur.verifier_element({"depuis": [1, 2]}))
self.assertTrue(moteur.verifier_element({"depuis": [1, 2, 3], "avant": [3, 2, 1]}))
self.assertTrue(moteur.verifier_element({"depui": [1, 2, 3]}))
self.assertTrue(moteur.verifier_element({"liens": {"x": "javascript:alert(1)"}}))
self.assertEqual(moteur.verifier_element({"depuis": [5, 7, 10], "liens": {"a": "https://x"}}), [])
def test_sans_mesure_est_gris(self):
self.assertEqual(couleur({"notes": "à définir"}, None), GRIS)
def test_gestes(self):
self.assertEqual(moteur.noter({"depuis": [1, 2, 3]}, None, "fait", "", J)["valeur"], "2026-11-15")
self.assertEqual(moteur.noter({"depuis": [1, 2, 3]}, None, "fait", "2026-11-10", J)["valeur"], "2026-11-10")
with self.assertRaises(ValueError):
moteur.noter({"depuis": [1, 2, 3]}, None, "fait", "2026-11-16", J)
with self.assertRaises(ValueError):
moteur.noter({"depuis": [1, 2, 3]}, None, "valeur", "3", J)
i = moteur.noter({"km": [1, 2, 3]}, None, "reference", "100", J)
i = moteur.noter({"km": [1, 2, 3]}, i, "compteur", "112,5", J)
self.assertEqual((i["valeur"], i["reference"]), ("112.5", "100"))
i = moteur.noter({"km": [1, 2, 3]}, i, "entretien", "113", J)
self.assertEqual((i["valeur"], i["reference"]), ("113", "113"))
class Stockage(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.d = Donnees(self.tmp.name)
self.p = self.d.creer_personne("daniel", "Daniel")
self.p.poser_element("revue", "hebdo", {"titre": "Revue de la semaine", "depuis": [5, 7, 10]})
def tearDown(self):
self.tmp.cleanup()
def test_noter_puis_annuler(self):
self.assertTrue(self.p.ligne("revue", "hebdo").etat.a_noter)
self.p.noter("revue", "hebdo", "fait", "2026-01-01")
self.p.noter("revue", "hebdo", "fait")
self.assertEqual(self.p.ligne("revue", "hebdo").etat.couleur, GRIS)
self.p.annuler("revue", "hebdo")
self.assertEqual(self.p.intrants()["revue/hebdo"]["valeur"], "2026-01-01")
with self.assertRaises(ValueError): # un seul niveau
self.p.annuler("revue", "hebdo")
self.assertEqual([j[2] for j in self.p.journal()], ["annuler", "fait", "fait"])
def test_annuler_le_premier_geste_revient_a_jamais_note(self):
self.p.noter("revue", "hebdo", "fait")
self.p.annuler("revue", "hebdo")
self.assertTrue(self.p.ligne("revue", "hebdo").etat.a_noter)
def test_poser_et_retirer(self):
with self.assertRaises(ValueError):
self.p.poser_element("revue", "hebdo", {"depuis": [1, 2, 3]}) # existe déjà
with self.assertRaises(ValueError):
self.p.poser_element("revue", "x", {"depuis": [3, 2, 1]}) # seuils à l'envers
self.p.noter("revue", "hebdo", "fait")
self.p.retirer_element("revue", "hebdo")
self.assertEqual(self.p.elements(), {})
self.assertEqual(self.p.intrants(), {})
self.assertEqual(self.p.journal()[0][2], "retirer")
def test_identifiants_refuses(self):
for mauvais in ("../x", "Daniel", "", "a/b", ".."):
with self.assertRaises(ValueError):
self.d.creer_personne(mauvais, "X")
with self.assertRaises(KeyError):
self.d.personne(mauvais)
class Ecrans(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.d = Donnees(cls.tmp.name)
cls.d.ecrire_reserve({"maison": {"filtre": {"titre": "Changer le filtre", "depuis": [80, 90, 120]}}})
web.Gestionnaire.donnees = cls.d
web.Gestionnaire.log_message = lambda *a: None # pas de journal pendant les tests
cls.serveur = ThreadingHTTPServer(("127.0.0.1", 0), web.Gestionnaire)
cls.base = f"http://127.0.0.1:{cls.serveur.server_address[1]}"
threading.Thread(target=cls.serveur.serve_forever, daemon=True).start()
@classmethod
def tearDownClass(cls):
cls.serveur.shutdown()
cls.tmp.cleanup()
def get(self, chemin):
try:
with urllib.request.urlopen(self.base + chemin) as r:
return r.status, r.read().decode()
except urllib.error.HTTPError as e:
return e.code, e.read().decode()
def post(self, chemin, champs: dict | list, entetes=None):
donnees = urllib.parse.urlencode(champs).encode()
req = urllib.request.Request(self.base + chemin, data=donnees, headers=entetes or {})
try:
with urllib.request.urlopen(req) as r:
return r.status, r.read().decode()
except urllib.error.HTTPError as e:
return e.code, e.read().decode()
def test_parcours_complet(self):
# L'aidant crée la personne, puis un élément ; le titre contient du HTML.
self.assertEqual(self.post("/config/", {"nom": "Mère <b>", "ident": ""})[0], 200)
p = self.d.personne("mere-b") # l'identifiant vient du nom
statut, html = self.get("/p/mere-b/")
self.assertIn("Rien n'est suivi", html)
statut, html = self.post("/config/mere-b/nouveau", {
"titre": "Pilulier <script>", "domaine": "Santé", "notes": "Le pilulier du jour",
"mesure": "depuis", "s0": "1", "s1": "1", "s2": "2", "unite": "", "liens": "", "instructions": ""})
self.assertEqual(statut, 200)
self.assertIn("Pilulier &lt;script&gt;", html) # la supervision, échappée
self.assertNotIn("<script>", html)
# La personne aidée : jamais noté → vert, avec la question.
statut, html = self.get("/p/mere-b/")
self.assertIn("Bonjour Mère &lt;b&gt;", html)
self.assertIn("Quand l&#x27;avez-vous fait la dernière fois", html)
# Elle touche « C'est fait » : bandeau « Noté », puis tout est fait.
statut, html = self.post("/p/mere-b/e/sante/pilulier-script", {"geste": "fait"})
self.assertIn("Noté : Pilulier", html)
self.assertIn("Tout est fait pour aujourd", html)
# Elle s'est trompée : Annuler.
statut, html = self.post("/p/mere-b/annuler", {"cle": "sante/pilulier-script"})
self.assertIn("Quand l&#x27;avez-vous fait", html)
# L'aidant voit ; puise dans la réserve ; modifie ; retire avec confirmation.
self.assertEqual(self.get("/config/mere-b/")[0], 200)
self.assertEqual(self.get("/config/mere-b/journal")[0], 200)
self.assertEqual(self.get("/config/mere-b/qr")[0], 200)
self.post("/config/mere-b/reserve", [("cle", "maison/filtre"), ("cle", "maison/absent")])
self.assertIn("filtre", p.elements()["maison"])
statut, _ = self.post("/config/mere-b/e/maison/filtre", {
"titre": "Filtre de la fournaise", "domaine": "autre", "mesure": "depuis", "s0": "60", "s1": "90", "s2": "120"})
self.assertEqual(p.elements()["maison"]["filtre"]["depuis"], [60, 90, 120]) # domaine inchangé
self.assertEqual(self.post("/config/mere-b/e/maison/filtre/retirer", {})[0], 400)
self.post("/config/mere-b/e/maison/filtre/retirer", {"confirmer": "oui"})
self.assertNotIn("maison", p.elements())
@unittest.skipUnless(__import__("importlib").util.find_spec("segno"), "python3-segno absent")
def test_codes_qr(self):
import segno
p = self.d.creer_personne("qr", "Qr")
p.poser_element("maison", "filtre", {"depuis": [1, 2, 3]})
req = urllib.request.Request(self.base + "/config/qr/qr",
headers={"Host": "noc.exemple.internal", "X-Forwarded-Proto": "https"})
with urllib.request.urlopen(req) as r:
html = r.read().decode()
attendu = segno.make("https://noc.exemple.internal/p/qr/e/maison/filtre", error="m").svg_inline(
scale=4, border=4, dark="#000", light="#fff")
self.assertIn(attendu, html) # le code porte l'adresse publique
self.assertNotIn("Ne pas imprimer", html)
self.assertIn("Ne pas imprimer", self.get("/config/qr/qr")[1]) # 127.0.0.1 : avertissement
def test_formulaire_invalide_garde_la_saisie(self):
self.d.creer_personne("essai", "Essai")
statut, html = self.post("/config/essai/nouveau", {"titre": "Truc", "domaine": "x", "mesure": "depuis",
"s0": "10", "s1": "5", "s2": "1"})
self.assertEqual(statut, 400)
self.assertIn("À corriger", html)
self.assertIn('value="Truc"', html)
def test_refus_et_introuvables(self):
self.assertEqual(self.get("/p/..%2F..%2Fetc/")[0], 404)
self.assertEqual(self.get("/p/inconnu/")[0], 404)
self.assertEqual(self.post("/config/", {"nom": "X"}, {"Sec-Fetch-Site": "cross-site"})[0], 403)
self.assertIn("ok", self.get("/sante")[1])
def test_api(self):
self.d.creer_personne("api", "Api")
self.d.personne("api").poser_element("stock", "eau", {"reste": [20, 10, 5], "unite": "litres"})
req = urllib.request.Request(self.base + "/api/api/element/stock/eau",
data=json.dumps({"geste": "valeur", "saisie": "8", "par": "capteur"}).encode())
with urllib.request.urlopen(req) as r:
self.assertEqual(json.loads(r.read())["valeur"], "8")
etats = json.loads(self.get("/api/api/etats")[1])
self.assertEqual(etats[0]["couleur"], ORANGE)
if __name__ == "__main__":
unittest.main()