@krysoworks/kryso 0.0.0-stage → 2.0.0-rc.1
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.
- package/LICENSE +21 -0
- package/README.md +152 -2
- package/bin/kryso +31 -0
- package/bin/ship-it-status +14 -0
- package/bin/ship-ledger +14 -0
- package/bin/ship-loop +14 -0
- package/bin/ship-pass +14 -0
- package/bin/warden +14 -0
- package/dist/answer.d.ts +38 -0
- package/dist/answer.js +48 -0
- package/dist/bytes.d.ts +5 -0
- package/dist/bytes.js +35 -0
- package/dist/cleanup.d.ts +1 -0
- package/dist/cleanup.js +629 -0
- package/dist/commands.d.ts +48 -0
- package/dist/commands.js +293 -0
- package/dist/completions.d.ts +24 -0
- package/dist/completions.js +239 -0
- package/dist/daemon.d.ts +15 -0
- package/dist/daemon.js +23 -0
- package/dist/diagnose.d.ts +47 -0
- package/dist/diagnose.js +314 -0
- package/dist/doctor.d.ts +1 -0
- package/dist/doctor.js +241 -0
- package/dist/env.d.ts +9 -0
- package/dist/env.js +17 -0
- package/dist/evidence.d.ts +39 -0
- package/dist/evidence.js +327 -0
- package/dist/home.d.ts +3 -0
- package/dist/home.js +27 -0
- package/dist/install.d.ts +59 -0
- package/dist/install.js +137 -0
- package/dist/isolate.d.ts +28 -0
- package/dist/isolate.js +402 -0
- package/dist/leftovers.d.ts +5 -0
- package/dist/leftovers.js +156 -0
- package/dist/machine.d.ts +6 -0
- package/dist/machine.js +185 -0
- package/dist/palette.d.ts +147 -0
- package/dist/palette.js +167 -0
- package/dist/plan.d.ts +1 -0
- package/dist/plan.js +133 -0
- package/dist/proc.d.ts +23 -0
- package/dist/proc.js +23 -0
- package/dist/read.d.ts +1 -0
- package/dist/read.js +297 -0
- package/dist/readiness.d.ts +5 -0
- package/dist/readiness.js +64 -0
- package/dist/remote.d.ts +6 -0
- package/dist/remote.js +85 -0
- package/dist/self-update.d.ts +1 -0
- package/dist/self-update.js +224 -0
- package/dist/semver.d.ts +7 -0
- package/dist/semver.js +42 -0
- package/dist/style.d.ts +71 -0
- package/dist/style.js +187 -0
- package/dist/update.d.ts +47 -0
- package/dist/update.js +190 -0
- package/dist/work.d.ts +25 -0
- package/dist/work.js +449 -0
- package/dist/workflows.d.ts +4 -0
- package/dist/workflows.js +73 -0
- package/docker/entrypoint.sh +44 -0
- package/docker/runner.Dockerfile +39 -0
- package/package.json +65 -4
- package/scripts/install-skills.sh +607 -0
- package/skills/code-review/SKILL.md +231 -0
- package/skills/kryso/SKILL.md +107 -0
- package/skills/kryso/golden/help.rounded.ansi +23 -0
- package/skills/kryso/golden/help.square.ansi +23 -0
- package/skills/kryso/golden/help.txt +23 -0
- package/skills/kryso/golden/table-narrow.json +11 -0
- package/skills/kryso/golden/table-narrow.rounded.ansi +4 -0
- package/skills/kryso/golden/table-narrow.square.ansi +4 -0
- package/skills/kryso/golden/table.ansi +5 -0
- package/skills/kryso/golden/table.json +11 -0
- package/skills/kryso/ledger.sh +2146 -0
- package/skills/kryso/palette.json +57 -0
- package/skills/kryso/reference/resuming.md +30 -0
- package/skills/kryso/reference/routing.md +23 -0
- package/skills/kryso/reference/stage-1-claim.md +79 -0
- package/skills/kryso/reference/stage-2-build.md +133 -0
- package/skills/kryso/reference/stage-3-prove.md +51 -0
- package/skills/kryso/reference/stage-4-pr.md +76 -0
- package/skills/kryso/reference/stage-5-reconcile.md +81 -0
- package/skills/kryso/reference/stage-6-merge-or-park.md +73 -0
- package/skills/kryso/reference/stage-7-close-out.md +62 -0
- package/skills/kryso/reference/terminal.md +7 -0
- package/skills/kryso/ship-it-status.sh +1503 -0
- package/skills/kryso/ui.py +274 -0
- package/skills/kryso/ui.sh +609 -0
- package/skills/kryso-build/SKILL.md +168 -0
- package/skills/kryso-shift/SKILL.md +167 -0
- package/skills/kryso-shift/archive.py +2784 -0
- package/skills/kryso-shift/archive_checker.py +462 -0
- package/skills/kryso-shift/archive_checker_lambda.py +155 -0
- package/skills/kryso-shift/archive_health.py +364 -0
- package/skills/kryso-shift/archive_launchd.py +140 -0
- package/skills/kryso-shift/archive_remote.py +990 -0
- package/skills/kryso-shift/archiving-checker.md +140 -0
- package/skills/kryso-shift/archiving-keep.md +115 -0
- package/skills/kryso-shift/archiving-recovery.md +112 -0
- package/skills/kryso-shift/archiving-remote.md +166 -0
- package/skills/kryso-shift/archiving.md +146 -0
- package/skills/kryso-shift/coverage.schema.json +225 -0
- package/skills/kryso-shift/deadline.sh +254 -0
- package/skills/kryso-shift/feedback.schema.json +35 -0
- package/skills/kryso-shift/feedback.sh +228 -0
- package/skills/kryso-shift/history-manifest.schema.json +331 -0
- package/skills/kryso-shift/keep-after.sh +55 -0
- package/skills/kryso-shift/measure.sh +611 -0
- package/skills/kryso-shift/merge-ready.sh +207 -0
- package/skills/kryso-shift/outcome.schema.json +16 -0
- package/skills/kryso-shift/pass-rules.md +8 -0
- package/skills/kryso-shift/profile.schema.json +42 -0
- package/skills/kryso-shift/reader.sh +692 -0
- package/skills/kryso-shift/reads.sh +151 -0
- package/skills/kryso-shift/reference/allowance.md +21 -0
- package/skills/kryso-shift/reference/driver.md +95 -0
- package/skills/kryso-shift/reference/measuring.md +67 -0
- package/skills/kryso-shift/reference/outputs.md +21 -0
- package/skills/kryso-shift/reference/pass-script.md +115 -0
- package/skills/kryso-shift/reference/reconcile-and-merge.md +55 -0
- package/skills/kryso-shift/reference/second-reader.md +9 -0
- package/skills/kryso-shift/reference/sweeps.md +83 -0
- package/skills/kryso-shift/repair.schema.json +14 -0
- package/skills/kryso-shift/report-template.html +679 -0
- package/skills/kryso-shift/report.py +389 -0
- package/skills/kryso-shift/report_fixture.py +65 -0
- package/skills/kryso-shift/reporting.md +58 -0
- package/skills/kryso-shift/result.sh +91 -0
- package/skills/kryso-shift/runner.sh +1178 -0
- package/skills/kryso-shift/ship-loop.sh +3977 -0
- package/skills/kryso-shift/ship-pass.sh +4987 -0
- package/skills/kryso-shift/steps.jq +19 -0
- package/skills/kryso-shift/workflow.mjs +830 -0
- package/skills/kryso-shift/workflows/default.json +22 -0
- package/skills/kryso-shift/workflows/ralph.json +13 -0
- package/skills/kryso-watch/SKILL.md +100 -0
- package/skills/kryso-watch/answer.schema.json +23 -0
- package/skills/kryso-watch/base-refs.sh +44 -0
- package/skills/kryso-watch/board.sh +58 -0
- package/skills/kryso-watch/reference/config.md +23 -0
- package/skills/kryso-watch/reference/outputs.md +30 -0
- package/skills/kryso-watch/reference/report.md +29 -0
- package/skills/kryso-watch/reference/scheduler.md +32 -0
- package/skills/kryso-watch/reference/settlement.md +29 -0
- package/skills/kryso-watch/reference/shift.md +44 -0
- package/skills/kryso-watch/reference/shim-limits.md +22 -0
- package/skills/kryso-watch/reference/triage.md +26 -0
- package/skills/kryso-watch/schema.jq +40 -0
- package/skills/kryso-watch/settle.schema.json +36 -0
- package/skills/kryso-watch/stage-common.sh +187 -0
- package/skills/kryso-watch/stages/report.sh +525 -0
- package/skills/kryso-watch/stages/settle.sh +722 -0
- package/skills/kryso-watch/stages/shift.sh +466 -0
- package/skills/kryso-watch/stages/triage.sh +379 -0
- package/skills/kryso-watch/tracker.sh +27 -0
- package/skills/kryso-watch/triage.schema.json +77 -0
- package/skills/kryso-watch/warden.launchd.plist +50 -0
- package/skills/kryso-watch/warden.schema.json +98 -0
- package/skills/kryso-watch/warden.sh +1004 -0
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
"""Health snapshots and the checker's judgement of them: which snapshot to trust, what state it shows, when to alert.
|
|
2
|
+
|
|
3
|
+
This module does no I/O of its own. Its callers hand it a store that lists and reads the remote, a journal the
|
|
4
|
+
check records are appended to, and a channel alerts go out on. archive.py passes the local or S3 adapters, and
|
|
5
|
+
the Lambda passes boto3 ones, so `archive.py health`, `archive.py checker run` and the deployed checker select a
|
|
6
|
+
snapshot and judge it with the same code. It imports nothing outside the standard library, so the Lambda's
|
|
7
|
+
package is this file and its handler. See archiving-checker.md.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
from datetime import datetime, timedelta, timezone
|
|
14
|
+
|
|
15
|
+
HEALTH_SCHEMA = "ship-archive-health/1"
|
|
16
|
+
CHECK_SCHEMA = "ship-archive-check/1"
|
|
17
|
+
# The time is to the microsecond, so two health snapshots in one second still sort in the order they were made.
|
|
18
|
+
HEALTH_NAME = re.compile(r"health/(?P<day>\d{4}-\d{2}-\d{2})/(?P<time>(?P<date>\d{8})T\d{12}Z)-(?P<digest>[0-9a-f]{64})\.json")
|
|
19
|
+
TIME = "%Y%m%dT%H%M%S%fZ"
|
|
20
|
+
HEALTH_LOOKBACK_DAYS = 7
|
|
21
|
+
# Why a listed key was passed over when it is not a health snapshot's name at all.
|
|
22
|
+
NOT_A_NAME = "not a health snapshot name"
|
|
23
|
+
|
|
24
|
+
# What a check reports. The four after healthy are each a reason to alert.
|
|
25
|
+
STATES = ("healthy", "stale", "backlog", "unknown", "failed")
|
|
26
|
+
# A keep runs every five minutes, so no new health snapshot for this long means the keep has stopped or cannot
|
|
27
|
+
# publish one, and a snapshot waiting this long in the upload queue means uploads are failing while the keep runs.
|
|
28
|
+
STALE_AFTER = timedelta(minutes=30)
|
|
29
|
+
# Two machines' clocks may disagree by this much. A snapshot published further ahead of the check than this
|
|
30
|
+
# proves nothing about now, so it is not taken as fresh.
|
|
31
|
+
CLOCK_SKEW = timedelta(minutes=5)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def sha256(data):
|
|
35
|
+
return hashlib.sha256(data).hexdigest()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def stamp(when):
|
|
39
|
+
"""A UTC datetime as the archive writes times, to the second."""
|
|
40
|
+
return when.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def parse_time(text):
|
|
44
|
+
"""A time the archive wrote, `YYYY-MM-DDTHH:MM:SSZ`, as a UTC datetime, or None when it is not one."""
|
|
45
|
+
try:
|
|
46
|
+
return datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
|
|
47
|
+
except (TypeError, ValueError):
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# ---- health snapshots -------------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
def health_day(day):
|
|
54
|
+
"""The prefix one UTC day's health snapshots sit under, for a date."""
|
|
55
|
+
return f"health/{day.isoformat()}/"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def health_name(when, digest):
|
|
59
|
+
"""A health snapshot's name for a UTC datetime: its day, its time to the microsecond, and the SHA-256 of its bytes,
|
|
60
|
+
so the name verifies the body."""
|
|
61
|
+
return f"health/{when.date().isoformat()}/{when.strftime(TIME)}-{digest}.json"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def published(name):
|
|
65
|
+
"""The UTC time a health snapshot's name says it was published."""
|
|
66
|
+
return datetime.strptime(HEALTH_NAME.fullmatch(name).group("time"), TIME).replace(tzinfo=timezone.utc)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def newest(store, today, days):
|
|
70
|
+
"""The newest health snapshot whose bytes match its name and parse as one, looking back `days` UTC days.
|
|
71
|
+
|
|
72
|
+
The day after `today` is listed first, because a keep whose clock runs a little ahead publishes there shortly
|
|
73
|
+
before midnight, and `judge` decides whether such a snapshot is within CLOCK_SKEW. Every name newer than the one
|
|
74
|
+
returned, and why it was passed over, is under `rejected`. A store that cannot list or read raises, which is
|
|
75
|
+
never the same answer as finding nothing.
|
|
76
|
+
"""
|
|
77
|
+
rejected = []
|
|
78
|
+
for back in range(-1, days):
|
|
79
|
+
for name in sorted(store.list(health_day(today - timedelta(days=back))), reverse=True):
|
|
80
|
+
found = HEALTH_NAME.fullmatch(name)
|
|
81
|
+
if not found or found.group("day").replace("-", "") != found.group("date"):
|
|
82
|
+
rejected.append({"object": name, "problem": NOT_A_NAME})
|
|
83
|
+
continue
|
|
84
|
+
raw = store.read(name)
|
|
85
|
+
if raw is None or sha256(raw) != found.group("digest"):
|
|
86
|
+
rejected.append({"object": name, "problem": "missing, or its bytes do not match its name"})
|
|
87
|
+
continue
|
|
88
|
+
try:
|
|
89
|
+
doc = json.loads(raw)
|
|
90
|
+
except ValueError:
|
|
91
|
+
doc = None
|
|
92
|
+
if not isinstance(doc, dict) or doc.get("schema") != HEALTH_SCHEMA:
|
|
93
|
+
rejected.append({"object": name, "problem": f"not a {HEALTH_SCHEMA} document"})
|
|
94
|
+
continue
|
|
95
|
+
return {"object": name, "health": doc, "rejected": rejected, "days": max(back, 0) + 1}
|
|
96
|
+
return {"object": None, "health": None, "rejected": rejected, "days": days}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ---- judging one check --------------------------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
def minutes(span):
|
|
102
|
+
return int(span.total_seconds() // 60)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def count(value):
|
|
106
|
+
return len(value) if isinstance(value, list) else 0
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
NO_BACKLOG = {"overdue": False, "pending": None, "pending_bytes": None, "oldest_pending": None, "waiting_minutes": None}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def waiting(doc, now):
|
|
113
|
+
"""The upload queue as a health snapshot reports it, and whether its oldest snapshot is overdue, which is
|
|
114
|
+
queued more than 30 minutes ago and still not verified."""
|
|
115
|
+
oldest = doc.get("oldest_pending") if isinstance(doc.get("oldest_pending"), dict) else None
|
|
116
|
+
queued = parse_time(oldest.get("queued")) if oldest else None
|
|
117
|
+
return {"overdue": bool(queued and doc.get("pending") and now - queued > STALE_AFTER),
|
|
118
|
+
"pending": doc.get("pending"), "pending_bytes": doc.get("pending_bytes"), "oldest_pending": oldest,
|
|
119
|
+
"waiting_minutes": minutes(now - queued) if queued else None}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def judge(found, now):
|
|
123
|
+
"""What one check shows, from what `newest` found or the error that stopped it, at `now`.
|
|
124
|
+
|
|
125
|
+
The state is the first that holds of failed, unknown, stale, backlog and healthy. Staleness and the upload
|
|
126
|
+
queue are judged apart and both reported whatever the state comes out as, because a keep whose health snapshots stop
|
|
127
|
+
arriving and a keep whose archive uploads fail need different fixes. Gaps and the keep's own errors are counted, never judged.
|
|
128
|
+
|
|
129
|
+
A rejected snapshot newer than the trusted one makes the check unknown. A key that is no health snapshot's name
|
|
130
|
+
is listed with the rejected and changes nothing, because it is not a snapshot at all, and it sorts after every
|
|
131
|
+
real name, so counting it would hold the state at unknown for the rest of its day.
|
|
132
|
+
"""
|
|
133
|
+
error = found.get("error")
|
|
134
|
+
rejected = [] if error else found["rejected"]
|
|
135
|
+
untrustworthy = [entry for entry in rejected if entry["problem"] != NOT_A_NAME]
|
|
136
|
+
reasons, health, stale, untrusted, backlog = [], None, False, False, dict(NO_BACKLOG)
|
|
137
|
+
if error:
|
|
138
|
+
reasons.append(f"the check could not read the remote: {error}")
|
|
139
|
+
if untrustworthy:
|
|
140
|
+
untrusted = True
|
|
141
|
+
more = f", and {len(untrustworthy) - 1} more cannot either" if len(untrustworthy) > 1 else ""
|
|
142
|
+
reasons.append(f"the newest health snapshot, {untrustworthy[0]['object']}, cannot be trusted: "
|
|
143
|
+
f"{untrustworthy[0]['problem']}{more}")
|
|
144
|
+
if not error and not found["object"]:
|
|
145
|
+
untrusted = True
|
|
146
|
+
reasons.append(f"the remote holds no health snapshot it can trust from the last {found['days']} days")
|
|
147
|
+
if not error and found["object"]:
|
|
148
|
+
doc, when = found["health"], published(found["object"])
|
|
149
|
+
health = {"object": found["object"], "published": stamp(when), "age_minutes": minutes(now - when),
|
|
150
|
+
"at": doc.get("at"), "host": doc.get("host"), "gaps": count(doc.get("gaps")),
|
|
151
|
+
"errors": count(doc.get("errors"))}
|
|
152
|
+
if when - now > CLOCK_SKEW:
|
|
153
|
+
untrusted = True
|
|
154
|
+
reasons.append(f"the newest health snapshot, {found['object']}, says it was published "
|
|
155
|
+
f"{minutes(when - now)} minutes ahead of the check, so the two clocks disagree")
|
|
156
|
+
stale = now - when > STALE_AFTER
|
|
157
|
+
if stale:
|
|
158
|
+
reasons.append(f"the remote holds no health snapshot from the last {minutes(STALE_AFTER)} minutes: the newest, "
|
|
159
|
+
f"{found['object']}, is {health['age_minutes']} minutes old")
|
|
160
|
+
backlog = waiting(doc, now)
|
|
161
|
+
if backlog["overdue"]:
|
|
162
|
+
reasons.append(f"snapshot {backlog['oldest_pending'].get('snapshot')} has waited {backlog['waiting_minutes']} "
|
|
163
|
+
f"minutes in the upload queue, with {backlog['pending']} waiting in all")
|
|
164
|
+
state = ("failed" if error else "unknown" if untrusted else "stale" if stale
|
|
165
|
+
else "backlog" if backlog["overdue"] else "healthy")
|
|
166
|
+
return {"schema": CHECK_SCHEMA, "at": stamp(now), "state": state, "reasons": reasons, "health": health,
|
|
167
|
+
"stale": stale, "backlog": backlog, "rejected": rejected}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# ---- quiet windows ----------------------------------------------------------------------------------------
|
|
171
|
+
#
|
|
172
|
+
# The Mac is expected to run all the time, because shifts run overnight. A quiet window is a span the owner has
|
|
173
|
+
# said it will not, and inside one a stale state is reported and not alerted on. It explains nothing else: an
|
|
174
|
+
# unreadable remote or an untrustworthy snapshot is not what a Mac being off looks like.
|
|
175
|
+
|
|
176
|
+
QUIET_FIELDS = ("from", "until", "reason")
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def quiet_problems(windows):
|
|
180
|
+
"""What is wrong with a list of quiet windows, as sentences. Empty when every window is usable."""
|
|
181
|
+
if not isinstance(windows, list):
|
|
182
|
+
return ["quiet must be a list of windows, each {\"from\", \"until\", \"reason\"}"]
|
|
183
|
+
problems = []
|
|
184
|
+
for index, window in enumerate(windows):
|
|
185
|
+
where = f"quiet window {index + 1}"
|
|
186
|
+
if not isinstance(window, dict):
|
|
187
|
+
problems.append(f"{where} is not an object with from, until and reason")
|
|
188
|
+
continue
|
|
189
|
+
problems += [f"{where} has {key}, which is not a quiet window setting" for key in sorted(set(window) - set(QUIET_FIELDS))]
|
|
190
|
+
start, end = parse_time(window.get("from")), parse_time(window.get("until"))
|
|
191
|
+
problems += [f"{where} needs {key} as a UTC time like 2026-10-04T12:00:00Z"
|
|
192
|
+
for key, held in (("from", start), ("until", end)) if held is None]
|
|
193
|
+
if start and end and start >= end:
|
|
194
|
+
problems.append(f"{where} ends at {window['until']}, which is not after it starts")
|
|
195
|
+
if not isinstance(window.get("reason"), str) or not window["reason"].strip():
|
|
196
|
+
problems.append(f"{where} needs a reason, which the checker reports while it applies")
|
|
197
|
+
return problems
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def lookback(windows, now):
|
|
201
|
+
"""How many UTC days a check lists: 7, or back to the day before a quiet window began when that window applies
|
|
202
|
+
now or ended within the last 7 days. A Mac that went quiet longer ago than the lookback still reads stale, with
|
|
203
|
+
the window applying, rather than unknown, and stale again once the window ends with it still silent."""
|
|
204
|
+
days = HEALTH_LOOKBACK_DAYS
|
|
205
|
+
for window in windows:
|
|
206
|
+
start, end = parse_time(window["from"]), parse_time(window["until"])
|
|
207
|
+
if start <= now and now - end < timedelta(days=HEALTH_LOOKBACK_DAYS):
|
|
208
|
+
days = max(days, (now.date() - start.date()).days + 2)
|
|
209
|
+
return days
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def quiet_at(windows, now):
|
|
213
|
+
"""The first quiet window `now` falls in, from its start up to but not including its end, or None."""
|
|
214
|
+
for window in windows:
|
|
215
|
+
if parse_time(window["from"]) <= now < parse_time(window["until"]):
|
|
216
|
+
return dict(window)
|
|
217
|
+
return None
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
# ---- alerting -----------------------------------------------------------------------------------------
|
|
221
|
+
|
|
222
|
+
# While a state other than healthy lasts, the owner is reminded of it once a day and not on every check.
|
|
223
|
+
REMIND_AFTER = timedelta(hours=24)
|
|
224
|
+
# What was last announced when nothing ever was: healthy, so a first check that is healthy sends nothing.
|
|
225
|
+
NOTHING_ANNOUNCED = {"state": "healthy", "at": None}
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def announced_by(previous, errors):
|
|
229
|
+
"""The state the owner was last told about, and when, as the previous check record carries it forward."""
|
|
230
|
+
if previous is None:
|
|
231
|
+
return dict(NOTHING_ANNOUNCED)
|
|
232
|
+
held = previous.get("announced") if isinstance(previous, dict) and previous.get("schema") == CHECK_SCHEMA else None
|
|
233
|
+
if isinstance(held, dict) and held.get("state") in STATES and (held.get("at") is None or parse_time(held.get("at"))):
|
|
234
|
+
return {"state": held["state"], "at": held.get("at")}
|
|
235
|
+
errors.append("the last check record does not say what was last announced, so the check takes it as healthy")
|
|
236
|
+
return dict(NOTHING_ANNOUNCED)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def decide(record, announced, now):
|
|
240
|
+
"""The alert one check sends: `change` when its state differs from the one last announced, `reminder` when a
|
|
241
|
+
state other than healthy was last announced a day or more ago, otherwise None. A stale state inside a quiet
|
|
242
|
+
window sends nothing and leaves what was announced alone, so the window's end is when it is news."""
|
|
243
|
+
state = record["state"]
|
|
244
|
+
if state == "stale" and record["quiet"]:
|
|
245
|
+
return None
|
|
246
|
+
if state != announced["state"]:
|
|
247
|
+
return "change"
|
|
248
|
+
if state != "healthy":
|
|
249
|
+
last = parse_time(announced["at"])
|
|
250
|
+
if last is None or now - last >= REMIND_AFTER:
|
|
251
|
+
return "reminder"
|
|
252
|
+
return None
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def compose(record, kind):
|
|
256
|
+
"""An alert's subject and plain-text message for one check record."""
|
|
257
|
+
state = record["state"]
|
|
258
|
+
if kind == "reminder":
|
|
259
|
+
subject = f"Evidence archive still {state}"
|
|
260
|
+
else:
|
|
261
|
+
subject = "Evidence archive healthy again" if state == "healthy" else f"Evidence archive {state}"
|
|
262
|
+
lines = [f"The evidence archive checker found the archive {state} at {record['at']}.", ""]
|
|
263
|
+
lines += [f"- {reason}" for reason in record["reasons"]]
|
|
264
|
+
if record["quiet"]:
|
|
265
|
+
lines.append(f"- A quiet window applies until {record['quiet']['until']}: {record['quiet']['reason']}.")
|
|
266
|
+
health = record["health"]
|
|
267
|
+
if health:
|
|
268
|
+
lines.append(f"- The newest health snapshot it trusts is {health['object']}, published {health['published']} "
|
|
269
|
+
f"by {health.get('host') or 'an unnamed host'}, {health['age_minutes']} minutes before the check.")
|
|
270
|
+
else:
|
|
271
|
+
lines.append("- It found no health snapshot it could trust.")
|
|
272
|
+
lines += ["", "This alert is about the evidence archive alone. It changes no shift's outcome and no pass's delivery."]
|
|
273
|
+
return subject, "\n".join(lines) + "\n"
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def run(store, journal, alerts, now, quiet=()):
|
|
277
|
+
"""One check: judge the newest health snapshot, alert on a change of state or a due reminder, and append the
|
|
278
|
+
record to the journal.
|
|
279
|
+
|
|
280
|
+
A failed alert is recorded on the check, beside the state it was about, and leaves what was last announced as
|
|
281
|
+
it was, so the next check sends it again. The record comes back with `recorded` saying whether the journal took
|
|
282
|
+
it, and the caller decides what an unrecorded check means for its exit.
|
|
283
|
+
"""
|
|
284
|
+
try:
|
|
285
|
+
found = newest(store, now.date(), lookback(quiet, now))
|
|
286
|
+
except Exception as error: # any failure to list or read is a failed check, never an empty one
|
|
287
|
+
found = {"error": str(error) or type(error).__name__}
|
|
288
|
+
record = dict(judge(found, now), quiet=quiet_at(quiet, now))
|
|
289
|
+
errors = []
|
|
290
|
+
try:
|
|
291
|
+
previous = journal.latest(now.date())
|
|
292
|
+
except Exception as error:
|
|
293
|
+
previous = None
|
|
294
|
+
errors.append(f"the check could not read the last check record, so it takes what was last announced as healthy: {error}")
|
|
295
|
+
announced = announced_by(previous, errors)
|
|
296
|
+
kind = decide(record, announced, now)
|
|
297
|
+
alert = {"kind": kind, "status": "none"}
|
|
298
|
+
if kind:
|
|
299
|
+
subject, message = compose(record, kind)
|
|
300
|
+
try:
|
|
301
|
+
alert["id"] = alerts.send({"at": record["at"], "kind": kind, "state": record["state"],
|
|
302
|
+
"subject": subject, "message": message})
|
|
303
|
+
alert["status"] = "sent"
|
|
304
|
+
announced = {"state": record["state"], "at": record["at"]}
|
|
305
|
+
except Exception as error:
|
|
306
|
+
alert.update(status="failed", error=str(error) or type(error).__name__)
|
|
307
|
+
record.update(alert=alert, announced=announced, errors=errors)
|
|
308
|
+
try:
|
|
309
|
+
journal.append(record)
|
|
310
|
+
recorded = True
|
|
311
|
+
except Exception as error:
|
|
312
|
+
recorded = False
|
|
313
|
+
record["errors"] = errors + [f"this check record was not appended to the journal: {error}"]
|
|
314
|
+
return dict(record, recorded=recorded)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def all_clear(record):
|
|
318
|
+
"""Whether a check needs nobody: healthy, recorded, with no failed alert and no error of the checker's own."""
|
|
319
|
+
return (record["state"] == "healthy" and record["recorded"] and record["alert"]["status"] != "failed"
|
|
320
|
+
and not record["errors"])
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
# ---- the journal and the alert channel over a store --------------------------------------------------
|
|
324
|
+
#
|
|
325
|
+
# The deployed checker appends to CloudWatch Logs and alerts through SNS. Against a local remote both are a
|
|
326
|
+
# store's create, list and read, so the journal is append-only for the same reason the remote is: a create never
|
|
327
|
+
# replaces what is there.
|
|
328
|
+
|
|
329
|
+
def record_name(kind, at, body):
|
|
330
|
+
when = parse_time(at)
|
|
331
|
+
return f"{kind}/{when.date().isoformat()}/{when.strftime('%Y%m%dT%H%M%SZ')}-{sha256(body)}.json"
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
class StoreJournal:
|
|
335
|
+
"""Check records as objects in a store, one per check, named by its time and the hash of its bytes."""
|
|
336
|
+
|
|
337
|
+
def __init__(self, store):
|
|
338
|
+
self.store = store
|
|
339
|
+
|
|
340
|
+
def append(self, record):
|
|
341
|
+
body = (json.dumps(record, indent=2, sort_keys=True) + "\n").encode()
|
|
342
|
+
self.store.create(record_name("checks", record["at"], body), body)
|
|
343
|
+
|
|
344
|
+
def latest(self, today):
|
|
345
|
+
"""The newest record from today or yesterday, or None when there is none."""
|
|
346
|
+
for day in (today, today - timedelta(days=1)):
|
|
347
|
+
names = self.store.list(f"checks/{day.isoformat()}/")
|
|
348
|
+
if names:
|
|
349
|
+
raw = self.store.read(max(names))
|
|
350
|
+
return json.loads(raw) if raw is not None else None
|
|
351
|
+
return None
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
class StoreAlerts:
|
|
355
|
+
"""Alerts as objects in a store, standing in for the topic the deployed checker publishes to."""
|
|
356
|
+
|
|
357
|
+
def __init__(self, store):
|
|
358
|
+
self.store = store
|
|
359
|
+
|
|
360
|
+
def send(self, alert):
|
|
361
|
+
body = (json.dumps(alert, indent=2, sort_keys=True) + "\n").encode()
|
|
362
|
+
name = record_name("alerts", alert["at"], body)
|
|
363
|
+
self.store.create(name, body)
|
|
364
|
+
return name
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""The keep's launch agent: its plist, and installing and removing it with launchctl.
|
|
2
|
+
|
|
3
|
+
archive.py is the only caller. It builds the job from a keep configuration, checks the remote before an install, and
|
|
4
|
+
reports the restore check the job carries. This module owns what launchd sees: the label, the plist, which plist at a
|
|
5
|
+
label is a keep's, and the launchctl calls that load and unload it. It never writes or unloads another agent's job.
|
|
6
|
+
See archiving-keep.md.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import plistlib
|
|
11
|
+
import re
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from archive_remote import Refused
|
|
18
|
+
|
|
19
|
+
LABEL = "io.github.krysoworks.kryso-keep"
|
|
20
|
+
# The label before the rename. Installing at the default label first removes a keep job left under it, and removing
|
|
21
|
+
# at the default label removes either, so one Mac never runs two keeps. Read until 3.0.0.
|
|
22
|
+
LABEL_OLD = "com.github.jv-k.ship-archive.keep"
|
|
23
|
+
LABEL_SHAPE = re.compile(r"[A-Za-z0-9][A-Za-z0-9.-]{0,127}")
|
|
24
|
+
# The file name a keep job runs. keep_plist knows a keep's plist by it, so a job is built for no other script.
|
|
25
|
+
SCRIPT = "archive.py"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def plist_path(agents, label):
|
|
29
|
+
return agents / f"{label}.plist"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def domain():
|
|
33
|
+
"""The launchd domain of this user's launch agents."""
|
|
34
|
+
return f"gui/{os.getuid()}"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def old_keep(agents, label):
|
|
38
|
+
"""True when label is the default and a keep job is left under the label before the rename."""
|
|
39
|
+
return label == LABEL and bool(keep_plist(plist_path(agents, LABEL_OLD)))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def job(label, script, config, log, interval):
|
|
43
|
+
"""The launch agent that runs `<script> keep --config <config>` every interval seconds and at login, as a plist dictionary.
|
|
44
|
+
|
|
45
|
+
script must be archive.py, at whatever path, because that is the job keep_plist recognises later.
|
|
46
|
+
"""
|
|
47
|
+
if Path(script).name != SCRIPT:
|
|
48
|
+
raise ValueError(f"{script} is not {SCRIPT}: install and remove would take its job for another agent's")
|
|
49
|
+
return {"Label": label,
|
|
50
|
+
"ProgramArguments": [sys.executable, str(script), "keep", "--config", str(config)],
|
|
51
|
+
"StartInterval": interval, "RunAtLoad": True, "ProcessType": "Background",
|
|
52
|
+
"LowPriorityIO": True, "Nice": 10, "StandardOutPath": str(log), "StandardErrorPath": str(log),
|
|
53
|
+
# launchd starts a job with a bare PATH, which finds neither age nor the aws CLI.
|
|
54
|
+
"EnvironmentVariables": {"PATH": os.environ.get("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")}}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def launchctl(*args):
|
|
58
|
+
command = shutil.which("launchctl")
|
|
59
|
+
if not command:
|
|
60
|
+
raise Refused("launchctl is not installed: launchd jobs are macOS only (install --no-load writes the plist without loading it)")
|
|
61
|
+
return subprocess.run([command, *args], capture_output=True, text=True)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def keep_plist(plist):
|
|
65
|
+
"""Whether the plist at this path is a keep job's: None when nothing is there, True when it runs archive.py keep,
|
|
66
|
+
False for anything else, which is another agent's."""
|
|
67
|
+
if not os.path.lexists(plist):
|
|
68
|
+
return None
|
|
69
|
+
try:
|
|
70
|
+
found = plistlib.loads(plist.read_bytes()) if plist.is_file() and not plist.is_symlink() else None
|
|
71
|
+
except (OSError, ValueError, plistlib.InvalidFileException):
|
|
72
|
+
found = None
|
|
73
|
+
arguments = found.get("ProgramArguments") if isinstance(found, dict) else None
|
|
74
|
+
return (isinstance(arguments, list) and len(arguments) >= 3 and str(arguments[1]).endswith(SCRIPT)
|
|
75
|
+
and arguments[2] == "keep")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def install(agents, label, keep_job, load, write):
|
|
79
|
+
"""Write keep_job's plist at this label through write(path, bytes) and load it, replacing only an earlier keep job there.
|
|
80
|
+
|
|
81
|
+
Another agent's plist at the label, or a job loaded under it with no plist here, is refused with nothing written
|
|
82
|
+
or unloaded, so a mistyped label cannot take another agent's place. The job's log directory is made before the
|
|
83
|
+
plist is written, since launchd does not make it.
|
|
84
|
+
"""
|
|
85
|
+
plist = plist_path(agents, label)
|
|
86
|
+
earlier = keep_plist(plist)
|
|
87
|
+
if earlier is False:
|
|
88
|
+
raise Refused(f"{plist} is not a job that runs archive.py keep, so nothing changed")
|
|
89
|
+
if load and earlier is None and launchctl("print", f"{domain()}/{label}").returncode == 0:
|
|
90
|
+
raise Refused(f"a job is loaded as {label} with no plist at {plist}, so it is not this keep's, "
|
|
91
|
+
"and nothing changed")
|
|
92
|
+
Path(keep_job["StandardOutPath"]).parent.mkdir(parents=True, exist_ok=True)
|
|
93
|
+
# A keep job under the label before the rename would run beside this one, so it goes first. Another agent's
|
|
94
|
+
# plist there is left alone, and with --no-load nothing is unloaded.
|
|
95
|
+
replaced = None
|
|
96
|
+
if load and old_keep(agents, label):
|
|
97
|
+
replaced = remove_one(agents, LABEL_OLD)
|
|
98
|
+
write(plist, plistlib.dumps(keep_job))
|
|
99
|
+
if load:
|
|
100
|
+
if earlier:
|
|
101
|
+
launchctl("bootout", f"{domain()}/{label}")
|
|
102
|
+
done = launchctl("bootstrap", domain(), str(plist))
|
|
103
|
+
if done.returncode != 0:
|
|
104
|
+
raise Refused(f"launchctl could not load {plist}: {done.stderr.strip() or f'exit {done.returncode}'}. "
|
|
105
|
+
"The plist is on disk, and `launchd remove` takes it away")
|
|
106
|
+
result = {"label": label, "plist": str(plist), "loaded": load}
|
|
107
|
+
if replaced:
|
|
108
|
+
result["replaced"] = replaced
|
|
109
|
+
return result
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def remove(agents, label):
|
|
113
|
+
"""Unload this label's job and delete its plist, only when the plist is a keep job's.
|
|
114
|
+
|
|
115
|
+
A plist that is not one is refused and left as it was. With no plist at the label nothing is unloaded, because
|
|
116
|
+
nothing says the job loaded under it is a keep. At the default label, a keep job under the label before the rename
|
|
117
|
+
is removed too, and the result names it under `old`.
|
|
118
|
+
"""
|
|
119
|
+
result = remove_one(agents, label)
|
|
120
|
+
if old_keep(agents, label):
|
|
121
|
+
result["old"] = remove_one(agents, LABEL_OLD)
|
|
122
|
+
return result
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def remove_one(agents, label):
|
|
126
|
+
"""Unload and delete one label's keep job, without looking at the label before the rename. remove calls it for each."""
|
|
127
|
+
plist = plist_path(agents, label)
|
|
128
|
+
found = keep_plist(plist)
|
|
129
|
+
if found is False:
|
|
130
|
+
raise Refused(f"{plist} is not a job that runs archive.py keep, so nothing changed")
|
|
131
|
+
if found is None:
|
|
132
|
+
return {"label": label, "plist": str(plist), "unloaded": False, "removed": False}
|
|
133
|
+
service = f"{domain()}/{label}"
|
|
134
|
+
done = launchctl("bootout", service)
|
|
135
|
+
# The plist is what lets a later remove act, so it stays while the job may still run.
|
|
136
|
+
if done.returncode != 0 and launchctl("print", service).returncode == 0:
|
|
137
|
+
raise Refused(f"launchctl could not unload {label}, which is still loaded: "
|
|
138
|
+
f"{done.stderr.strip() or f'exit {done.returncode}'}. The plist stays, so `launchd remove` can try again")
|
|
139
|
+
plist.unlink()
|
|
140
|
+
return {"label": label, "plist": str(plist), "unloaded": done.returncode == 0, "removed": True}
|