Functional Weave
Code in Rust

monitor.alert-mute@1.0.0

impl/python.py

1,605 bytes · the Python implementation · view raw

from typing import Sequence

from .monitor_alert_mute_types import AlertMute, MutePolicy


def mute_alert(kind: str, under_maintenance: bool, firing_kinds: Sequence[str], policy: MutePolicy) -> AlertMute:
    """Hold an alert back, as Alertmanager's silences and inhibit rules do:
    during its component's maintenance if its kind is one maintenance mutes,
    or while an alert that inhibits it fires on the same component. The whole
    policy is checked every time, so a mistake in it fails loudly rather than
    silently never muting. The caller passes `condition and not muted` to
    monitor.alert-state."""
    if kind == "":
        raise ValueError("kind must not be empty")
    for k in policy.maintenance:
        if k == "":
            raise ValueError("maintenance kinds must not be empty")
    for rule in policy.inhibit:
        if rule.source == "":
            raise ValueError("inhibition source must not be empty")
        if rule.target == "":
            raise ValueError("inhibition target must not be empty")
        if rule.source == rule.target:
            raise ValueError("an alert kind cannot inhibit itself: %s" % (rule.source,))
    if under_maintenance and kind in policy.maintenance:
        return AlertMute(muted=True, reason="maintenance", by=None)
    for rule in policy.inhibit:
        # source != target, so an alert listed among firingKinds never inhibits itself.
        if rule.target == kind and rule.source in firing_kinds:
            return AlertMute(muted=True, reason="inhibited", by=rule.source)
    return AlertMute(muted=False, reason=None, by=None)