beaconry 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- beaconry/__init__.py +64 -0
- beaconry/__main__.py +155 -0
- beaconry/channels.py +135 -0
- beaconry/evaluate.py +294 -0
- beaconry/evidence.py +59 -0
- beaconry/history.py +174 -0
- beaconry/model.py +210 -0
- beaconry/monitor.py +226 -0
- beaconry/scrub.py +181 -0
- beaconry/stores.py +47 -0
- beaconry/tools.py +139 -0
- beaconry-0.0.1.dist-info/METADATA +95 -0
- beaconry-0.0.1.dist-info/RECORD +16 -0
- beaconry-0.0.1.dist-info/WHEEL +4 -0
- beaconry-0.0.1.dist-info/entry_points.txt +2 -0
- beaconry-0.0.1.dist-info/licenses/LICENSE +21 -0
beaconry/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""beaconry: monitoring notifications that remember what they said, and why.
|
|
2
|
+
|
|
3
|
+
A monitor runs its checks and hands them to :func:`tick`. beaconry decides whether that
|
|
4
|
+
is news (alert on change, reminders with backoff, resolved and recovered notices,
|
|
5
|
+
hysteresis against flapping, retry backoff on failed delivery), gathers evidence,
|
|
6
|
+
scrubs secrets, sends the notice, and records it, with its delivery outcome, in a
|
|
7
|
+
history an agent can read in one call (``beaconry latest <source> --json``).
|
|
8
|
+
|
|
9
|
+
>>> from beaconry import Check, tick
|
|
10
|
+
>>> sent = []
|
|
11
|
+
>>> n = tick(
|
|
12
|
+
... [Check("disk", "Disk /", "crit", "95% used", remedy="free some space")],
|
|
13
|
+
... source="box", history={}, state_store={},
|
|
14
|
+
... send=lambda notice: (sent.append(notice.title) or True, ""),
|
|
15
|
+
... )
|
|
16
|
+
>>> n.title, n.delivery["ok"], sent
|
|
17
|
+
('box: 1 issue(s)', True, ['box: 1 issue(s)'])
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from beaconry.channels import correspond_sender, ntfy_sender
|
|
21
|
+
from beaconry.evaluate import Decision, alert_part, evaluate, parse_state, signature
|
|
22
|
+
from beaconry.evidence import gather_default, journal
|
|
23
|
+
from beaconry.history import History
|
|
24
|
+
from beaconry.model import (
|
|
25
|
+
CRIT,
|
|
26
|
+
NOTICE_KINDS,
|
|
27
|
+
OK,
|
|
28
|
+
WARN,
|
|
29
|
+
Check,
|
|
30
|
+
Notice,
|
|
31
|
+
Policy,
|
|
32
|
+
resolve_policy,
|
|
33
|
+
)
|
|
34
|
+
from beaconry.monitor import adopt_state, notify, send_test, tick
|
|
35
|
+
from beaconry.scrub import scrub
|
|
36
|
+
from beaconry.stores import beaconry_home, json_store
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"CRIT",
|
|
40
|
+
"Check",
|
|
41
|
+
"Decision",
|
|
42
|
+
"History",
|
|
43
|
+
"NOTICE_KINDS",
|
|
44
|
+
"Notice",
|
|
45
|
+
"OK",
|
|
46
|
+
"Policy",
|
|
47
|
+
"WARN",
|
|
48
|
+
"adopt_state",
|
|
49
|
+
"alert_part",
|
|
50
|
+
"beaconry_home",
|
|
51
|
+
"correspond_sender",
|
|
52
|
+
"evaluate",
|
|
53
|
+
"gather_default",
|
|
54
|
+
"journal",
|
|
55
|
+
"json_store",
|
|
56
|
+
"notify",
|
|
57
|
+
"ntfy_sender",
|
|
58
|
+
"parse_state",
|
|
59
|
+
"resolve_policy",
|
|
60
|
+
"scrub",
|
|
61
|
+
"send_test",
|
|
62
|
+
"signature",
|
|
63
|
+
"tick",
|
|
64
|
+
]
|
beaconry/__main__.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# PYTHON_ARGCOMPLETE_OK
|
|
2
|
+
"""The ``beaconry`` command line: read the notice history.
|
|
3
|
+
|
|
4
|
+
::
|
|
5
|
+
|
|
6
|
+
beaconry latest [source] [--kind K] [--json] [--on HOST]
|
|
7
|
+
beaconry list [source] [--since 2d] [--kind K] [--q TEXT] [--limit N] [--json] [--on HOST]
|
|
8
|
+
beaconry show <id> [--json] [--on HOST]
|
|
9
|
+
beaconry sources [--json] [--on HOST]
|
|
10
|
+
|
|
11
|
+
Human output is short; ``--json`` is the format for agents (and what ``--on HOST``
|
|
12
|
+
asks the other machine for). Each command is a thin wrapper over the same function in
|
|
13
|
+
:mod:`beaconry.tools`.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import functools
|
|
19
|
+
import json as _json
|
|
20
|
+
|
|
21
|
+
import cw
|
|
22
|
+
|
|
23
|
+
from beaconry import tools
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _dumps(obj) -> str:
|
|
27
|
+
return _json.dumps(obj, indent=2, ensure_ascii=False)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _first_line(s: str, width: int = 160) -> str:
|
|
31
|
+
line = (s or "").strip().splitlines()[0] if (s or "").strip() else ""
|
|
32
|
+
return line if len(line) <= width else line[: width - 3] + "..."
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def format_notice(n: dict) -> str:
|
|
36
|
+
"""A notice as a few lines: header, body, checks (with remedies), evidence summary."""
|
|
37
|
+
d = n.get("delivery") or {}
|
|
38
|
+
delivered = (
|
|
39
|
+
"delivered" if d.get("ok") else f"NOT delivered ({d.get('error') or 'unknown'})"
|
|
40
|
+
)
|
|
41
|
+
out = [
|
|
42
|
+
f"{n['ts']} [{n['kind']}] {n['title']} ({delivered} via {d.get('channel', '?')})"
|
|
43
|
+
]
|
|
44
|
+
out.append(f"id: {n['id']}")
|
|
45
|
+
if n.get("body"):
|
|
46
|
+
out += ["", n["body"]]
|
|
47
|
+
if n.get("checks"):
|
|
48
|
+
out.append("")
|
|
49
|
+
for c in n["checks"]:
|
|
50
|
+
out.append(f"[{c['status']}] {c['label']}: {c.get('value', '')}")
|
|
51
|
+
if c.get("detail"):
|
|
52
|
+
out.append(f" {_first_line(c['detail'])}")
|
|
53
|
+
if c.get("remedy"):
|
|
54
|
+
out.append(f" remedy: {_first_line(c['remedy'])}")
|
|
55
|
+
journal = (n.get("evidence") or {}).get("journal") or {}
|
|
56
|
+
if journal:
|
|
57
|
+
out += [
|
|
58
|
+
"",
|
|
59
|
+
"evidence: "
|
|
60
|
+
+ ", ".join(
|
|
61
|
+
f"{u} ({len(t.splitlines())} journal lines)" for u, t in journal.items()
|
|
62
|
+
),
|
|
63
|
+
]
|
|
64
|
+
return "\n".join(out)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _errors_as_command_errors(func):
|
|
68
|
+
"""Expected failures (unknown id, bad input, a remote error) as one line, no traceback."""
|
|
69
|
+
|
|
70
|
+
@functools.wraps(func)
|
|
71
|
+
def wrapper(*args, **kwargs):
|
|
72
|
+
try:
|
|
73
|
+
return func(*args, **kwargs)
|
|
74
|
+
except (KeyError, ValueError, tools.RemoteError) as e:
|
|
75
|
+
msg = e.args[0] if isinstance(e, KeyError) and e.args else str(e)
|
|
76
|
+
raise cw.CommandError(f"beaconry: {msg}") from None
|
|
77
|
+
|
|
78
|
+
return wrapper
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@_errors_as_command_errors
|
|
82
|
+
def latest(source: str = None, *, kind: str = None, json: bool = False, on: str = None):
|
|
83
|
+
"""The newest notice (of SOURCE), with its checks, remedies and evidence."""
|
|
84
|
+
n = tools.latest(source, kind=kind, on=on)
|
|
85
|
+
if json:
|
|
86
|
+
return _dumps(n)
|
|
87
|
+
return "no notices" if n is None else format_notice(n)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@_errors_as_command_errors
|
|
91
|
+
def list_(
|
|
92
|
+
source: str = None,
|
|
93
|
+
*,
|
|
94
|
+
since: str = None,
|
|
95
|
+
kind: str = None,
|
|
96
|
+
q: str = None,
|
|
97
|
+
limit: int = 50,
|
|
98
|
+
json: bool = False,
|
|
99
|
+
on: str = None,
|
|
100
|
+
):
|
|
101
|
+
"""Notices newest first, one line each (SINCE: a duration like 2d, or an ISO time)."""
|
|
102
|
+
hits = tools.list_notices(source, since=since, kind=kind, q=q, limit=limit, on=on)
|
|
103
|
+
if json:
|
|
104
|
+
return _dumps(hits)
|
|
105
|
+
lines = [
|
|
106
|
+
f"{h['id']} {h['kind']:<9} {h['title']}"
|
|
107
|
+
+ ("" if h["delivered"] else " [undelivered]")
|
|
108
|
+
for h in hits
|
|
109
|
+
]
|
|
110
|
+
return "\n".join(lines) or "no notices"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@_errors_as_command_errors
|
|
114
|
+
def show(id: str, *, json: bool = False, on: str = None):
|
|
115
|
+
"""The full notice with this ID."""
|
|
116
|
+
n = tools.show(id, on=on)
|
|
117
|
+
return _dumps(n) if json else format_notice(n)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@_errors_as_command_errors
|
|
121
|
+
def sources(*, json: bool = False, on: str = None):
|
|
122
|
+
"""The sources that have notices."""
|
|
123
|
+
s = tools.sources(on=on)
|
|
124
|
+
return _dumps(s) if json else ("\n".join(s) or "no sources")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
COMMANDS = {"latest": latest, "list": list_, "show": show, "sources": sources}
|
|
128
|
+
|
|
129
|
+
_COMMON = {
|
|
130
|
+
"json": {"help": "print JSON (the agent format)"},
|
|
131
|
+
"on": {"help": "read HOST's history over ssh", "metavar": "HOST"},
|
|
132
|
+
}
|
|
133
|
+
_KIND = {"help": "alert, reminder, resolved, recovered or test", "metavar": "KIND"}
|
|
134
|
+
_CONFIG = {
|
|
135
|
+
"latest": {**_COMMON, "source": {"help": "only this source"}, "kind": _KIND},
|
|
136
|
+
"list": {
|
|
137
|
+
**_COMMON,
|
|
138
|
+
"source": {"help": "only this source"},
|
|
139
|
+
"since": {"help": "a duration (2d, 6h) or an ISO time"},
|
|
140
|
+
"kind": _KIND,
|
|
141
|
+
"q": {"help": "text in the title, body or checks", "metavar": "TEXT"},
|
|
142
|
+
"limit": {"help": "at most this many"},
|
|
143
|
+
},
|
|
144
|
+
"show": {**_COMMON, "id": {"help": "a notice id, as list prints it"}},
|
|
145
|
+
"sources": _COMMON,
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def main(argv=None) -> int:
|
|
150
|
+
"""Run the CLI; returns the exit code."""
|
|
151
|
+
return cw.dispatch(COMMANDS, argv, config=_CONFIG, convention=cw.MODERN)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
if __name__ == "__main__":
|
|
155
|
+
raise SystemExit(main())
|
beaconry/channels.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Delivery channels: callables that take a :class:`~beaconry.model.Notice` and send it.
|
|
2
|
+
|
|
3
|
+
A sender is any ``Callable[[Notice], tuple[bool, str]]``: it returns whether delivery
|
|
4
|
+
worked and, if not, why. It may carry a ``channel`` attribute (its name in the
|
|
5
|
+
history) and a ``secrets()`` method (literal values to scrub from what is recorded, such
|
|
6
|
+
as the ntfy topic).
|
|
7
|
+
|
|
8
|
+
- :func:`ntfy_sender` posts to an ntfy topic with the standard library alone.
|
|
9
|
+
- :func:`correspond_sender` sends through the ``correspond`` package (ntfy, and some 150
|
|
10
|
+
services through Apprise), installed with ``pip install beaconry[correspond]``.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import urllib.request
|
|
17
|
+
from collections.abc import Callable
|
|
18
|
+
|
|
19
|
+
from beaconry.model import Notice
|
|
20
|
+
|
|
21
|
+
Sender = Callable[[Notice], "tuple[bool, str]"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _ascii(s: str) -> str:
|
|
25
|
+
"""HTTP header values are latin-1: keep them ASCII so a header can never fail to encode."""
|
|
26
|
+
return s.encode("ascii", "ignore").decode()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def read_topic(*, topic: str | None = None, topic_file=None) -> str:
|
|
30
|
+
"""The ntfy topic: ``topic``, else ``$NTFY_TOPIC``, else read from ``topic_file``.
|
|
31
|
+
|
|
32
|
+
``topic_file`` holds either a ``NTFY_TOPIC=<topic>`` line (an env file) or the bare
|
|
33
|
+
topic on its first line. Returns ``""`` when none is configured.
|
|
34
|
+
"""
|
|
35
|
+
if topic:
|
|
36
|
+
return topic
|
|
37
|
+
if os.environ.get("NTFY_TOPIC"):
|
|
38
|
+
return os.environ["NTFY_TOPIC"]
|
|
39
|
+
if not topic_file:
|
|
40
|
+
return ""
|
|
41
|
+
try:
|
|
42
|
+
with open(os.path.expanduser(str(topic_file))) as f:
|
|
43
|
+
lines = [
|
|
44
|
+
ln.strip() for ln in f if ln.strip() and not ln.lstrip().startswith("#")
|
|
45
|
+
]
|
|
46
|
+
except OSError:
|
|
47
|
+
return ""
|
|
48
|
+
for ln in lines:
|
|
49
|
+
if ln.startswith("NTFY_TOPIC="):
|
|
50
|
+
return ln.split("=", 1)[1].strip().strip("'\"")
|
|
51
|
+
return lines[0] if lines and "=" not in lines[0] else ""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def ntfy_sender(
|
|
55
|
+
*,
|
|
56
|
+
topic: str | None = None,
|
|
57
|
+
topic_file=None,
|
|
58
|
+
base_url: str | None = None,
|
|
59
|
+
timeout: float = 20,
|
|
60
|
+
) -> Sender:
|
|
61
|
+
"""A sender that POSTs a notice to an ntfy topic.
|
|
62
|
+
|
|
63
|
+
``base_url`` defaults to ``$NTFY_URL``, else ``https://ntfy.sh``. The topic is
|
|
64
|
+
resolved at each send (see :func:`read_topic`), so a topic file edited
|
|
65
|
+
later is picked up. The title, priority and tags travel as ASCII headers (ntfy
|
|
66
|
+
renders emoji from tags); the body is sent as UTF-8.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
base_url = base_url or os.environ.get("NTFY_URL") or "https://ntfy.sh"
|
|
70
|
+
|
|
71
|
+
def topic_now() -> str:
|
|
72
|
+
return read_topic(topic=topic, topic_file=topic_file)
|
|
73
|
+
|
|
74
|
+
def send(notice: Notice) -> tuple[bool, str]:
|
|
75
|
+
t = topic_now()
|
|
76
|
+
if not t:
|
|
77
|
+
return False, "no ntfy topic configured"
|
|
78
|
+
req = urllib.request.Request(
|
|
79
|
+
f"{base_url.rstrip('/')}/{t}",
|
|
80
|
+
data=notice.body.encode(),
|
|
81
|
+
headers={
|
|
82
|
+
"Title": _ascii(notice.title),
|
|
83
|
+
"Priority": notice.priority or "default",
|
|
84
|
+
"Tags": _ascii(",".join(notice.tags)),
|
|
85
|
+
},
|
|
86
|
+
method="POST",
|
|
87
|
+
)
|
|
88
|
+
try:
|
|
89
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
90
|
+
resp.read()
|
|
91
|
+
return True, ""
|
|
92
|
+
except Exception as e: # noqa: BLE001 - any failure is a failed delivery
|
|
93
|
+
return False, f"{type(e).__name__}: {e}"
|
|
94
|
+
|
|
95
|
+
send.channel = "ntfy"
|
|
96
|
+
send.secrets = lambda: (topic_now(),)
|
|
97
|
+
return send
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
#: beaconry's (ntfy-style) priorities, in correspond's vocabulary.
|
|
101
|
+
_CORRESPOND_PRIORITY = {
|
|
102
|
+
"min": "low",
|
|
103
|
+
"low": "low",
|
|
104
|
+
"default": "normal",
|
|
105
|
+
"high": "high",
|
|
106
|
+
"max": "urgent",
|
|
107
|
+
"urgent": "urgent",
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def correspond_sender(ref: str = "ntfy:") -> Sender:
|
|
112
|
+
"""A sender that delivers through ``correspond.send(ref, ...)``.
|
|
113
|
+
|
|
114
|
+
``ref`` is a correspond conversation reference (``"ntfy:"`` for its configured
|
|
115
|
+
topic, an Apprise URL reference, ...). correspond is imported on first send.
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
def send(notice: Notice) -> tuple[bool, str]:
|
|
119
|
+
try:
|
|
120
|
+
import correspond
|
|
121
|
+
except ImportError:
|
|
122
|
+
return False, "correspond is not installed: pip install beaconry[correspond]"
|
|
123
|
+
try:
|
|
124
|
+
r = correspond.send(
|
|
125
|
+
ref,
|
|
126
|
+
notice.body,
|
|
127
|
+
title=notice.title,
|
|
128
|
+
priority=_CORRESPOND_PRIORITY.get(notice.priority, "normal"),
|
|
129
|
+
)
|
|
130
|
+
except Exception as e: # noqa: BLE001
|
|
131
|
+
return False, f"{type(e).__name__}: {e}"
|
|
132
|
+
return bool(r.ok), r.error or ""
|
|
133
|
+
|
|
134
|
+
send.channel = f"correspond:{ref}"
|
|
135
|
+
return send
|
beaconry/evaluate.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""Alert evaluation: from a run of checks and the last state, decide what (if anything) to say.
|
|
2
|
+
|
|
3
|
+
:func:`evaluate` is pure: no clock, no environment, no I/O. It returns a
|
|
4
|
+
:class:`Decision` holding the notice that is due (or ``None``) and the state to persist
|
|
5
|
+
in each outcome: ``on_sent`` if the notice was delivered (or none was due), ``on_failed``
|
|
6
|
+
if its delivery failed. The caller (normally :func:`beaconry.monitor.tick`) delivers and
|
|
7
|
+
picks one.
|
|
8
|
+
|
|
9
|
+
The rules:
|
|
10
|
+
|
|
11
|
+
- **Alert on change.** A failing check is identified by :func:`alert_part` (its
|
|
12
|
+
``cause``, or its status for a volatile measurement, or its rendered value with
|
|
13
|
+
elapsed times masked). The *signature* of a run is a hash of the sorted parts, so it
|
|
14
|
+
names the set of problems, not their order. An unchanged signature is not news.
|
|
15
|
+
- **Reminders with backoff.** An unchanged alert is re-sent as a reminder after
|
|
16
|
+
``renotify_hours``, then after twice that, and so on, capped at ``renotify_max_hours``.
|
|
17
|
+
- **Resolved.** When some alerted checks clear and nothing new broke, a quiet
|
|
18
|
+
"N resolved, M still open" notice; when all clear, "<label> recovered".
|
|
19
|
+
- **Hysteresis.** An alerted check that is ok again is *held* until it has stayed ok for
|
|
20
|
+
``recover_ticks`` runs; a held check keeps its place in the signature, so a check
|
|
21
|
+
flapping around its threshold neither re-alerts nor sends "recovered" each time.
|
|
22
|
+
- **Retry backoff.** A notice whose delivery failed is retried at most every
|
|
23
|
+
``retry_minutes`` while its signature stays the same; a different signature is tried
|
|
24
|
+
at once, so a new problem is never held back by an old one's backoff.
|
|
25
|
+
- **Legacy state.** A one-line ``"<sig> <ts>"`` state (whose signature was the unsorted
|
|
26
|
+
join) describing the same alert is adopted, so upgrading neither re-sends nor forgoes
|
|
27
|
+
hysteresis.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import hashlib
|
|
33
|
+
import json
|
|
34
|
+
import re
|
|
35
|
+
from collections.abc import Iterable, Mapping
|
|
36
|
+
from dataclasses import dataclass
|
|
37
|
+
from datetime import datetime, timezone
|
|
38
|
+
|
|
39
|
+
from beaconry.model import CRIT, OK, Check, Notice, resolve_policy
|
|
40
|
+
|
|
41
|
+
#: An elapsed time or countdown inside a rendered value ("10h59m", "3 min ago",
|
|
42
|
+
#: "12 days left"). Such a value changes every run while the problem stays the same, so
|
|
43
|
+
#: :func:`alert_part` masks it. The explicit seam is ``Check.cause``; this is the guard
|
|
44
|
+
#: for a check that did not set one.
|
|
45
|
+
_ELAPSED = re.compile(
|
|
46
|
+
r"\b\d+(?:\.\d+)?\s*(?:d|h|m|s|min|mins|minutes?|hours?|days?|secs?|seconds?)"
|
|
47
|
+
r"(?:\d+\s*(?:h|m|s))*\b(?:\s+(?:ago|left))?",
|
|
48
|
+
re.IGNORECASE,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def alert_part(c: Check) -> str:
|
|
53
|
+
"""The dedupe identity of a failing check: a change in it is news, nothing else is.
|
|
54
|
+
|
|
55
|
+
``cause`` when the check names one; ``key:status`` for a volatile measurement;
|
|
56
|
+
otherwise the rendered ``label: value`` with any elapsed time masked, so
|
|
57
|
+
"1/5 broken" -> "5/5 broken" is news but "unshipped for 10h59m" -> "for 11h09m"
|
|
58
|
+
is not.
|
|
59
|
+
|
|
60
|
+
>>> alert_part(Check("m", "Prod", "crit", "main unshipped for 10h59m"))
|
|
61
|
+
'Prod: main unshipped for <t>'
|
|
62
|
+
>>> alert_part(Check("c", "Connectors", "crit", "1/5 broken"))
|
|
63
|
+
'Connectors: 1/5 broken'
|
|
64
|
+
>>> alert_part(Check("m", "Prod", "crit", "for 3h", cause="since deploy abc"))
|
|
65
|
+
'm:crit:since deploy abc'
|
|
66
|
+
>>> alert_part(Check("disk", "Disk /", "warn", "85% used", volatile=True))
|
|
67
|
+
'disk:warn'
|
|
68
|
+
"""
|
|
69
|
+
if c.cause:
|
|
70
|
+
return f"{c.key}:{c.status}:{c.cause}"
|
|
71
|
+
if c.volatile:
|
|
72
|
+
return f"{c.key}:{c.status}"
|
|
73
|
+
return f"{c.label}: " + _ELAPSED.sub("<t>", c.value)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def signature(parts: Iterable[str]) -> str:
|
|
77
|
+
"""A short hash naming the SET of ``parts`` (order-independent).
|
|
78
|
+
|
|
79
|
+
>>> signature(["b", "a"]) == signature(["a", "b"])
|
|
80
|
+
True
|
|
81
|
+
>>> len(signature(["a"]))
|
|
82
|
+
16
|
|
83
|
+
"""
|
|
84
|
+
return _hash(sorted(parts))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _hash(parts) -> str:
|
|
88
|
+
return hashlib.sha256("\n".join(parts).encode()).hexdigest()[:16]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def parse_state(raw) -> dict:
|
|
92
|
+
"""An alert state as a dict, from ``None``, a dict, JSON text, or the legacy line.
|
|
93
|
+
|
|
94
|
+
>>> parse_state(None)
|
|
95
|
+
{}
|
|
96
|
+
>>> parse_state('{"sig": "abc", "ts": 5}')
|
|
97
|
+
{'sig': 'abc', 'ts': 5}
|
|
98
|
+
>>> parse_state("abc 5")
|
|
99
|
+
{'sig': 'abc', 'ts': 5, 'legacy': True}
|
|
100
|
+
>>> parse_state("garbage")
|
|
101
|
+
{}
|
|
102
|
+
"""
|
|
103
|
+
if raw is None:
|
|
104
|
+
return {}
|
|
105
|
+
if isinstance(raw, Mapping):
|
|
106
|
+
return dict(raw)
|
|
107
|
+
if isinstance(raw, bytes):
|
|
108
|
+
raw = raw.decode(errors="replace")
|
|
109
|
+
try:
|
|
110
|
+
state = json.loads(raw)
|
|
111
|
+
return dict(state) if isinstance(state, dict) else {}
|
|
112
|
+
except ValueError:
|
|
113
|
+
pass
|
|
114
|
+
try:
|
|
115
|
+
sig, ts = raw.split()
|
|
116
|
+
return {"sig": sig, "ts": int(ts), "legacy": True}
|
|
117
|
+
except ValueError:
|
|
118
|
+
return {}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _int(x, default: int = 0) -> int:
|
|
122
|
+
"""``int(x)``, or ``default`` for a value a hand edit or an old version left behind."""
|
|
123
|
+
try:
|
|
124
|
+
return int(x)
|
|
125
|
+
except (TypeError, ValueError):
|
|
126
|
+
return default
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def iso_utc(ts: float) -> str:
|
|
130
|
+
"""An epoch time as ISO-8601 UTC with a ``Z``.
|
|
131
|
+
|
|
132
|
+
>>> iso_utc(0)
|
|
133
|
+
'1970-01-01T00:00:00Z'
|
|
134
|
+
"""
|
|
135
|
+
return datetime.fromtimestamp(ts, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@dataclass
|
|
139
|
+
class Decision:
|
|
140
|
+
"""What :func:`evaluate` decided: the notice due (or ``None``) and the next state.
|
|
141
|
+
|
|
142
|
+
Persist ``on_sent`` when the notice was delivered or none was due, ``on_failed``
|
|
143
|
+
when delivering it failed (it records the attempt, for the retry backoff).
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
notice: Notice | None
|
|
147
|
+
on_sent: dict
|
|
148
|
+
on_failed: dict
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def evaluate(
|
|
152
|
+
checks: Iterable,
|
|
153
|
+
state=None,
|
|
154
|
+
*,
|
|
155
|
+
now: float,
|
|
156
|
+
policy=None,
|
|
157
|
+
source: str = "",
|
|
158
|
+
label: str | None = None,
|
|
159
|
+
) -> Decision:
|
|
160
|
+
"""Decide what to notify about ``checks``, given the last ``state``, at time ``now``.
|
|
161
|
+
|
|
162
|
+
``checks`` are :class:`~beaconry.model.Check` objects or check dicts; ``state`` is
|
|
163
|
+
what the previous decision said to persist (or ``None``, or a legacy one-line
|
|
164
|
+
state); ``policy`` a :class:`~beaconry.model.Policy` or settings data (see
|
|
165
|
+
:func:`~beaconry.model.resolve_policy`); ``label`` names the source in titles
|
|
166
|
+
(default: ``source``).
|
|
167
|
+
|
|
168
|
+
>>> d = evaluate([Check("disk", "Disk /", "crit", "95% used")], None, now=0, source="box")
|
|
169
|
+
>>> d.notice.title, d.notice.kind, d.on_sent["alerted"]
|
|
170
|
+
('box: 1 issue(s)', 'alert', {'disk': 'Disk /: 95% used'})
|
|
171
|
+
>>> evaluate([Check("disk", "Disk /", "crit", "95% used")], d.on_sent, now=60).notice is None
|
|
172
|
+
True
|
|
173
|
+
"""
|
|
174
|
+
policy = resolve_policy(policy, source)
|
|
175
|
+
label = label or source or "beaconry"
|
|
176
|
+
checks = [Check.from_mapping(c) for c in checks]
|
|
177
|
+
state = parse_state(state)
|
|
178
|
+
now = int(now)
|
|
179
|
+
renotify = policy.renotify_hours * 3600
|
|
180
|
+
renotify_max = max(renotify, policy.renotify_max_hours * 3600)
|
|
181
|
+
recover_ticks = max(1, int(policy.recover_ticks))
|
|
182
|
+
retry_wait = policy.retry_minutes * 60
|
|
183
|
+
|
|
184
|
+
prev_sig = str(state.get("sig", ""))
|
|
185
|
+
prev_ts = _int(state.get("ts"))
|
|
186
|
+
reminders = max(0, _int(state.get("reminders")))
|
|
187
|
+
alerted = state.get("alerted") if isinstance(state.get("alerted"), dict) else {}
|
|
188
|
+
streaks = state.get("ok_streak") if isinstance(state.get("ok_streak"), dict) else {}
|
|
189
|
+
|
|
190
|
+
bad = [c for c in checks if c.status != OK]
|
|
191
|
+
parts = {c.key: alert_part(c) for c in bad}
|
|
192
|
+
ok_keys = {c.key for c in checks if c.status == OK}
|
|
193
|
+
labels = {c.key: c.label for c in checks}
|
|
194
|
+
# Held: alerted, ok now, and not yet ok for long enough. A check that is bad again
|
|
195
|
+
# loses its streak; one that vanished from the run entirely is not held. Streaks are
|
|
196
|
+
# kept for every alerted check (not only held ones) until a delivered notice drops
|
|
197
|
+
# it, so a recovered check cannot fall back into "held" while that notice is retried.
|
|
198
|
+
streaks = {k: _int(streaks.get(k)) + 1 for k in alerted if k in ok_keys}
|
|
199
|
+
held = {k: alerted[k] for k, n in sorted(streaks.items()) if n < recover_ticks}
|
|
200
|
+
sig_parts = list(parts.values()) + [held[k] for k in held if k not in parts]
|
|
201
|
+
sig = signature(sig_parts) if sig_parts else "OK"
|
|
202
|
+
if "legacy" in state and parts:
|
|
203
|
+
# The one-line state's signature was the unsorted join and it kept no per-check
|
|
204
|
+
# record: if it describes this same alert, adopt it.
|
|
205
|
+
if prev_sig == _hash(parts.values()):
|
|
206
|
+
prev_sig, alerted = sig, dict(parts)
|
|
207
|
+
state.update(sig=sig, alerted=alerted)
|
|
208
|
+
state.pop("legacy", None)
|
|
209
|
+
state["ok_streak"] = streaks
|
|
210
|
+
|
|
211
|
+
def unchanged() -> Decision:
|
|
212
|
+
return Decision(None, dict(state), dict(state))
|
|
213
|
+
|
|
214
|
+
def due(kind, title, body, priority, tags, delivered, *, about=()) -> Decision:
|
|
215
|
+
attempt = state.get("attempt") if isinstance(state.get("attempt"), dict) else {}
|
|
216
|
+
if attempt.get("sig") == sig and now - _int(attempt.get("ts")) < retry_wait:
|
|
217
|
+
return unchanged() # backing off after a failed delivery of this same notice
|
|
218
|
+
notice = Notice(
|
|
219
|
+
source=source,
|
|
220
|
+
ts=iso_utc(now),
|
|
221
|
+
kind=kind,
|
|
222
|
+
title=title,
|
|
223
|
+
body=body,
|
|
224
|
+
priority=priority,
|
|
225
|
+
tags=tags,
|
|
226
|
+
checks=[c.to_dict() for c in checks if c.status != OK or c.key in about],
|
|
227
|
+
)
|
|
228
|
+
sent = {**state, **delivered}
|
|
229
|
+
sent.pop("attempt", None)
|
|
230
|
+
# Recorded as delivered only if delivery worked: a network blip must not
|
|
231
|
+
# silence a real alert. Undelivered, a later run retries.
|
|
232
|
+
failed = {**state, "attempt": {"sig": sig, "ts": now}}
|
|
233
|
+
return Decision(notice, sent, failed)
|
|
234
|
+
|
|
235
|
+
if bad:
|
|
236
|
+
body = "\n".join(f"• {c.label}: {c.value}" for c in bad)
|
|
237
|
+
if held:
|
|
238
|
+
body += "\n(recovering: " + ", ".join(labels.get(k, k) for k in held) + ")"
|
|
239
|
+
prio = "high" if any(c.status == CRIT for c in bad) else "default"
|
|
240
|
+
if sig != prev_sig:
|
|
241
|
+
# Resolved: delivered before, gone now (past hysteresis). New: not in the
|
|
242
|
+
# delivered alert in this form. Only-resolved is good news, sent quietly.
|
|
243
|
+
resolved = sorted(k for k in alerted if k not in parts and k not in held)
|
|
244
|
+
new = [k for k, p in parts.items() if alerted.get(k) != p]
|
|
245
|
+
gone = ", ".join(labels.get(k, k) for k in resolved)
|
|
246
|
+
delivered = dict(sig=sig, ts=now, alerted={**held, **parts}, reminders=0)
|
|
247
|
+
if resolved and not new and prev_sig and prev_sig != "OK":
|
|
248
|
+
title = f"{label}: {len(resolved)} resolved, {len(bad)} still open"
|
|
249
|
+
return due(
|
|
250
|
+
"resolved",
|
|
251
|
+
title,
|
|
252
|
+
f"Resolved: {gone}\n{body}",
|
|
253
|
+
"low",
|
|
254
|
+
("white_check_mark",),
|
|
255
|
+
delivered,
|
|
256
|
+
about=resolved,
|
|
257
|
+
)
|
|
258
|
+
if resolved:
|
|
259
|
+
body += f"\n(resolved: {gone})"
|
|
260
|
+
return due(
|
|
261
|
+
"alert",
|
|
262
|
+
f"{label}: {len(bad)} issue(s)",
|
|
263
|
+
body,
|
|
264
|
+
prio,
|
|
265
|
+
("warning",),
|
|
266
|
+
delivered,
|
|
267
|
+
about=resolved,
|
|
268
|
+
)
|
|
269
|
+
if (now - prev_ts) >= min(renotify * 2**reminders, renotify_max):
|
|
270
|
+
title = f"{label}: still {len(bad)} issue(s) (reminder {reminders + 1})"
|
|
271
|
+
return due(
|
|
272
|
+
"reminder",
|
|
273
|
+
title,
|
|
274
|
+
body,
|
|
275
|
+
prio,
|
|
276
|
+
("warning",),
|
|
277
|
+
dict(ts=now, reminders=reminders + 1),
|
|
278
|
+
)
|
|
279
|
+
return unchanged()
|
|
280
|
+
if held:
|
|
281
|
+
return unchanged() # recovering: no "recovered" until the held checks stay ok
|
|
282
|
+
cleared = dict(sig="OK", ts=now, alerted={}, reminders=0)
|
|
283
|
+
if prev_sig and prev_sig != "OK":
|
|
284
|
+
return due(
|
|
285
|
+
"recovered",
|
|
286
|
+
f"{label} recovered",
|
|
287
|
+
"All monitored checks are passing again.",
|
|
288
|
+
"low",
|
|
289
|
+
("white_check_mark",),
|
|
290
|
+
cleared,
|
|
291
|
+
about=set(alerted),
|
|
292
|
+
)
|
|
293
|
+
state.update(cleared)
|
|
294
|
+
return unchanged()
|