Skip to content

feat(alerts): allow module-provided rules - #91

Merged
gsanchietti merged 19 commits into
mainfrom
module-alert-rules
Oct 20, 2026
Merged

gsanchietti merged 19 commits into
mainfrom
module-alert-rules

Conversation

@Amygos

@Amygos Amygos commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Goal: let each module ship its own alerts, without running an extra exporter. This PR lets a module publish Prometheus alert rules through Redis (NethServer/dev#8100). It builds on the module identity support from #79.

Three pieces work together:

Each module's rules are checked on their own. A bad rule from one module never blocks the others: its last working version stays active. When rules change or a module is removed, Prometheus reloads its rules without a restart.

  • Rules that did not change are not checked again, so Prometheus starts quickly even with many rules.
  • If a check fails, the error is logged and the other rules are still applied. Rules of removed modules are always cleaned up.
  • Config files are written safely, so a reload never reads a half-written file, even when several events run at the same time.
  • New Robot tests cover publishing, a bad update, and removing a rule.

Example

A rule that fires when the kamailio container of the module is not running, while its other containers are:

count by (module_id, node) (ns8_container_info)
  unless on (module_id, node)
count by (module_id, node) (ns8_container_info{unit="kamailio.service"})

module_id is added to every selector, so the rule only checks the containers of the module that published it.

openldap1 has only one container. When it stops, no series of the module is left, so the rule uses absent(). Publish it and send the change event:

redis-cli HSET module/openldap1/metrics_alert_rules openldap-down '{alert: OpenldapDown, expr: "absent(ns8_container_info{unit=\"openldap.service\"})", for: 5m, labels: {severity: critical}, annotations: {summary_en: "OpenLDAP is down", summary_it: "OpenLDAP non è attivo"}}'
redis-cli PUBLISH module/openldap1/event/metrics-alert-rules-changed '{}'

Stop it with runagent -m openldap1 systemctl --user stop openldap.service: the alert fires after about 7 minutes (1 minute for the collector, 1 for the scrape, 5 for for).

How to test

  • Install the PR image and run tests/20__module_alert_rules.robot.
  • Publish a rule in module/<module_id>/metrics_alert_rules, send the metrics-alert-rules-changed event, and check that the rule appears in Prometheus without a restart.
  • Publish a broken rule and check that the previous rule stays active and a warning is logged.
  • With feat(prometheus): add module_id to node series #105: stop a module service and check that the rule above fires.

See also


Generated by Claude Code:claude-opus-5-5 with nethserver-pr

@Amygos Amygos self-assigned this Sep 25, 2026
@Amygos Amygos linked an issue Sep 28, 2026 that may be closed by this pull request
@Amygos
Amygos force-pushed the module-alert-rules branch from 91eb85c to 63db151 Compare October 2, 2026 07:45
@Amygos
Amygos marked this pull request as ready for review October 2, 2026 07:45
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-02T07:52:21.438874Z 63db151 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 63db1514b2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/pythonreq.txt Resolved
Comment thread imageroot/bin/reload-prometheus-rules Resolved
Comment thread imageroot/bin/provision-prometheus Resolved
@Amygos
Amygos force-pushed the module-alert-rules branch from 63db151 to cafb5e6 Compare October 2, 2026 13:25
@Amygos
Amygos changed the base branch from main to feat/alerts-my-cutover October 2, 2026 13:25
@DavidePrincipi

Copy link
Copy Markdown
Member

I'd look at this PR when my.nethesis.it migration has been launched since we're releasing ns8-metrics for it.

Base automatically changed from feat/alerts-my-cutover to main October 6, 2026 06:39

@gsanchietti gsanchietti left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor changes but I think they worth:

  • avoid crash loop with a new try/catch
  • raise startup timeout

Comment thread imageroot/bin/provision-prometheus Resolved
Comment thread imageroot/bin/provision-prometheus Resolved

@DavidePrincipi DavidePrincipi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To generate less rules and lower startup timeout, I'd consider (if possible, and not already done) to group the same rules for multiple modules.

@Amygos
Amygos force-pushed the module-alert-rules branch from d4ad2e2 to 488ffb2 Compare October 12, 2026 08:12
Amygos added a commit that referenced this pull request Oct 12, 2026
Warn on module-rule infrastructure failures so Prometheus startup and
reloads can finish with stale or incomplete rules. Continue generating
legacy rules and templates while keeping other failures fatal.

Cover partial updates, recovery cleanup, and exception propagation in
entrypoint tests.

#91 (comment)

Assisted-by: Codex:GPT-6
Amygos added a commit that referenced this pull request Oct 12, 2026
Warn on module-rule infrastructure failures so Prometheus startup and
reloads can finish with stale or incomplete rules. Continue generating
legacy rules and templates while keeping other failures fatal.

#91 (comment)

Assisted-by: Codex:GPT-6
@Amygos
Amygos force-pushed the module-alert-rules branch from 1f5f99d to 22733e1 Compare October 12, 2026 14:46
Validate and normalize module alert rules with distinct group
namespaces, scoped PromQL selectors, and a fixed module_id label.

Use the pinned Prometheus parser in networkless containers. Choose a
temporary matcher label absent from formatted PromQL so authored labels
remain intact when applying module scope.

Assisted-by: Codex:GPT-5
Assisted-by: Codex:GPT-6-Astra
Validate Redis target keys and identifiers before file access, sharing
the filename policy with alert rules. Skip invalid fields independently
and report their Redis key and field while propagating filesystem
failures.

Discover alert rules by output filename, reject collisions, and validate
candidates with promtool before atomic replacement. Retain prior valid
rules for invalid sources, preserve module and severity labels, and keep
built-in and legacy custom rules intact.

Use raw Redis responses so rule validation rejects malformed UTF-8
without preventing valid sources from being provisioned.

Assisted-by: Codex:GPT-5
Assisted-by: Codex:GPT-6-Astra
Provision module alert rules before reloading an active Prometheus
service. Verify successful activation through reload metrics and fall
back to a verified restart when the reload cannot be confirmed.

Keep inactive services stopped and allow valid rules to reference
metrics that have not been scraped yet.

Assisted-by: Codex:GPT-5
Assisted-by: Codex:GPT-6-Astra
Use a fixed temporary file prefix so 255-byte rule filenames remain
valid. Keep candidates beside their destinations for atomic
replacement.

Assisted-by: Codex:GPT-5
Assisted-by: Codex:GPT-6-Astra
Terminate promtool option parsing before each expression so valid
negative PromQL survives formatting and matcher rewrites.

Assisted-by: Codex:GPT-6-Astra
Read module targets as raw Redis data and decode each source separately
so malformed keys, fields, or payloads do not block valid publishers.
Keep decoded node and legacy configuration reads and propagate genuine
Redis or filesystem failures.

Assisted-by: Codex:GPT-6-Astra
Copy group and rule label mappings before enforcing module identity.
YAML anchors can share those mappings with annotations, whose authored
values must survive rewriting and validation unchanged.

Assisted-by: Codex:GPT-6-Astra
Allow 120 seconds for startup provisioning before systemd times out.
Keep the reload verification window at 30 seconds.

Assisted-by: Codex:GPT-6
Treat an observed reload-success value of zero as an explicit rejection.
Keep polling for recovery, but fail without restarting if verification
expires after rejection, even when later metrics are unavailable.

Preserve checked restart fallback for inconclusive verification and
reload-command failures.

Assisted-by: Codex:GPT-6
Warn on module-rule infrastructure failures so Prometheus startup and
reloads can finish with stale or incomplete rules. Continue generating
legacy rules and templates while keeping other failures fatal.

#91 (comment)

Assisted-by: Codex:GPT-6
Cover scoped publication, invalid-update isolation, and publisher
withdrawal through Redis events and the Prometheus API.

Use unique fixtures, verify reloads and service readiness, and remove
published fields and loaded rules during teardown.

Assisted-by: Codex:GPT-6
@gsanchietti gsanchietti self-assigned this Oct 16, 2026
Promtool output is reused as the rewritten PromQL expression, but
podman stderr was merged into it. A harmless rootless podman warning
could corrupt the expression and reject every module rule.

Capture stderr separately, return stdout only, and still use both
streams to detect tooling errors and build error messages.

Assisted-by: Claude Code:Opus 5.5
Prometheus startup re-transformed every module rule set with several
podman runs each time, which can push ExecStartPre past the start
timeout once enough module rules exist.

Store a fingerprint of the payload, source identity, Prometheus image,
and output format in the generated file header. Unchanged sources are
skipped, so their transformation warnings are logged only when the
file is rewritten.

Assisted-by: Claude Code:Opus 5.5
One podman or I/O failure aborted module rule provisioning. Later
sources were skipped and stale rules from removed modules stayed
loaded, so their alerts could keep firing.

Handle infrastructure errors per source, keep the previous file of a
failed source, always clean up stale files, and tolerate files that
vanish meanwhile. One summary error is raised at the end, so the
caller still warns that rules may be incomplete.

Assisted-by: Claude Code:Opus 5.5
Rule events now reload Prometheus right after provisioning, and event
handlers can run concurrently. A reload could read a config or rule
file while another run was still rewriting it, and load an empty or
partial configuration.

Serialize provisioning with a lock and replace files in mounted
directories atomically. prometheus.yml and alertmanager.yml are
single-file bind mounts that cannot be replaced, so rewrite them only
when their content changes.

Assisted-by: Claude Code:Opus 5.5
Core 3.22.0 publishes per-module series on the node exporter, such as
ns8_container_* and ns8_module_*_bytes, labeled with "module". Module
alert rules are scoped by "module_id", so they could not match them.

Copy "module" to "module_id" on node targets, only when the series has
no module_id and the value is a module ID. Modules can then alert on
their own containers without running a dedicated exporter.

Assisted-by: Claude Code:claude-sonnet-5-5
Node series now carry module_id, a copy of module. The raw
ns8_container_info query of the Containers table would show it as an
extra, duplicated column.

Assisted-by: Claude Code:claude-haiku-5-5

@DavidePrincipi DavidePrincipi left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small refactor
Releted NethServer/ns8-core#1367

Comment thread imageroot/bin/provision-prometheus Resolved
Comment thread imageroot/bin/metrics_alert_rules.py Resolved
Replace the local temp-file-and-rename helpers with agent.safe_open(),
which already provides crash-safe atomic writes in the core agent
library, as requested in review.

Module alert rules are now validated by piping the candidate to
promtool on standard input, so no temporary file or volume mount is
needed before installing the rule file with safe_open().

Assisted-by: Claude Code:claude-sonnet-5-5
@gsanchietti
gsanchietti merged commit 5e896e4 into main Oct 20, 2026
8 checks passed
gsanchietti pushed a commit that referenced this pull request Oct 20, 2026
Warn on module-rule infrastructure failures so Prometheus startup and
reloads can finish with stale or incomplete rules. Continue generating
legacy rules and templates while keeping other failures fatal.

#91 (comment)

Assisted-by: Codex:GPT-6
@gsanchietti
gsanchietti deleted the module-alert-rules branch October 20, 2026 06:01
gsanchietti added a commit that referenced this pull request Oct 28, 2026
Module alert rules, added in #91, are no longer experimental but the
README did not explain how to publish them. Describe the
metrics_alert_rules hash, the metrics-alert-rules-changed event, the
module_id scoping and the failure handling, with an example.

Also drop the experimental warnings from the custom alert rules and
mail template sections, and fix a typo in a heading.

Assisted-by: Claude Code:claude-sonnet-5-5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Allow applications to provide their own alert rules

4 participants