Compare commits
336
Commits
f7c39c1700
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b3ab7fbd1a | ||
|
|
440711b4e4 | ||
|
|
10df99b89f | ||
|
|
c5acb91a44 | ||
|
|
c7e4ec9b5e | ||
|
|
3928c3db28 | ||
|
|
f628cb5082 | ||
|
|
591195fadd | ||
|
|
ae07ed46cd | ||
|
|
ee3b05edd0 | ||
|
|
7daf3d24a7 | ||
|
|
fdc0e29400 | ||
|
|
fcf73479c2 | ||
|
|
95ed6314cc | ||
|
|
df0990f3aa | ||
|
|
8747744b48 | ||
|
|
a9189c9dc4 | ||
|
|
3dbb68c163 | ||
|
|
844f19f11e | ||
|
|
da060d7e7f | ||
|
|
27360d6abe | ||
|
|
64b99b74e3 | ||
|
|
5c336d828c | ||
|
|
13e34d4ed4 | ||
|
|
37644458c7 | ||
|
|
c4b6844d34 | ||
|
|
a90b62323f | ||
|
|
94049a7200 | ||
|
|
b69e90bdad | ||
|
|
a28db2d17f | ||
|
|
2a0a17a760 | ||
|
|
99fac06aa7 | ||
|
|
6077ac0083 | ||
|
|
5b3b541602 | ||
|
|
c7bb776e00 | ||
|
|
652a690e5d | ||
|
|
6c72e3ff34 | ||
|
|
fd75c7c717 | ||
|
|
e3fce09d96 | ||
|
|
a815b37fbd | ||
|
|
20c5877056 | ||
|
|
eed23e7594 | ||
|
|
e33cffaee1 | ||
|
|
342a394bff | ||
|
|
ed3927f03a | ||
|
|
5ba1b86293 | ||
|
|
b1b9be3a8e | ||
|
|
710ceace12 | ||
|
|
9b5bb0a9a6 | ||
|
|
e01eb64b25 | ||
|
|
37f7e40b18 | ||
|
|
90a2530689 | ||
|
|
5d07c4e923 | ||
|
|
a3ed63ee9a | ||
|
|
a1c65b3d81 | ||
|
|
2560cf1779 | ||
|
|
cccb9aee84 | ||
|
|
f24233c829 | ||
|
|
106325de43 | ||
|
|
b156e4526a | ||
|
|
dfd0f8ec53 | ||
|
|
1170b48e59 | ||
|
|
7e15a374b2 | ||
|
|
e333477b11 | ||
|
|
5bd03ad152 | ||
|
|
20cf4bccfd | ||
|
|
5ce54a5076 | ||
|
|
6bfb784c4d | ||
|
|
26191911c4 | ||
|
|
3d711ee611 | ||
|
|
0a59044105 | ||
|
|
9c1dfdd71f | ||
|
|
fbec5cb499 | ||
|
|
7ea942a118 | ||
|
|
838c834169 | ||
|
|
b5863a96eb | ||
|
|
a79a292d72 | ||
|
|
fe9837708a | ||
|
|
e2a976198d | ||
|
|
935e624f10 | ||
|
|
3a1f09d29f | ||
|
|
1ee0353dbd | ||
|
|
35232de80d | ||
|
|
2149a13378 | ||
|
|
7720439440 | ||
|
|
e8d2151a77 | ||
|
|
1f8295918e | ||
|
|
1f9c863f79 | ||
|
|
bd9f4f7b74 | ||
|
|
2d71270858 | ||
|
|
b680db85cb | ||
|
|
02daebe9c5 | ||
|
|
e1613aea8d | ||
|
|
c9b4b82dc7 | ||
|
|
518a13592d | ||
|
|
062f9b41d9 | ||
|
|
bb2809dc68 | ||
|
|
2449223f10 | ||
|
|
b01bb4b88d | ||
|
|
321df1f87a | ||
|
|
046b808792 | ||
|
|
bddc477e22 | ||
|
|
42cda07b42 | ||
|
|
ed1011b088 | ||
|
|
60e487db51 | ||
|
|
a9c1997fbc | ||
|
|
277e99839d | ||
|
|
63dcccfeec | ||
|
|
32e61d5d1d | ||
|
|
caaa86eb3c | ||
|
|
23f77f93ba | ||
|
|
1babfe94f6 | ||
|
|
9d9e4041c9 | ||
|
|
943c517550 | ||
|
|
912e59210d | ||
|
|
66a69d4954 | ||
|
|
df78b6caae | ||
|
|
ae394670c1 | ||
|
|
03c0a693b8 | ||
|
|
d5f88a2182 | ||
|
|
6a17c95815 | ||
|
|
cbc944c3c0 | ||
|
|
fc5a20f40a | ||
|
|
add310c80a | ||
|
|
08fa440d04 | ||
|
|
7900a32695 | ||
|
|
1de8a559ed | ||
|
|
f0abdd0eda | ||
|
|
ba22f9b2d9 | ||
|
|
5776d54901 | ||
|
|
28b05d6d68 | ||
|
|
8c1e290f63 | ||
|
|
37b79caad9 | ||
|
|
d582feb245 | ||
|
|
7848d4aaac | ||
|
|
5929b8e345 | ||
|
|
8f5bea0148 | ||
|
|
01c967e49e | ||
|
|
7ca59e2de3 | ||
|
|
aa9e09e817 | ||
|
|
93fb251ea9 | ||
|
|
ae2bfb2f7a | ||
|
|
a03c25aa1f | ||
|
|
c4b3b0a039 | ||
|
|
15ea002458 | ||
|
|
db980ff2cc | ||
|
|
546eef37bd | ||
|
|
e1a2abf1e3 | ||
|
|
a6fa3c01d2 | ||
|
|
c809dd3bc6 | ||
|
|
a741bc1d0f | ||
|
|
601bdba253 | ||
|
|
9bdd8f8fe8 | ||
|
|
ba4a6f060b | ||
|
|
8ae9178138 | ||
|
|
772ef36f5f | ||
|
|
615940de35 | ||
|
|
6c6bd87664 | ||
|
|
03ab121b25 | ||
|
|
2fe634141f | ||
|
|
5d67041d6d | ||
|
|
e30091bf27 | ||
|
|
99f9117296 | ||
|
|
09ac87a843 | ||
|
|
36c4aa4e69 | ||
|
|
24d937d6e4 | ||
|
|
6d90374f63 | ||
|
|
71fbef6bbe | ||
|
|
0c6ce9500c | ||
|
|
a4c0d546e5 | ||
|
|
67a4b452e2 | ||
|
|
8f029aa70b | ||
|
|
411d7761d9 | ||
|
|
e3bb775ac5 | ||
|
|
3e8d027677 | ||
|
|
334df7db12 | ||
|
|
30956aabd2 | ||
|
|
3f0127778c | ||
|
|
55868cb3e0 | ||
|
|
85d60a1930 | ||
|
|
68af0e97f2 | ||
|
|
88aa65d595 | ||
|
|
6ed223886d | ||
|
|
94f44931dd | ||
|
|
7d41c2973c | ||
|
|
7600e6a8b7 | ||
|
|
b69585789a | ||
|
|
f75b3aa778 | ||
|
|
00a0d91976 | ||
|
|
8587198781 | ||
|
|
fbcc3cf042 | ||
|
|
29a3ce8cf2 | ||
|
|
e9d0d723c1 | ||
|
|
52619e89bd | ||
|
|
fc77fcb89b | ||
|
|
f037be7a6a | ||
|
|
8fe46a1313 | ||
|
|
7e791d9b5d | ||
|
|
c02c9d833a | ||
|
|
1296e7aa46 | ||
|
|
f30a80841e | ||
|
|
39bf56298d | ||
|
|
0f82eba7c6 | ||
|
|
7adbbb17c0 | ||
|
|
d170a2aecf | ||
|
|
8d44416610 | ||
|
|
36da4089ca | ||
|
|
a43d0423d5 | ||
|
|
123d2d553f | ||
|
|
a86c864b06 | ||
|
|
e7b64af1f0 | ||
|
|
0626b9fc8a | ||
|
|
c6a567122e | ||
|
|
4261a38bf0 | ||
|
|
f9151f0875 | ||
|
|
ec438479e2 | ||
|
|
8c7aa10a6e | ||
|
|
9e68e526e9 | ||
|
|
02252556b3 | ||
|
|
f908eee2a3 | ||
|
|
006ceab58a | ||
|
|
48d8674876 | ||
|
|
7f3e58ff0a | ||
|
|
9cc7ffcf3b | ||
|
|
83392064ae | ||
|
|
db52f5a4cf | ||
|
|
fe0228c877 | ||
|
|
e66d4669d6 | ||
|
|
85f65c70d8 | ||
|
|
97c992ad44 | ||
|
|
17863fe8bc | ||
|
|
e209a8d724 | ||
|
|
cac92a407e | ||
|
|
f327bc53a9 | ||
|
|
372d6e5994 | ||
|
|
37ffa3beb5 | ||
|
|
a09cab124a | ||
|
|
f580d88a14 | ||
|
|
78c894234c | ||
|
|
331be17e1e | ||
|
|
8bc7ec54cd | ||
|
|
9b95e8e09b | ||
|
|
3b85a0c29a | ||
|
|
8d862e4e69 | ||
|
|
acbbf4b305 | ||
|
|
e24430cce5 | ||
|
|
201f936e9a | ||
|
|
1b2f74c52f | ||
|
|
7626a28de3 | ||
|
|
402fa41e45 | ||
|
|
462196e29b | ||
|
|
68294ecb6f | ||
|
|
faef8f8a91 | ||
|
|
fd28d70bff | ||
|
|
dcd89364a4 | ||
|
|
fc6466a50a | ||
|
|
9e5b88146e | ||
|
|
c255195e37 | ||
|
|
1cb43a21a2 | ||
|
|
b3a879b50e | ||
|
|
ec9b997151 | ||
|
|
13eeb484ab | ||
|
|
d7bfdccf57 | ||
|
|
3f84f82c3d | ||
|
|
d3e17e9b2e | ||
|
|
e06680b797 | ||
|
|
63441f0a69 | ||
|
|
740339567a | ||
|
|
1040cfe225 | ||
|
|
fcd9f09927 | ||
|
|
423b6d3404 | ||
|
|
e37e9b50c6 | ||
|
|
d5f2e47ea1 | ||
|
|
05e129267a | ||
|
|
a40729a698 | ||
|
|
a0370b4ed8 | ||
|
|
75b3b39254 | ||
|
|
6d07ca2be4 | ||
|
|
4d3a0246df | ||
|
|
29bebbb937 | ||
|
|
431da7ebbc | ||
|
|
191836946b | ||
|
|
e2392935a3 | ||
|
|
a3e85e5a40 | ||
|
|
9acc3adb96 | ||
|
|
0629c16a4b | ||
|
|
1de22a166a | ||
|
|
3d6ba2852f | ||
|
|
f65ace0ca6 | ||
|
|
5e7522e023 | ||
|
|
0b1b8d3445 | ||
|
|
66aee8939b | ||
|
|
ce2e31f4b2 | ||
|
|
5b8656974b | ||
|
|
9c945688c0 | ||
|
|
9d2d62831a | ||
|
|
d720495cd5 | ||
|
|
d8c2634472 | ||
|
|
31242786af | ||
|
|
36088fd82e | ||
|
|
871d05b84d | ||
|
|
c393d8529a | ||
|
|
2d63714eca | ||
|
|
13bda270c3 | ||
|
|
ff4a99a0ab | ||
|
|
bee2c2d815 | ||
|
|
c67b26be28 | ||
|
|
4c3c2037fd | ||
|
|
2fc314d491 | ||
|
|
0a960ba58d | ||
|
|
7044b11804 | ||
|
|
2e5ef7e410 | ||
|
|
e4774e6a06 | ||
|
|
0f2eab7a3e | ||
|
|
ff1758a21c | ||
|
|
84d6ef706d | ||
|
|
ef199c5705 | ||
|
|
c4f4019721 | ||
|
|
d7efa7b54e | ||
|
|
ca89e70d53 | ||
|
|
b05be0ac11 | ||
|
|
b36a85ac04 | ||
|
|
1991c742a3 | ||
|
|
4347983a72 | ||
|
|
05a447ef02 | ||
|
|
28a5203d01 | ||
|
|
6fac245d24 | ||
|
|
33c397380e | ||
|
|
034a2b7363 | ||
|
|
daeed27223 | ||
|
|
8ce496f124 | ||
|
|
391967bcf1 | ||
|
|
074ddda352 | ||
|
|
7b8216abac | ||
|
|
d15ad105be | ||
|
|
9271f33359 |
No files matched your search
+13
-11
@@ -6,17 +6,19 @@ paths: ["controller/**/*.go", "controller/**/*.html", "controller/**/*.css", "co
|
|||||||
|
|
||||||
## The ONE entry point
|
## The ONE entry point
|
||||||
|
|
||||||
**Run `python3 controller/scripts/controller_gates.py` (from `controller/`) after ANY change in this
|
**Run `python3 scripts/controller_gates.py` from `controller/` (or `python3
|
||||||
repo.** It runs the local gates — `template_id_gate`, `emoji_gate`, `native_confirm_gate`,
|
controller/scripts/controller_gates.py` from the repo root) after ANY change in this repo.** It runs
|
||||||
`offbox_rename_gate`, `app_row_dedup_gate`, `mojibake_gate`, `docker_run_volume_path_gate`,
|
every gate in the runner's `GATES` table, the shared `reuse_refs_check`, `instructions_gate` and
|
||||||
`secret_in_markup_gate`, `retrieval_promise_gate`, `debug_route_gate` — plus `reuse_refs_check`,
|
`observations_gate` among them, streaming each gate's own output and exiting non-zero if any fails;
|
||||||
`instructions_gate` and `observations_gate` on the repo root, streaming each gate's own output and
|
one, `golden-notice`, is ADVISORY and never refuses. **The `GATES` table is the list; this sentence is a
|
||||||
exiting non-zero if any fails. **The runner's `GATES` table is the list; this sentence is a pointer to
|
pointer to it, not a second copy** — it drifted twice (it said "seven" while nine were registered, then
|
||||||
it, not a second copy** — it has already drifted once (it said "seven" while nine were registered).
|
named ten local gates while fourteen were).
|
||||||
|
|
||||||
- `--fast` selects the gates that touch no network and no container runtime; today that is all of them.
|
- `--fast` selects the gates that touch no network and no container runtime; today that is all of them
|
||||||
|
except `gate-decoys` (the decoy suite, ~22 s, edits real files in this tree for a moment; R-1116), which
|
||||||
|
runs in the full run only — so the hook and CI do not run it.
|
||||||
- **A missing gate script is a FAILURE, never a skip.**
|
- **A missing gate script is a FAILURE, never a skip.**
|
||||||
- **The shared `reuse_refs_check.py` and `instructions_gate.py` live in `felhom.eu/scripts/` and are
|
- **The shared `reuse_refs_check.py`, `instructions_gate.py` and `observations_gate.py` live in `felhom.eu/scripts/` and are
|
||||||
never copied here** — a copy would recreate the drift they detect; an absent sibling clone FAILS.
|
never copied here** — a copy would recreate the drift they detect; an absent sibling clone FAILS.
|
||||||
- **The pre-push hook** (`.githooks/pre-push`) runs it with `--fast` and refuses a failing push. It is
|
- **The pre-push hook** (`.githooks/pre-push`) runs it with `--fast` and refuses a failing push. It is
|
||||||
per-clone — switch it on once with `git config core.hooksPath .githooks`, and a manual run WARNS
|
per-clone — switch it on once with `git config core.hooksPath .githooks`, and a manual run WARNS
|
||||||
@@ -59,7 +61,7 @@ fast, and wrong.
|
|||||||
|
|
||||||
**A decoy is the LABEL without the FACT** — a directory with the right name and no bake log, a
|
**A decoy is the LABEL without the FACT** — a directory with the right name and no bake log, a
|
||||||
handler case that exists only in a comment, a note whose prose mentions the marker it lacks. Write
|
handler case that exists only in a comment, a note whose prose mentions the marker it lacks. Write
|
||||||
one for every new gate, run it, and watch it convict. `scripts/decoy_coverage_gate.py` refuses a gate
|
one for every new gate, run it, and watch it convict. `felhom.eu/scripts/decoy_coverage_gate.py` (run by felhom.eu's `repo_gates.py`, for all four repos) refuses a gate
|
||||||
registered without one, or without a named exemption carrying its row.
|
registered without one, or without a named exemption carrying its row.
|
||||||
|
|
||||||
**Earned by five instances, every one found by accident:** R-410, R-400, R-378, R-419, R-94. The
|
**Earned by five instances, every one found by accident:** R-410, R-400, R-378, R-419, R-94. The
|
||||||
@@ -75,4 +77,4 @@ green and correct today, blind the moment anyone adds a subdirectory. Prefer `os
|
|||||||
glob over a hand-maintained list of files.
|
glob over a hand-maintained list of files.
|
||||||
|
|
||||||
**A decoy nobody would write proves nothing** — say the gate is sound and move on. Five of mine were
|
**A decoy nobody would write proves nothing** — say the gate is sound and move on. Five of mine were
|
||||||
withdrawn as illegitimate and are named in `documentation/audits/AUDIT-gate-decoys-2026-09-01.md`.
|
withdrawn as illegitimate and are named in `felhom.eu/documentation/audits/AUDIT-gate-decoys-2026-09-01.md`.
|
||||||
@@ -6,7 +6,8 @@ unconditional: true
|
|||||||
> Goal sessions, nightly sessions, "work the register" sessions. **A session that starts from
|
> Goal sessions, nightly sessions, "work the register" sessions. **A session that starts from
|
||||||
> `/goal` or a standing brief inherits these rules exactly as it inherits the gates.** They are the
|
> `/goal` or a standing brief inherits these rules exactly as it inherits the gates.** They are the
|
||||||
> part of `PROMPT-TEMPLATE.md` that a task file used to carry and a goal does not. Same wording lives
|
> part of `PROMPT-TEMPLATE.md` that a task file used to carry and a goal does not. Same wording lives
|
||||||
> in all three repos' `.claude/rules/`; change it in all three or in none.
|
> in `felhom.eu`, `felhom-controller`, `felhom-agent` and `app-catalog-felhom.eu` `.claude/rules/`, and in the workspace
|
||||||
|
> root's unversioned `.claude/rules/`; change all five or none.
|
||||||
|
|
||||||
## 1. What you may pick up on your own
|
## 1. What you may pick up on your own
|
||||||
|
|
||||||
@@ -22,7 +23,8 @@ unconditional: true
|
|||||||
customer data; anything that changes a promise the product makes to a customer; anything that
|
customer data; anything that changes a promise the product makes to a customer; anything that
|
||||||
reverses a documented design decision (`documentation/architecture/` — a design decision is not a
|
reverses a documented design decision (`documentation/architecture/` — a design decision is not a
|
||||||
defect, R-370); anything on DooPlex or ep0; baking or vouching a golden; promoting a
|
defect, R-370); anything on DooPlex or ep0; baking or vouching a golden; promoting a
|
||||||
catalog version; a new external dependency.
|
catalog version; a new external dependency; **a hub image build or hub deploy in a session the operator does not
|
||||||
|
attend** (operator ruling 2026-10-07, `09` §3 decision 162).
|
||||||
|
|
||||||
## 2. When you may decide instead of ask (operator grant, 2026-09-14)
|
## 2. When you may decide instead of ask (operator grant, 2026-09-14)
|
||||||
|
|
||||||
@@ -42,13 +44,28 @@ it **first** in the morning note. A decision you cannot write in that shape is o
|
|||||||
Throwaway apps only; the standing apps and `bentopdf` stay.
|
Throwaway apps only; the standing apps and `bentopdf` stay.
|
||||||
5. **Evidence off the machine at the end of each phase**, before any revert (R-320).
|
5. **Evidence off the machine at the end of each phase**, before any revert (R-320).
|
||||||
6. **One release per repo per session**, with a CHANGELOG entry (controller: with its `MinAgent`
|
6. **One release per repo per session**, with a CHANGELOG entry (controller: with its `MinAgent`
|
||||||
line), REPORT overwritten, floor raised to deliver it. **No golden unless a drill or fresh install
|
line) and REPORT overwritten. **A controller release needs no golden** (operator ruling 2026-10-15
|
||||||
needs one** (the waiver, R-468). **No `--no-verify`.**
|
11:26, `09` §3 decision 250; decision 7 stands): push the image only when it is ready for EVERY box (the
|
||||||
|
household's update button offers the highest tag); raise the floor, MinAgent declared, only after it ran
|
||||||
|
on Tester 1, demo-hp and demo-felhom through the normal update path and the box walk's checks are green
|
||||||
|
on all three — not at night unless the night brief says so. **Agent releases still stop for the
|
||||||
|
operator's vouch.** The golden is baked weekly and vouched by the operator; CC never vouches. **No `--no-verify`.**
|
||||||
|
**A version number is pushed once** — `felhom-controller/controller/build.sh` now refuses a second
|
||||||
|
push of a tag that exists, and a registry it cannot reach is a refusal too. This is a FACT about
|
||||||
|
what the build does, not a new rule: a fix for something already pushed is the next patch version,
|
||||||
|
and a box on a bad image is moved by the normal update path, never by re-tagging. Earned on
|
||||||
|
2026-10-15, when 0.315.0 was pushed three times from three different commits and a cache kept
|
||||||
|
serving the first one (`09-update-architecture.md` §0).
|
||||||
7. **An enumerated gap becomes a row in the same session — or, if it is small, is fixed in it** (the size rule).
|
7. **An enumerated gap becomes a row in the same session — or, if it is small, is fixed in it** (the size rule).
|
||||||
Prose is not a record.
|
Prose is not a record.
|
||||||
8. **Hungarian text is searched with ASCII fragments**, with a positive and a negative control.
|
8. **Hungarian text is searched with ASCII fragments**, with a positive and a negative control.
|
||||||
9. **Never leave a half-state.** If time runs out, revert to clean and say what was reverted.
|
9. **Never leave a half-state.** If time runs out, revert to clean and say what was reverted.
|
||||||
10. **Teardown, three layers, stated** — machine, host, hub — or "provisioned nothing".
|
10. **Teardown, three layers, stated** — machine, host, hub — or "provisioned nothing".
|
||||||
|
11. **Every helper prompt carries the brief's fences in full** (operator ruling 2026-10-07). A helper session (a
|
||||||
|
subagent, a fork, a workflow agent) gets the brief's fence list word for word — every protected machine, every
|
||||||
|
„no", every delivery and Docker limit — not a summary and not „the usual fences". Earned on 2026-10-06 night: two
|
||||||
|
helpers whose prompts carried only part of the fences ran `docker volume prune` on the bench and a Docker-using
|
||||||
|
gate on DooPlex.
|
||||||
|
|
||||||
## 4. The morning note
|
## 4. The morning note
|
||||||
|
|
||||||
@@ -56,3 +73,29 @@ One screen, plain language, in this order: **decisions you took** (§2) first; w
|
|||||||
what broke and whether you fixed it; rows opened and closed with the register size before and after;
|
what broke and whether you fixed it; rows opened and closed with the register size before and after;
|
||||||
what needs the operator, each with what happens if they do nothing. No file paths, no function
|
what needs the operator, each with what happens if they do nothing. No file paths, no function
|
||||||
names, no row numbers as the subject of a sentence.
|
names, no row numbers as the subject of a sentence.
|
||||||
|
|
||||||
|
## 5. Instruction files
|
||||||
|
|
||||||
|
**Instruction files (`CLAUDE.md`, `.claude/rules/*`) are kept true by the session that finds them wrong**
|
||||||
|
(operator ruling 2026-10-06, `09` §3 decision 150). A session MAY, without asking: correct a stale fact (a command, a
|
||||||
|
count, a version, a path, a description of what a gate does), add a fact it proved, and remove a reference to something
|
||||||
|
that no longer exists. Each edit is named in the report (file, line, before, after, why). A session MAY NOT, without the
|
||||||
|
operator's word: loosen a safety rule, a fence, a „never", a protected machine, a secret rule, or a review step; or
|
||||||
|
remove a rule. When in doubt, it is a rule change, and it goes to the operator. If Claude Code's own permission check
|
||||||
|
asks before such an edit, wait for the operator's click; if it refuses, record that and file the exact line.
|
||||||
|
|
||||||
|
## 6. The system poster stays true
|
||||||
|
|
||||||
|
**A session that changes a fact listed in `architecture/felhom-system-poster.facts.md` (a machine, a
|
||||||
|
role, a traffic path, a backup tier, a time, a retention, a key, a known gap) updates that file in
|
||||||
|
the same commit.** If the change is text only, it also edits the matching text in
|
||||||
|
`felhom-system-poster.html`. If it needs a new drawing, it adds the line
|
||||||
|
**"System poster needs a refresh: <what changed>"** to `STATUS.md`'s "waiting on the operator" list.
|
||||||
|
**The session report names which of the three it did.**
|
||||||
|
|
||||||
|
Why the three-way split: the poster is a drawing made in Claude Design, and **nothing in this
|
||||||
|
repository renders it** — unlike `where-felhom-stands.html`, which has `render_stands.py`. So the
|
||||||
|
facts file is the source of truth and the drawing trails it. `scripts/poster_facts_gate.py` warns
|
||||||
|
when the facts file has a newer commit than the poster; it **never fails a push**, because a refresh
|
||||||
|
needs the operator and another tool, and a gate nobody can clear is a gate people learn to route
|
||||||
|
around.
|
||||||
@@ -16,7 +16,16 @@
|
|||||||
# A failing run must reach a person — a detector nobody hears is the defect R-29 filed, rebuilt one
|
# A failing run must reach a person — a detector nobody hears is the defect R-29 filed, rebuilt one
|
||||||
# layer up. That is the last step, and it runs ONLY on failure.
|
# layer up. That is the last step, and it runs ONLY on failure.
|
||||||
name: gates
|
name: gates
|
||||||
on: [push]
|
# R-1129: `workflow_dispatch` is the manual PROOF that the failure mail can be sent. A push run is
|
||||||
|
# unchanged by it: the proof step below is skipped on a push, and `force_alarm` is then empty.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
force_alarm:
|
||||||
|
description: "Fail this run on purpose so the alarm step sends its real mail (a proof, not a gate result)"
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
gates:
|
gates:
|
||||||
@@ -43,8 +52,28 @@ jobs:
|
|||||||
- name: Run the gate entry point
|
- name: Run the gate entry point
|
||||||
# The ONLY thing CI runs. No go build, no go test, no linting, no deploy. The
|
# The ONLY thing CI runs. No go build, no go test, no linting, no deploy. The
|
||||||
# exit code IS the result: no `|| true`, no pipe that could swallow it.
|
# exit code IS the result: no `|| true`, no pipe that could swallow it.
|
||||||
|
env:
|
||||||
|
# R-986: the security-scan gate fetches the PINNED gitleaks here (sha256-checked); no Go, so govulncheck says
|
||||||
|
# NOT CHECKED in CI, out loud. Warn-first either way: the scan lists, it never fails this job.
|
||||||
|
FELHOM_SCAN_FETCH: "1"
|
||||||
run: cd ws/felhom-controller/controller && python3 scripts/controller_gates.py --fast
|
run: cd ws/felhom-controller/controller && python3 scripts/controller_gates.py --fast
|
||||||
|
|
||||||
|
- name: Manual proof - alarm key present, optional forced failure (dispatch only, R-1129)
|
||||||
|
# Runs ONLY on a manual dispatch, never on a push. It prints the key's LENGTH, never the key,
|
||||||
|
# so "CI can see the secret" is an observable rather than an assumption. With
|
||||||
|
# force_alarm=true it then fails on purpose so the alarm step below sends its real mail;
|
||||||
|
# the commit itself stays green, because its push run skips this step.
|
||||||
|
if: github.event_name == 'workflow_dispatch'
|
||||||
|
env:
|
||||||
|
RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }}
|
||||||
|
FORCE_ALARM: ${{ github.event.inputs.force_alarm }}
|
||||||
|
run: |
|
||||||
|
python3 -c 'import os;print("RESEND_API_KEY length: %d" % len(os.environ.get("RESEND_API_KEY","")))'
|
||||||
|
if [ "$FORCE_ALARM" = "true" ]; then
|
||||||
|
echo "force_alarm=true - failing on purpose so the alarm step runs (R-1129 proof)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
- name: Alarm on failure
|
- name: Alarm on failure
|
||||||
# THE POINT OF THE WHOLE THING. Probe P5 measured that a failed run produces NO mail, NO
|
# THE POINT OF THE WHOLE THING. Probe P5 measured that a failed run produces NO mail, NO
|
||||||
# notification row and NO log line from Gitea itself — a red tick in a web UI nobody watches
|
# notification row and NO log line from Gitea itself — a red tick in a web UI nobody watches
|
||||||
@@ -58,6 +87,8 @@ jobs:
|
|||||||
if: failure()
|
if: failure()
|
||||||
env:
|
env:
|
||||||
RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }}
|
RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }}
|
||||||
|
# Empty on a push, so a push run's mail is exactly what it was before R-1129.
|
||||||
|
FORCE_ALARM: ${{ github.event.inputs.force_alarm }}
|
||||||
run: |
|
run: |
|
||||||
python3 - <<'PY'
|
python3 - <<'PY'
|
||||||
import json, os, sys, urllib.request, urllib.error
|
import json, os, sys, urllib.request, urllib.error
|
||||||
@@ -69,13 +100,23 @@ jobs:
|
|||||||
|
|
||||||
repo = os.environ.get("GITHUB_REPOSITORY", "?")
|
repo = os.environ.get("GITHUB_REPOSITORY", "?")
|
||||||
sha = os.environ.get("GITHUB_SHA", "?")
|
sha = os.environ.get("GITHUB_SHA", "?")
|
||||||
run = os.environ.get("GITHUB_RUN_NUMBER", "?")
|
# R-1135: the link is for a PERSON, so it is the public address and the run ID.
|
||||||
srv = os.environ.get("GITHUB_SERVER_URL", "https://gitea.dooplex.hu")
|
# NOT GITHUB_SERVER_URL: the runner registers at the in-cluster address, so that variable
|
||||||
|
# reads http://gitea.gitea-system.svc.cluster.local:3000, which nobody outside the cluster
|
||||||
|
# can open (forced-test mail, job 1997). NOT GITHUB_RUN_NUMBER: Gitea 1.26 reads
|
||||||
|
# /actions/runs/<n> as a run id first, so a run number that is also an older run's id
|
||||||
|
# opens THAT run (measured 2026-10-18: felhom.eu /actions/runs/1116 opened the run whose
|
||||||
|
# id is 1116 = run number 613). The link is printed too, so the job log carries it.
|
||||||
|
run = os.environ.get("GITHUB_RUN_ID", "?")
|
||||||
|
srv = "https://gitea.dooplex.hu"
|
||||||
|
print("ALARM-LINK %s/%s/actions/runs/%s" % (srv, repo, run))
|
||||||
|
|
||||||
body = json.dumps({
|
body = json.dumps({
|
||||||
"from": "Felhom CI <monitoring@felhom.eu>",
|
"from": "Felhom CI <monitoring@felhom.eu>",
|
||||||
"to": ["admin@felhom.eu"],
|
"to": ["admin@felhom.eu"],
|
||||||
"subject": "[felhom CI] gates FAILED in %s" % repo,
|
"subject": ("[felhom CI] FORCED TEST, not a real failure - gates FAILED in %s"
|
||||||
|
if os.environ.get("FORCE_ALARM") == "true"
|
||||||
|
else "[felhom CI] gates FAILED in %s") % repo,
|
||||||
"text": (
|
"text": (
|
||||||
"The gate entry point exited non-zero.\n\n"
|
"The gate entry point exited non-zero.\n\n"
|
||||||
"Repository : %s\n"
|
"Repository : %s\n"
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# .security-accepted — hits security_scan_gate.py (felhom.eu/scripts, R-986) lists as ACCEPTED, not WARN.
|
||||||
|
# One per line: <tool> <id> <where> # reason. govulncheck: OSV id + module dir; gitleaks: rule@<sha256[:12] of the line> + file.
|
||||||
|
# The first scan's verdicts (2026-10-19): felhom.eu documentation/audits/night-2026-10-19/P7/triage.md
|
||||||
|
gitleaks generic-api-key@93610586e88d controller/internal/stacks/samba_test.go # false: a test constant or a decoy value, no live secret
|
||||||
|
gitleaks generic-api-key@a882b8f2ea6b controller/internal/backup/offbox_offer_shapec_r241_test.go # false: a test constant or a decoy value, no live secret
|
||||||
|
gitleaks generic-api-key@b3c473a524c2 controller/scripts/test_gate_decoys.py # false: a test constant or a decoy value, no live secret
|
||||||
|
gitleaks generic-api-key@c9c6aa2fcae6 controller/scripts/test_gate_decoys.py # false: a test constant or a decoy value, no live secret
|
||||||
+2741
-2
File diff suppressed because it is too large.
Load diff
@@ -27,7 +27,7 @@ integrations, git-sync, notifications. Disk/host/Proxmox concerns are delegated
|
|||||||
| which box may I break | `felhom.eu/documentation/runbooks/target-selection.md` |
|
| which box may I break | `felhom.eu/documentation/runbooks/target-selection.md` |
|
||||||
| host addresses, break-glass, node facts | `felhom.eu/documentation/operations/nodes.md` |
|
| host addresses, break-glass, node facts | `felhom.eu/documentation/operations/nodes.md` |
|
||||||
| what version is live anywhere | ask the hub (`/hosts`, `/configs`) or the box — **never a doc** |
|
| what version is live anywhere | ask the hub (`/hosts`, `/configs`) or the box — **never a doc** |
|
||||||
| the authoritative design | `felhom.eu/documentation/architecture/01/02/03-*.md` |
|
| the authoritative design | `felhom.eu/documentation/architecture/NN-*.md` (01–03 for this repo; 07 backup, 09 updates, 10 language) |
|
||||||
|
|
||||||
## Session-critical invariants
|
## Session-critical invariants
|
||||||
|
|
||||||
@@ -37,8 +37,8 @@ The rest live in `REUSE.md`. These cost incidents to learn:
|
|||||||
- Docker's `.State` says "running" even for unhealthy containers — the `.Status` parse is the truth.
|
- Docker's `.State` says "running" even for unhealthy containers — the `.Status` parse is the truth.
|
||||||
- In-memory `Deployed` is set BEFORE `compose up -d` (slow-pull race); reverted on failure.
|
- In-memory `Deployed` is set BEFORE `compose up -d` (slow-pull race); reverted on failure.
|
||||||
- `compose up -d` exits 0 on crash-loops — the post-start status check is the detection.
|
- `compose up -d` exits 0 on crash-loops — the post-start status check is the detection.
|
||||||
- Env var KEYS are logged, never values. Protected stacks (traefik, cloudflared, felhom-controller)
|
- Env var KEYS are logged, never values. Protected stacks (traefik, cloudflared, felhom-controller,
|
||||||
cannot be stopped from the UI.
|
and always samba) cannot be stopped from the UI.
|
||||||
- Verify a container image HAS the healthcheck tool before using it (BusyBox wget / python3 / curl —
|
- Verify a container image HAS the healthcheck tool before using it (BusyBox wget / python3 / curl —
|
||||||
the catalog `REUSE.md` maps the families).
|
the catalog `REUSE.md` maps the families).
|
||||||
- `IsRunning()` is CONCURRENCY, false during a verification restore — display MUST use
|
- `IsRunning()` is CONCURRENCY, false during a verification restore — display MUST use
|
||||||
@@ -61,7 +61,7 @@ credentials) — they load when you touch a template or stylesheet.
|
|||||||
|
|
||||||
| Surface | Command |
|
| Surface | Command |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Gates (after ANY change) | `python3 controller/scripts/controller_gates.py` — from `controller/` |
|
| Gates (after ANY change) | `python3 scripts/controller_gates.py` — from `controller/` |
|
||||||
| Green gate | `go build ./... && go vet ./... && go test ./...` |
|
| Green gate | `go build ./... && go vet ./... && go test ./...` |
|
||||||
| Build + deploy | the **`felhom-build-deploy`** skill — do not hand-roll it |
|
| Build + deploy | the **`felhom-build-deploy`** skill — do not hand-roll it |
|
||||||
|
|
||||||
|
|||||||
+294
-1
@@ -1,5 +1,132 @@
|
|||||||
# CONTEXT.md — Project Memory
|
# CONTEXT.md — Project Memory
|
||||||
|
|
||||||
|
> **2026-11-10 (afternoon, attended) — v0.352.0 RELEASED: one fill warning per filesystem (felhom.eu R-1371).**
|
||||||
|
> Global floor 15:31 UTC, MinAgent 0.158.1; rc.1 on scratch guest 9202, then the three test boxes through per-box
|
||||||
|
> floors, walk green (felhom.eu `audits/release-space-fixes-2026-11-10/controller/`). `fillTargets` keeps one target per
|
||||||
|
> filesystem (`system.FilesystemKey`; an overlay "/" is identified by a Docker-kept file's device, not by its own).
|
||||||
|
> Seen on 9202: two warnings for one fill before, one after. Still open, by design question: the guest's own root disk
|
||||||
|
> has no fill watcher (felhom.eu `16-storage-physical-identity.md`).
|
||||||
|
|
||||||
|
> **2026-11-09 (attended) — v0.351.0 RELEASED** (global floor 12:18 UTC, MinAgent 0.158.1; rc.1 on Tester 1, then the
|
||||||
|
> three test boxes through per-box floors, walk green; felhom.eu `audits/release-2026-11-09/`). Operator's word 2026-11-09 („go with A"): decision 56 amended
|
||||||
|
> (an old `-rc` controller image is deleted like an old release) and decision 285 (pinned infra images keep the pin + the
|
||||||
|
> previous pin). Measured cause: demo-hp's whole-guest local copy refused for space (felhom.eu R-548); 3.5 GB of its 27.5 GB
|
||||||
|
> of images were these kinds. The bigger lever — the whole-guest copy carries every Docker image — is a design question
|
||||||
|
> (felhom.eu register, filed the same day).
|
||||||
|
|
||||||
|
> **2026-11-03 (day, attended) — v0.350.0 RELEASED, the global floor since 08:18 CET (MinAgent 0.158.1).** Image `sha256:9ee53908…` from `5c336d8`. Traefik v3.7.17 (GHSA-xv5x), R-1347, R-1348, R-1339, R-1351, R-1323. Golden 0.350.0 vouched 10:18:10 CET.
|
||||||
|
>
|
||||||
|
> **2026-10-29 (evening, attended) — v0.349.0 RELEASED, the global floor since 19:24 CET (MinAgent 0.158.1).** Image
|
||||||
|
> `sha256:c5341883…` from `94049a7`. D65 = A: `internal/busymark` keeps `<data>/ctl/busy` fresh while the controller's
|
||||||
|
> own work runs (the agent refuses „Reboot guest" meanwhile); the dashboard shows „A Felhom ügyfélszolgálata HH:MM-kor
|
||||||
|
> újraindította a dobozt." for a day after an operator reboot (`GET /guest/operator-reboot`, asked once at start).
|
||||||
|
> R-1350: the operator's hold clear records the stop as wanted (desired state „stopped") before the hold is lifted —
|
||||||
|
> proven on Tester 1, no `app_start_failed` in 6.5 minutes. 30-minute watch clean; per-box floors cleared.
|
||||||
|
|
||||||
|
> **2026-10-29 (afternoon, attended) — v0.348.0 RELEASED, the global floor since 14:48 CET (MinAgent 0.158.1).** Image
|
||||||
|
> `sha256:672fc1c1…` from `2a0a17a` (CI 2515). D64 = B (`09` §3 decision 283): `clear_hold` is the fifth verb of the closed
|
||||||
|
> operator-action list; any hold reason; the running controller clears memory and `settings.json` together through
|
||||||
|
> `<data>/ctl/hold.sock` (0600, peer uid checked), and `--clear-restore-hold` goes through it when a controller runs
|
||||||
|
> (R-1343). R-1340 (both producers name the real cause), R-1341 (OOM line once per kill), R-1342 (no delete during the
|
||||||
|
> stable-start watch). Proven live on Tester 1 on the release build: a crash-loop hold cleared from the hub stayed
|
||||||
|
> cleared after the next settings save. Open: R-1350 (an `app_start_failed` 30 s after a clear), R-1347, R-1348.
|
||||||
|
|
||||||
|
> **2026-10-29 (attended release run) — v0.347.0 RELEASED, the global floor (MinAgent 0.158.1).** Image `sha256:c79b06e6…`
|
||||||
|
> from `fd75c7c` (CI 2491); rc.1 = `e3fce09` on scratch 9202. Carries the night's R-1256 (all four edges, H4 + H5's
|
||||||
|
> failed stop proven live on Tester 1 with a `-tags faultinject` test build — D63), R-1254 controller half, R-528, the
|
||||||
|
> unknown-app 404, and D62 (restore copies 30 days; „Törlés most" in the kept-copies list; `restore_copy_deleted` needs hub
|
||||||
|
> ≥ 0.175.0). The fault switch (`cmd/controller/faultpoint_{on,off}.go`) is a no-op in every build without the tag
|
||||||
|
> (`TestD63_TheReleaseBuildHasNoFaultSwitch`). Next here: R-1340 (the mixed-hold operator mail), R-1341 (the OOM WARN every
|
||||||
|
> 30 s), R-1339 (the false „not mounted" line).
|
||||||
|
|
||||||
|
> **2026-10-28 night (unattended) — R-1256, R-1254 (controller half), R-528 and the unknown-app 404 on `main`, NOT
|
||||||
|
> released (`342a394`, `e33cffa`, `eed23e7`, `20c5877`; MinAgent unchanged).** Restore ops begin through
|
||||||
|
> `Manager.TryBeginRestoreOp` / `web.beginRestoreOp` only (`TestR1256_H6_NoHandlerBeginsARestoreUnchecked` refuses a direct
|
||||||
|
> `BeginRestoreOp` in a handler). **Decided by CC unattended — operator may reverse:** an unused restore copy goes after
|
||||||
|
> 14 days (`restoreCopyUnusedAge`; felhom.eu `07` §6.3). H4 and H5's failed stop: tests only, live proof owed. H5 (busy
|
||||||
|
> volume) proven live on 9202, R-528 on Tester 1, with the local test tag `0.347.0-rc.n1028` (never pushed).
|
||||||
|
|
||||||
|
> **2026-10-26 (evening) — D53 ruled (felhom.eu `09` §3 decision 265): held apps reach the OPERATOR first.** Next here:
|
||||||
|
> the controller reports its holds (stack, reason, since) to the hub as `app_held` / `app_hold_cleared` events plus a
|
||||||
|
> daily re-send (felhom.eu `08` §10). Commit only; the release rides a later attended run.
|
||||||
|
|
||||||
|
> **2026-10-25 (Sunday, unattended) — D47, D48, R-1270, R-1271 on `main`, NOT released (next v0.343.0, MinAgent 0.158.1
|
||||||
|
> unchanged).** D47 (`02daebe`): `stacks.AppConfig.InstallID` (minted at install/import, taken from the unit by a
|
||||||
|
> restore, `EnsureInstallID` for older apps); `backup/unit_owner.go` `guardUnitWrite`/`guardUnitDir` in every unit writer
|
||||||
|
> (capture, refresh, dumps, update pre-backup, volume dump, second-drive unit copy, stale-drive prune) sets another
|
||||||
|
> install's unit aside whole (`backups/set-aside/<app>/<stamp>`, a kept copy kind `unit`, restore page „Visszaállítás").
|
||||||
|
> R-1270 (`b680db8`): `ErrRestoreNotStarted` from every restore path on a health timeout; undo copy kept; late-start
|
||||||
|
> watcher. D48 (`2d71270`): `prepareRestoreImages` before the stop on every restore path under
|
||||||
|
> `dockerexec.HoldImageWork`. R-1271 (`bd9f4f7`): `keptPick`/`KeptNewerAt` — a copy more than 10 min in the future is
|
||||||
|
> never the newest. Live proofs on 9202 with `0.343.0-rc.1`: felhom.eu `audits/restore-truth-2026-10-25/`.
|
||||||
|
|
||||||
|
> **2026-10-24 night (unattended restore-holes run) — on `main`, NOT released (next v0.343.0, MinAgent 0.158.1 unchanged).**
|
||||||
|
> R-1251: a pending put-back blocks every start (`backup/appstop_putback_wait.go`: restore hold `putback_pending`, the
|
||||||
|
> hold store every start path honours; `ResumePutBack` in the boot recreate and `restartStacks`; `ResumeWaitingPutBacks`
|
||||||
|
> at start and on a drive return; a failed put-back = the D20 hold; the copy's folders synced before `SetUndo`).
|
||||||
|
> R-1252: `tier2CaptureSetFull` returns `classified`; reconcile only then; `BackupBlockRejected` via the stack adapter.
|
||||||
|
> R-1253: `AppStopGuard.BusyWith` / `BeginExclusive`; the exporter refuses a stop-first export. Proven on Tester 1
|
||||||
|
> (R-1251) and 9202 (R-1252, R-1253): felhom.eu `audits/restore-holes-2026-10-24/`. Release: Monday's list (STATUS).
|
||||||
|
|
||||||
|
> **2026-10-24 (attended release run) — v0.342.0 gains the TESTED line (operator rulings D41 = 50 %, D42, the iperf3 line
|
||||||
|
> test; felhom.eu CONTEXT 07:22/07:26).** `agentapi.LineTest` reads the agent's `GET /host/line-test` (agent ≥ 0.164.0 —
|
||||||
|
> its weekly 10-second iperf3 upload to ep0 inside the tunnel; demo-hp measured 90.7 Mbit/s where the push floor said 10).
|
||||||
|
> qBittorrent's limit = 50 % of the TESTED line only; the watch uses the higher of test and floor; the system page names
|
||||||
|
> the source. MinAgent stays 0.158.1 (an older agent = „not measured" = no limit). Release order: agent 0.164.0 (vouch),
|
||||||
|
> hub 0.169.0, then this controller through the normal path.
|
||||||
|
|
||||||
|
> **2026-10-23 night — v0.342.0 on `main`, NOT released: the upload and CPU watch (`internal/upwatch`; operator ruling
|
||||||
|
> 2026-10-23 19:22; felhom.eu `08` §9 [DESIGN — proposed], `audits/SPIKE-upload-watch-2026-10-23.md`).** Exact
|
||||||
|
> per-container counters (Docker Engine API), per-app judging, explainers qBittorrent / Transmission / Plex, the
|
||||||
|
> operator-only `app_unexplained_upload` / `app_unexplained_cpu` (+ `_cleared`; hub 0.169.0, also unreleased), the line
|
||||||
|
> from a one-second sample of the off-site push (settings.json `upwatch`), qBittorrent's default limit (50 %, never over
|
||||||
|
> the household's). `0.342.0-rc.1` ran on scratch 9202 (its off-site is off, so the line was seeded by hand there).
|
||||||
|
> Open: R-1244 (release), R-1245 (limit size), R-1246 (who is told), R-1247 (active line test), R-1248 (a `tc` ceiling).
|
||||||
|
|
||||||
|
> **2026-10-23 (day, later) — v0.341.0: the night leg takes a `security_fix` ladder step (D39 = B, `09` §3 decision 255,
|
||||||
|
> R-1239; operator ruling by starting the run).** `legCandidate`: verdict `proven` OR `security_fix`, every other guard
|
||||||
|
> unchanged and in order; log `[update-leg] <app>: security fix <ids> taken (<from> → <to>)`; `LegStep.Security`. The
|
||||||
|
> catalog side (format, gates, writer, `box_walk.py --security`) is catalog `3898593`. On ≤ 0.340.0 the leg skips such a
|
||||||
|
> step (`not_proven`) and a hand press takes it — both proven on 9202 (felhom.eu `audits/security-lane-2026-10-23/`).
|
||||||
|
|
||||||
|
> **2026-10-22/23 night — 0.340.0 candidate on `main`, unreleased.** The stray-copy fix (`66a69d4`, `912e592`) and two
|
||||||
|
> review rounds (`943c517` C5/C3/C6/C8; `9d9e404` N2–N5, N9; `1babfe9` two races): the capped copy's container has a
|
||||||
|
> fixed name + label, is removed by name on any error, leftovers are removed at start before the scheduler/web server
|
||||||
|
> (holding the destination's lock), one copy per destination at a time, `RunTier2` refuses during a restore of the app
|
||||||
|
> in one step with its record (`beginTier2Run`), every leg asks again; a restore is refused while a copy runs or a stray
|
||||||
|
> may run (per-name strays, cleared by a later removal). Proven on 9202 with rc.5 and rc.8; rc.8 runs on the test box
|
||||||
|
> (Tester4-16fdef) for the night. Release: 0.340.0 with MinAgent 0.158.1, the operator's yes (STATUS morning list).
|
||||||
|
|
||||||
|
> **2026-10-22 night — four fixes on `main`, NOT released (night brief: no release). The next release is 0.340.0, MinAgent 0.158.1.** R-49 (D21 = B): `.felhom.yml` `backup.volumes` class `excluded` (`6a17c95`); R-1187(c): an import over an installed app that is not running is refused (`d5f88a2`, reproduced and proven fixed on 9202); R-1189(d): `nightchain.CatchUp.After` runs the off-site proof + integrity once after a catch-up (`d5f88a2`); R-1214: the second-drive copy runs in a 512 MB memory-capped container for clean `/mnt/` paths with no symlink (`03c0a69`, `ae39467`). 9202 ran rc.1–rc.4 and is back on 0.339.0. rc tags pushed: 0.340.0-rc.1..rc.4 (never offered: not X.Y.Z).
|
||||||
|
|
||||||
|
> **2026-10-20 — v0.336.0 is the floor (MinAgent 0.158.1, 08:54 UTC).** R-893 option A (operator D20): a failed off-site restore
|
||||||
|
> copies the app's live volumes first and puts them back exactly, then starts the app (proven on 9202: schema, data and row-count
|
||||||
|
> md5 equal before and after a forced failure); R-1169 the held sentence. Follow-up row: the put-back's ERROR log level and an
|
||||||
|
> empty `backups/restore-undo/` folder.
|
||||||
|
|
||||||
|
|
||||||
|
> **2026-10-19 (day) — v0.332.0 is the floor (MinAgent 0.158.1): one sign-in for the file manager (R-1100, D16) and the
|
||||||
|
> typed-back escrow confirm (R-1151).** Every dashboard folder link → `fileBrowserOpenLink` → `GET /__files/open` (pass:
|
||||||
|
> 60 s, one use, host + session bound; none for `Sec-Fetch-Site: cross-site`) → traefik forwardAuth `GET
|
||||||
|
> /__felhom_gate/files` (`web/files_sso.go`) swaps it at `/_felhom/sso` for the host-only `felhom_files` cookie and then sets
|
||||||
|
> the per-box SECRET header (`infra.LoadOrCreateFileBrowserSSOHeader`, `<data>/filebrowser-sso-header`, NEVER logged)
|
||||||
|
> naming `felhom-household`. **A forwardAuth answer's redirect must be ABSOLUTE** (traefik resolves a relative Location
|
||||||
|
> against the auth server — rc.2 sent browsers to `http://felhom-controller:8080/…`). Escrow: the claim sends
|
||||||
|
> `{"defer_upload": true}`; `/api/escrow/confirm` forwards the two typed words; an agent < 0.160.0 needs no confirm.
|
||||||
|
> Residuals R-1155 (FileBrowser's own token), R-1161 (the „live code" wording). felhom.eu `REPORT-day-2026-10-19.md`.
|
||||||
|
> **2026-10-18 (evening) — v0.331.0: OnlyOffice opens and saves from FileBrowser (`server.internalUrl`) and Nextcloud
|
||||||
|
> (`DocumentServerInternalUrl` with its slash); a FileBrowser restart runs the R-1126 gate at once (R-1018); a removal deletes volumes still labelled with the
|
||||||
|
> app's project that the definition no longer declares (R-1117).** MinAgent 0.158.1.
|
||||||
|
> **2026-10-18 (day) — v0.330.0: „anyway" asks the agent's disk list first and starts again the apps it stopped when the
|
||||||
|
> agent refuses (R-1144).** MinAgent 0.158.1.
|
||||||
|
> **2026-10-18 (night) — v0.329.0: each app reaches only its own `appdata/<folder>` (R-1142, compiled-in folder map:
|
||||||
|
> paperless-ngx → paperless); the allow-list is EMPTY (homepage's socket removed, R-981); a drive retirement asks the agent
|
||||||
|
> first and a refusal changes nothing (R-1063); a plain message for a virtio disk without a serial (R-1069); `:latest`
|
||||||
|
> only for a release tag (R-1143).** MinAgent 0.158.1.
|
||||||
|
> **2026-10-17 (late) — v0.328.0 is the floor (MinAgent 0.158.1): the catalog allow-list (R-971, operator decision D2 = A).**
|
||||||
|
> `internal/privpolicy` refuses container rights not on the compiled list before ANY compose write; refusal = nothing
|
||||||
|
> written + `app_definition_refused` (hub ≥ 0.157.0) + an app-page line. Three security-review rounds fixed before the
|
||||||
|
> release; a live finding on 9201 (rc.4) fixed in rc.5. Follow-ups R-1142 (cross-app appdata), R-1143 (`:latest`).
|
||||||
> This file serves as persistent project memory across Claude Code sessions.
|
> This file serves as persistent project memory across Claude Code sessions.
|
||||||
> It replaces the auto-generated "Memory" from the claude.ai Project.
|
> It replaces the auto-generated "Memory" from the claude.ai Project.
|
||||||
> **Update this file at the end of each working session** with current state,
|
> **Update this file at the end of each working session** with current state,
|
||||||
@@ -7,7 +134,173 @@
|
|||||||
>
|
>
|
||||||
> Ask Claude Code: "Please update CONTEXT.md with what we did today"
|
> Ask Claude Code: "Please update CONTEXT.md with what we did today"
|
||||||
|
|
||||||
Last updated: 2026-10-04 (v0.293.0 — the Docker-socket self-heal, R-860)
|
Last updated: 2026-10-17 (v0.327.0 — FileBrowser published only after its check; real memory amounts in the install check)
|
||||||
|
|
||||||
|
> **2026-10-17 (afternoon, 2) — v0.327.0.** R-1126 (D11 = A): FileBrowser off `traefik-public` until this run's default
|
||||||
|
> login is checked (`stacks/filebrowser_gate.go`, connect by container ID); FileBrowser's own admin-password setting
|
||||||
|
> re-applies every start, so it cannot carry ours. R-1125 (D10 = A): catalog requests = measured use; the refusal and the
|
||||||
|
> install page say what to do; the page reads `stacks.InstallMemory` like the check. R-1129 was a misreading (CI mail
|
||||||
|
> always worked).
|
||||||
|
|
||||||
|
> **2026-10-17 (afternoon) — v0.326.0.** R-977: `EnsureFileBrowserAdminPassword` probes the default login once per
|
||||||
|
> FileBrowser RUN (`fbStartedAt`, `fbProbedRun`), with ~20 s for a new run to answer; measured on 9202 before (default 200
|
||||||
|
> for 10 min after a re-created volume) and after (replaced in 2 s). The tunnel-before-claim question is the operator's
|
||||||
|
> (R-1126). R-1116: `gate-decoys` in the full run (not `--fast`: 22 s, edits real files — R-1128).
|
||||||
|
|
||||||
|
> **2026-10-17 (day) — v0.325.0 (burndown 3).** R-1111 `reserveAttempt` is the one limiter body (dashboard sign-in,
|
||||||
|
> share password, escrow re-auth). R-1112 `family.json` stores fingerprints; an old file is converted when the
|
||||||
|
> controller STARTS (`webServer.OpenFamilyStore` — rc.1 opened it lazily, found live on 9201). R-1113 the household's
|
||||||
|
> pass reuses its family session (`Store.HouseholdSession`, new one under half-life). R-1109 samba compose label
|
||||||
|
> `felhom.smb-conf-sha256` (every box with sharing on recreates samba once). R-1110 `TestNoBareDrivePathToPathHelpers`.
|
||||||
|
> R-1114 `scripts/shared_scripts.py` + `FELHOM_WORKSPACE`. Same day, catalog `5d9450b`: five apps' Redis → RDB
|
||||||
|
> (R-1096), applied at each app's next start. Known flake filed: a stacks test writes `update-journal.json(.tmp)` into
|
||||||
|
> the package folder (empty DataDir), and the R-578 walk can trip on it.
|
||||||
|
|
||||||
|
> **2026-10-17 (night) — v0.324.0 RELEASED to the three test boxes (per-box floors, 21:52 UTC).** R-1106 / R-127 b
|
||||||
|
> (operator decision 1A): `appbackup.DBCredentialVars` + `DBDataVolumes`; `backup/restore_dbcreds.go` (pure
|
||||||
|
> `planDBCredentials`, `dbCredentialPlanFor`, `offsiteCredentialOverlay`); `unitRestoreEnv` refuses a DB credential it
|
||||||
|
> cannot source and O4 never generates one; the same-version off-site restore writes the snapshot's password via the
|
||||||
|
> optional `secretValueSetter` → `stacks.SetStackSecretValues` (load-then-save; also marks the reinstall's `type:
|
||||||
|
> password` logins as restored — R-926). R-1107: restic 0.19.1 pinned; fixtures for three versions. R-1108, R-1065,
|
||||||
|
> R-1017 (+ `userdataKept` fix), R-983 (6), R-976 (2) — written by two helper sessions in detached worktrees, merged
|
||||||
|
> and reviewed here. Proven live on demo-hp. **Global floor 0.324.0 / MinAgent 0.158.1 at 02:46 UTC 2026-10-17**, after all three test boxes
|
||||||
|
> made the night's off-site backup on it; per-box floors cleared. Next: R-1096 (Redis plan in `audits/night-restore-2026-10-17/P6/`), R-1109…R-1115.
|
||||||
|
|
||||||
|
> **2026-10-16 (evening) — v0.323.0 RELEASED to the three test boxes ONLY (per-box floors); the GLOBAL floor stays
|
||||||
|
> 0.322.0 until each test box has made one real night's off-site backup on 0.323.0** (the brief's rule; the check and
|
||||||
|
> the floor command are in felhom.eu `STATUS.md`). R-1105: runtime `debian:13.7-slim` (digest-pinned), Docker repo
|
||||||
|
> codename from `/etc/os-release`; restic is the official 0.18.1 release binary from a `restic` build stage (signed
|
||||||
|
> `SHA256SUMS` + vendored key in `third_party/restic/`, published sum, pinned per-arch sum). Every restic assumption
|
||||||
|
> re-proven with REAL outputs of 0.14.0 and 0.18.1 (`internal/backup/testdata/restic/`, `TestR1105_*`); the one that
|
||||||
|
> moved is the forget plan — 0.17+ keeps each group's oldest snapshot while monthly slots are unused (only ever keeps
|
||||||
|
> more). Removed packages the binary never runs (postgres/mysql clients, sqlite3, fdisk, e2fsprogs, parted, sshpass).
|
||||||
|
> felhom-samba 1.2.0 (Alpine 3.24.2), and `build-samba-image.sh` refuses a reused tag. Live on demo-hp 9201: both
|
||||||
|
> restore directions byte-identical on the real store; the drill's data came back; the full restore after a reinstall
|
||||||
|
> leaves a DB app unusable (old volume, new password — R-1106, not restic). Open: R-1107 (restic 0.18.1's binary adds
|
||||||
|
> 50 fixable scanner findings; 0.19.1 has 19 — the operator's choice), R-1108 (a share added before the first password
|
||||||
|
> is not exported). **Decision (CC, inside the brief, reversible):** the packages above were removed though the brief
|
||||||
|
> named only the two database clients — none is run by the binary (every exec call read), and the image carries fewer
|
||||||
|
> known holes. Full report: felhom.eu `REPORT-debian13-restic-2026-10-16.md`.
|
||||||
|
|
||||||
|
> **2026-10-16 — v0.322.0 RELEASED by CC; the global floor 0.322.0 / MinAgent 0.158.1.** R-970: `/api/config`,
|
||||||
|
> `/api/config/apply`, `/api/config/hash` are gone; the self-update and geo routes no longer take the box's hub key
|
||||||
|
> (`selfUpdateAuthMiddleware` removed), and the CSRF Bearer exemption is gone. The route table is `buildMux` in `main.go`
|
||||||
|
> so `TestR970_HubKeyOpensNoDoor` drives the real table. R-972: Go 1.27.2, x/crypto v0.58.0, runtime
|
||||||
|
> `debian:12.13-slim` pinned by digest + `apt-get upgrade`. **Decision (CC, inside the brief, reversible): the runtime
|
||||||
|
> stays on Debian 12** — Debian 13 brings restic 0.18.0 and the off-site code relies on measured 0.14.0 behaviour; the
|
||||||
|
> move is R-1105. Data tab: the export field is `fab_encryption_key`, `autocomplete="new-password"`; the 2nd-copy
|
||||||
|
> status rows are gone. R-1103: the installed-only branches of `app_fields.html` removed; their rules live in the
|
||||||
|
> app-page and settings-tab tests. Full report: felhom.eu `REPORT-burndown2-2026-10-16.md`.
|
||||||
|
|
||||||
|
> **2026-10-16 — v0.321.0 RELEASED by CC; the global floor 0.321.0 / MinAgent 0.158.1.** R-1101: in `generated` the page asks
|
||||||
|
> FileBrowser whether the stored password still logs in (`stacks.FileBrowserStoredPasswordRefused`, only a 401/403 counts)
|
||||||
|
> and, refused, offers the reset; no „change it" line for FileBrowser; its config switches off its update banner and
|
||||||
|
> „Install app" prompt. The Data tab's backup part is one section in plain words. R-1095: `/apps/{slug}/install` of an
|
||||||
|
> installed app → 302 settings; the installed-only `app_fields.html` branches stay (R-1103). Catalog the same day: RomM's
|
||||||
|
> saves in a named volume (R-1097), `default_creds` off eight apps (D10 = A). Next: R-1103; R-1067 waits on Tester-2 (0.292.0).
|
||||||
|
|
||||||
|
> **2026-10-16 — v0.320.0 RELEASED by CC; the global floor 0.320.0 / MinAgent 0.158.1.** A protected infra stack is
|
||||||
|
> installed by definition on the app page (`Deployed || Protected`; v0.315.0 had shown FileBrowser „not installed" with
|
||||||
|
> Install and no login); the deploy API and `DeployStack` refuse a protected stack. FileBrowser `operator` state →
|
||||||
|
> „Új jelszó beállítása" (`stacks.ResetFileBrowserAdminPassword`: its CLI with the server stopped, verify, encrypt,
|
||||||
|
> `generated`) — pressed on demo-hp; **the N100 waits for the operator's yes**. Every installed app has ONE login answer
|
||||||
|
> (`web/app_login.go` `loginAnswerFor`; catalog `app_info.login_kind`). „Fájlok ↗" + per-drive media folders; a folder with
|
||||||
|
> no FileBrowser source is text. Decisions inside the brief (felhom.eu `REPORT-logins-folders-2026-10-16.md` §0): no backup
|
||||||
|
> sentence on media rows; no data tab for infra; „none" behind the family gate says the family sign-in. Next: R-1100
|
||||||
|
> (one sign-in), R-1101 (stale FileBrowser password), R-1102 (eight „known password" lines, decision D10).
|
||||||
|
|
||||||
|
> **2026-10-16 — v0.319.0 RELEASED by CC; the global floor 0.319.0 / MinAgent 0.158.1.** App page style A (operator
|
||||||
|
> 2026-10-16): the hero, the tab bar and every section are panels on `--bg-1`; the install page's form groups use the same
|
||||||
|
> rule. „Belépés az alkalmazásba" pairs a `type: password` field with its `*_USER/_USERNAME/_EMAIL` name
|
||||||
|
> (`web/app_login.go`); a field the box holds no value for is a sentence, never an eye — page and reveal endpoint share
|
||||||
|
> `storedValuePresent`. Measured cause on demo-hp: Calibre-Web installed 2026-08-21, `ADMIN_PASSWORD` entered its template
|
||||||
|
> 2026-09-29, and `InjectMissingFields` never fills a `type: password` field; its stored user name is real (renamed in the
|
||||||
|
> app on 2026-10-01). The settings tab no longer renders `app_deploy_fields`; `/apps/{slug}/install` for an installed app
|
||||||
|
> still does (R-1095). Evidence: felhom.eu `audits/app-page-tuning-2026-10-16/`.
|
||||||
|
|
||||||
|
> **2026-10-16 — v0.318.0 RELEASED; the global floor 0.318.0 / MinAgent 0.158.1 (set by the operator).** The internal data
|
||||||
|
> place („Belső tárhely", agent ≥ 0.158.1 reports kind `internal`): bound on one drive-gate tick, registered on the next as
|
||||||
|
> the default drive (web/internal_place.go); eject/decommission/wipe of it refused. Partitions in the format/attach wizards
|
||||||
|
> (agent `formattable`: only while nothing on the disk is mounted); the whole disk under a registered part refused
|
||||||
|
> server-side (`deviceBacksRegistered`). R-1084: the whole-box backup offer asks the same-disk question (`offerRelationFor`).
|
||||||
|
> R-1082: `/mnt/sys_drive` never offered (`withoutSystemVolume`, by device). Live on a fresh one-disk scratch box: felhom.eu
|
||||||
|
> `audits/storage-identity-buildB-2026-10-15/`. Next: R-1094 (the whole-disk refusal sentence), with the next release.
|
||||||
|
|
||||||
|
> **2026-10-15 (late evening) — v0.316.0/.1/.2 built and on demo-hp; .3 committed, NOT built.**
|
||||||
|
> **Measured before fixing:** the tabs rendered unstyled through the public address because of a
|
||||||
|
> CACHE, not the box — the stylesheet URL was `?v={{.Version}}`, identical across three different
|
||||||
|
> 0.315.0 builds; the origin sends NO ETag and NO Last-Modified, so a copy can only expire; and
|
||||||
|
> Cloudflare caches it while rewriting the browser TTL to four hours. Evidence and its caveat:
|
||||||
|
> `audits/app-page-2026-10-15b/P0/VERDICT.md`.
|
||||||
|
> **Two mechanisms now:** `build.sh` refuses a second push of a version (a registry it cannot reach
|
||||||
|
> is a refusal too), and every shell's stylesheet address is a per-build tag.
|
||||||
|
> **The app page is the approved one-column mockup**: one width, hairline sections, underlined tabs,
|
||||||
|
> and a box only for „the app is waiting for you" (blue) or „this is risky" (amber). The
|
||||||
|
> auto-update SUCCESS banner is now meta text.
|
||||||
|
> **THE LESSON OF THE EVENING, and it cost a bad push:** I put the guard in `controller/build.sh`,
|
||||||
|
> but the release runbook runs `build/felhom-controller/build.sh` — a SEPARATE COPY from
|
||||||
|
> 2026-07-18. Proving the refusal against a real tag therefore re-pushed 0.315.0 a fourth time
|
||||||
|
> (R-1081). The build directory's script is a symlink now. A guard in a script nobody runs is not a
|
||||||
|
> guard. The same shape bit twice more in one evening: the asset tag shipped dead because only one
|
||||||
|
> of TWO render paths set it, and both times a BROWSER found what the suite could not.
|
||||||
|
> Not yet validated: the operator's own look; 0.316.3's two cosmetic fixes.
|
||||||
|
|
||||||
|
> **2026-10-15 (evening) — v0.315.0, ONE APP PAGE WITH FOUR TABS.** An app was six pages and every „Vissza" went to the
|
||||||
|
> app LIST; it is now `/apps/{slug}/{settings,data,guide,logs}` plus `/apps/{slug}/install`, one shared header and one
|
||||||
|
> set of banners (`internal/web/app_page.go`, `templates/app_shell.html`). Operator decisions recorded for this release:
|
||||||
|
> **D1** — Export lives on „Adatok és mentés", not under Beállítások. **D2** — an after-start field's CARD is rendered
|
||||||
|
> generically from the catalog's `after_start: true`, and its ACTION is Go code in a registry keyed by slug + env var
|
||||||
|
> (`internal/web/after_start.go`), so customer text can never reach a catalog-defined command. **The FAQ is a section of
|
||||||
|
> the guide, not a tab**, and **the guide tab replaces the details page**. **302, never 301**, for every old
|
||||||
|
> `/stacks/{name}/…` GET — a cached 301 cannot be withdrawn; every POST on those paths is untouched.
|
||||||
|
> New catalog block `app_info.guide` (sections + faq + `checked_version`), rendered only when `checked_version` names the
|
||||||
|
> image tag its author checked it against; no template carries one yet (the content is the companion task). The Pi and
|
||||||
|
> „csak x86" badges are gone; `PiCompatible` and the catalog key STAY this release, or a box on 0.314.0 would read
|
||||||
|
> „csak x86" on every app.
|
||||||
|
> **Found by a red-proof, and worth remembering:** the after-start handler's „the catalog must have DECLARED this field"
|
||||||
|
> check could be deleted with the whole suite green — and a POST for an undeclared field then reached Plex and opened the
|
||||||
|
> setup gate. Two guards that look like one are two tests.
|
||||||
|
> **Two defects the whole test suite could not see, both found in Chrome on the workstation** (this is
|
||||||
|
> the case for CC running on Windows): the tab bar had no CSS at all and the hero logo was unsized,
|
||||||
|
> because the shell invented class names beside ones the design system already had rules for; and the
|
||||||
|
> log tab's `<script>` was never closed, so the page rendered, every marker matched, and the live log
|
||||||
|
> poller was dead ("SyntaxError: Unexpected token '<'"). A marker proves a string is present, not that
|
||||||
|
> the browser will run it. `TestAppPage_ScriptTagsAreBalanced` now pins the second on all seven URLs.
|
||||||
|
> Live on demo-hp 9201; the floor stays 0.314.0 until all three test boxes have taken it.
|
||||||
|
> Not yet validated: the operator's own look at the page, and a real Plex claim through the new card.
|
||||||
|
|
||||||
|
> **2026-10-15 (evening) — v0.314.0, the floor since 13:11 UTC (raised by CC's token after the three test boxes; no golden).**
|
||||||
|
> A restore puts the setup gate back as it was (`internal/stacks/restore_gate.go`, felhom.eu `09` §3 decision 253, R-1057);
|
||||||
|
> `util.ParseVersionPre` puts `X.Y.Z-rc.N` below `X.Y.Z` for the floor ONLY — never for the tags offered (R-1053);
|
||||||
|
> Prowlarr's start runs the media wiring (`linkOnlyApps`, R-1058); every Plex call goes to the container's address
|
||||||
|
> (`mediawire.PlexURL`, R-1060 — Plex refuses the name `plex` as non-local). Still open: the real Plex claim on demo-hp
|
||||||
|
> 9201 (the operator's code), R-1052's new-box proof (a throwaway customer is session only).
|
||||||
|
|
||||||
|
> **2026-10-15 (afternoon) — release rule `09` §3 decision 250:** a release needs no golden; the floor carries it after
|
||||||
|
> the three test boxes; the golden is weekly. Test images use `-rc.N` tags — the household button skips them, but the
|
||||||
|
> floor never moves a box running one (`maybeAutoUpdate: not parseable — skip`, R-1053): write the release tag back.
|
||||||
|
|
||||||
|
> **2026-10-15 — v0.313.0, the media build (R-1023 and the rows under it; `09` §3 decisions 245, 247, 248).** Media apps bind
|
||||||
|
> every PRESENT drive through an owned `docker-compose.override.yml` (`media_library:` marker in the template); a real
|
||||||
|
> restart (force-recreate + start times); the drive wiring (`internal/mediawire`, keys read at use — Plex's own token,
|
||||||
|
> decision 248; Jellyfin's key named „felhom"); drive events with the notice, „restart now/later" and a stream check; safe
|
||||||
|
> removal keeps the drive; Plex's code asked after the start (`after_start`). Floor 0.313.0 and golden 0.313.0 vouched by the operator 2026-10-15 11:29. Traps found on Tester 1 and fixed: qBittorrent 5 logs in with 204; the agent's disk
|
||||||
|
> `state` stays „attached" for a pulled registered disk (presence = backing device); the drive gate raced a safe removal.
|
||||||
|
> A Plex status probe (`/library/sections`, 401) OPENED an unclaimed Plex while Plex started — removed within the hour;
|
||||||
|
> never gate on a status a starting app also returns.
|
||||||
|
|
||||||
|
> **2026-10-14 (night) — v0.312.0, https only (R-1033, P1; `09` §3 decision 244).** DECIDED BY CC UNATTENDED — operator
|
||||||
|
> may reverse: the redirect lives in traefik on the box (`felhom-https-only` in the `felhom-forwarded` chain), not in
|
||||||
|
> Cloudflare, because every box's `cf_api_token` lacks „Zone Settings" (403, measured on all three zones). Cloudflare's
|
||||||
|
> „Always Use HTTPS" stays the operator's defence-in-depth option once the keys carry the permission. HSTS one day.
|
||||||
|
|
||||||
|
> **2026-10-08 (day) — UNRELEASED on main, ships with tomorrow's release (no release today: kernel night 8→9, `09` §3
|
||||||
|
> decision 178).** R-899 (decision 177): a daytime press never cancels the night's whole-guest backup —
|
||||||
|
> `internal/quiesce/nightowed.go` ledger, owed tiers never fire the valve; a press reaches the agent as `trigger=manual`.
|
||||||
|
> R-304: the agent's new 424 `older_unchecked` → `RecoveryOlderUnchecked`, bundle key `recovery.older_unchecked` (hu+en).
|
||||||
|
> MinAgent unchanged (0.131.0): both changes degrade safely against an older agent. Afternoon (`a40729a`): the
|
||||||
|
> operator-only `recovery_older_package` event (decision 183; needs the hub of the same day), no eject/format on a
|
||||||
|
> backup-target drive (R-298 side fix), R-717 comments.
|
||||||
|
|
||||||
> **2026-10-04 night — v0.293.0 (R-860; floor 0.293.0 on the demo customers only, golden 0.293.0 vouched):**
|
> **2026-10-04 night — v0.293.0 (R-860; floor 0.293.0 on the demo customers only, golden 0.293.0 vouched):**
|
||||||
> `internal/sockheal` — the controller exits after 60 s of socket REFUSALS (never timeouts, only after Docker answered
|
> `internal/sockheal` — the controller exits after 60 s of socket REFUSALS (never timeouts, only after Docker answered
|
||||||
|
|||||||
@@ -0,0 +1,218 @@
|
|||||||
|
# REPORT — the app page in one column, and one image per version number (2026-10-15)
|
||||||
|
|
||||||
|
**A non-overwritten sibling of `REPORT.md`.** Two sessions released this repo on the same evening;
|
||||||
|
`REPORT.md` is per-session and overwritten, and it now holds v0.317.0's (the storage work). This
|
||||||
|
file holds the app-page arc so it stops being clobberable — the convention `felhom.eu/CLAUDE.md`
|
||||||
|
prescribes for parallel sessions, applied here.
|
||||||
|
|
||||||
|
## 1. Baselines
|
||||||
|
|
||||||
|
| Repo | `main` at start | Version at start |
|
||||||
|
|---|---|---|
|
||||||
|
| felhom-controller | `8339206` | v0.315.0 |
|
||||||
|
| felhom.eu | `340804f9` | docs only |
|
||||||
|
|
||||||
|
Architecture read before any claim: `02-controller-module-map.md` „The app page",
|
||||||
|
`09-update-architecture.md`, the `felhom-ui-design` skill, `CLAUDE.md` + `.claude/rules/*`.
|
||||||
|
Edited on the Windows workstation; built and tested on DooPlex in an isolated clone; the browser
|
||||||
|
work is on the workstation, which is why CC runs here.
|
||||||
|
|
||||||
|
## 2. PART 0 — the diagnosis, before any fix
|
||||||
|
|
||||||
|
**Verdict: (a) a cache.** Evidence: `felhom.eu/documentation/audits/app-page-2026-10-15b/P0/VERDICT.md`.
|
||||||
|
|
||||||
|
**(b) is ruled out.** Exactly one guest ran 0.315.0 — demo-hp 9201 — on digest `8887343011d6`,
|
||||||
|
identical to the registry's 0.315.0 at the time of measuring. The **global floor was 0.314.0** (read
|
||||||
|
from the hub's `/configuration`), so no box could have taken 0.315.0 by itself. demo-hp 9202 and
|
||||||
|
felhom-pve (N100) 9201 were both on 0.314.0; Tester 1 (`c11-appliance`) was unreachable and, by the
|
||||||
|
floor, cannot have had it.
|
||||||
|
|
||||||
|
**The mechanism, in four measured facts:**
|
||||||
|
|
||||||
|
1. `layout.html` asked for `/static/style.css?v={{.Version}}` → `?v=0.315.0` for **all three**
|
||||||
|
different 0.315.0 builds (`e66d466`, `fe0228c`, `db52f5a`); the first had no `.app-tabs` rules.
|
||||||
|
2. The origin sends **no validator**: on the box, `ETag present = 0`, `Last-Modified present = 0`.
|
||||||
|
A cached copy cannot be revalidated — only expire.
|
||||||
|
3. Cloudflare caches that URL (`cf-cache-status: HIT`, `age: 99 → 100` over three requests) and
|
||||||
|
**rewrites the browser TTL from the origin's 3600 to 14400** — four hours.
|
||||||
|
4. The session's first request returned **`cf-cache-status: EXPIRED`**, which only happens when the
|
||||||
|
edge holds an entry that has aged past its TTL.
|
||||||
|
|
||||||
|
**The caveat, stated rather than glossed:** origin, edge and box now agree byte-for-byte
|
||||||
|
(`sha256 c1774f63…`) and all carry the rules. The stale object itself is **no longer observable** —
|
||||||
|
that first probe forced its revalidation, which is what `EXPIRED` records — so no `HIT` with a bad
|
||||||
|
body can be produced. What is shown is every precondition, the proof an aged entry existed, and the
|
||||||
|
elimination of the only other candidate. **No cache was purged by hand.**
|
||||||
|
|
||||||
|
## 3. What shipped
|
||||||
|
|
||||||
|
| Area | What |
|
||||||
|
|---|---|
|
||||||
|
| Push-once | `build.sh` refuses `--push`/`--multiarch` for a tag already in the registry, before building. A registry it cannot reach is a refusal too. Local builds untouched. |
|
||||||
|
| Clean tree | `build.sh` also refuses a tree that is dirty, not at `origin/main`, or not a git checkout. Added after it was needed — see §6. |
|
||||||
|
| Asset tag | `assetTag()` hashes version + `GitCommit` + `BuildTime`; **all nine shells** use it (seven asked for `?v={{.Version}}`). Opaque 8 hex, because the stranger-facing share pages use the same value. `Cache-Control` unchanged — the new address is the fix. |
|
||||||
|
| Layout | The approved one-column mockup: 820px column, hairline sections, underlined tabs, no hero box, 200px label grid. Two boxes only: blue „the app is waiting for you", amber „this is risky". |
|
||||||
|
| Banner | The auto-update SUCCESS banner is meta text in the hero. Every banner that needs a decision is untouched above the tabs (R-571). |
|
||||||
|
| Leftovers | „2. mentés beállítása — <app>" and „<app> — Exportálás" removed; „Cím és kulcsok" with one address row replaces the duplicate disabled subdomain field; the „already installed, read-only" banner is now the hint under the fields; the install wizard gets the same back link, hero and column. |
|
||||||
|
|
||||||
|
## 4. Commits on `main`
|
||||||
|
|
||||||
|
`9cc7ffc` push-once + per-build asset tag · `7f3e58f` the one-column layout · `48d8674` v0.316.0
|
||||||
|
CHANGELOG + the rule-file fact · `006ceab` v0.316.1 (the tag reaches the dashboard) · `f908eee`
|
||||||
|
settings tab de-boxed · `9e68e52` two data-tab leftovers · `8c7aa10` v0.316.3 CHANGELOG · `f9151f0`
|
||||||
|
**the padding fix** · `4261a38` `FELHOM_REPO_DIR` + the build names its tree · `c6a5671` v0.316.4
|
||||||
|
the clean-tree gate · `e7b64af` `workspace/` gitignored.
|
||||||
|
felhom.eu: `b6638ac4` (design docs + the audit), `22cd7c51` (R-1080 closed, R-1081 filed).
|
||||||
|
|
||||||
|
## 5. Tests and red-proofs — every break seen failing, then reverted
|
||||||
|
|
||||||
|
| # | Break | Result |
|
||||||
|
|---|---|---|
|
||||||
|
| B1 | the registry check deleted | 5 of 6 cases fail; a present tag builds AND pushes |
|
||||||
|
| B2 | an unreachable registry treated as absent | the two unanswered-registry cases fail |
|
||||||
|
| B3 | the clean-tree gate deleted | all four of its cases fail |
|
||||||
|
| C1 | `assetTag` from the version only | `TestAssetTag_ChangesPerBuild` fails on both same-version cases |
|
||||||
|
| C2 | one shell back on `?v={{.Version}}` | `TestAssetTag_EveryShellUsesIt` fails naming layout.html |
|
||||||
|
| C3 | `addShellAssetData` removed from `executeTemplate` | `TestAssetTag_ReachesTheRenderedPage`: empty buster on four pages |
|
||||||
|
| D1 | the success banner restored | `TestAppPage_AutoUpdateSuccessIsMetaNotBanner` fails |
|
||||||
|
| D2 | one tab loses its column | `TestAppPage_OneColumnLayout` fails naming the tab |
|
||||||
|
| D3 | a section drawn as a card again | same test fails on two tabs |
|
||||||
|
| E | an informational section drawn as a blue callout | `TestAppPage_CalloutsOnlyForAskAndWarn` fails on both counts |
|
||||||
|
|
||||||
|
New: `scripts/test_build_push_once.sh` (**ten** cases, driving the real `build.sh` with a fake
|
||||||
|
`docker` on PATH — nothing is ever pushed),
|
||||||
|
`TestAssetTag_{ChangesPerBuild,EveryShellUsesIt,ReachesTheRenderedPage}`,
|
||||||
|
`TestAppPage_{OneColumnLayout,AutoUpdateSuccessIsMetaNotBanner,CalloutsOnlyForAskAndWarn}`.
|
||||||
|
|
||||||
|
Full gate: `go build ./... && go vet ./... && go test ./...` → **exit 0, 37 packages ok, zero
|
||||||
|
failures**, read from `go test`'s own exit code, not a pipeline's. All controller gates OK; 53
|
||||||
|
decoys behaved.
|
||||||
|
|
||||||
|
## 6. THREE INCIDENTS, one shape
|
||||||
|
|
||||||
|
All three are the same defect: **a guard that is not on the path the work actually takes.** Two of
|
||||||
|
them I caused while fixing the first.
|
||||||
|
|
||||||
|
**(i) I re-pushed 0.315.0 a fourth time.** The push-once guard went into
|
||||||
|
`controller/build.sh` in the repo; the documented release command runs
|
||||||
|
`$FELHOM_ROOT/build/felhom-controller/build.sh`, which was a **separate copy taken 2026-07-18** with
|
||||||
|
no guard. The first thing I did with the new refusal — run it against a real existing tag to prove
|
||||||
|
it fires — therefore rebuilt and re-pushed 0.315.0 with v0.316.0's code under it
|
||||||
|
(`8887343011d6` → `b809201841f7`). Root cause fixed: the build directory's script is a symlink to
|
||||||
|
the repo's, the stale copy kept as `build.sh.stale-copy-2026-07-18`, and the refusal then proven
|
||||||
|
from the documented path. **R-1081.**
|
||||||
|
|
||||||
|
**(ii) The asset tag shipped dead in 0.316.0.** Every shell asked for `?v={{.AssetTag}}` and the
|
||||||
|
template test passed, but `addShellAssetData` was only ever called by `executeTemplateLang` — the
|
||||||
|
stranger-facing pages. The dashboard path had never needed it, because `layout.html` used to ask for
|
||||||
|
`{{.Version}}`, which `baseData` supplies. The first live load rendered `/static/style.css?v=` —
|
||||||
|
**empty, which is a constant, and a constant busts nothing.** Found in a browser. Fixed in 0.316.1;
|
||||||
|
`TestAssetTag_ReachesTheRenderedPage` now asserts the rendered value, not the markup.
|
||||||
|
|
||||||
|
**(iii) Building 0.316.3 published another session's unreleased work.** The symlink from (i) points
|
||||||
|
into the shared clone's **working copy**, which predated the `FELHOM_REPO_DIR` override — so the
|
||||||
|
override was silently ignored and the build copied the shared tree, which held 31 uncommitted files
|
||||||
|
of the physical-disk storage work. The banner said `Commit: 0225255` with no `Repo:` line; the
|
||||||
|
evidence was on screen and the image was already pushed. **Nobody deployed it — that was luck, not a
|
||||||
|
control.** The clean-tree rule had existed only as a sentence in a runbook. It is now two questions
|
||||||
|
the build asks and refuses on, plus a refusal for a source that is not a git checkout at all; it
|
||||||
|
immediately caught its own next build (the scratch `workspace/` beside the script, now gitignored).
|
||||||
|
|
||||||
|
**`0.316.3` must never be deployed.** It is neither re-pushed nor deleted: a version number is
|
||||||
|
pushed once, and that applies to a number I spoiled.
|
||||||
|
|
||||||
|
## 7. Deployed, and what happened to 0.316.4
|
||||||
|
|
||||||
|
**demo-hp guest 9201 runs `0.317.0`, healthy.** That is the other session's release, built from
|
||||||
|
`main` at a commit that contains all of this work — verified: `f9151f0` (the padding fix) and
|
||||||
|
`c6a5671` (the clean-tree gate) are both ancestors of it.
|
||||||
|
|
||||||
|
**`0.316.4` was built but never published, and was then dropped.** Its first build attempt was
|
||||||
|
refused by its own new clean-tree gate (the `workspace/` directory); by the time that was fixed,
|
||||||
|
`0.317.0` was already in the registry. Publishing 0.316.4 would have put a *lower* number in the
|
||||||
|
registry carrying nothing 0.317.0 does not already have. The household's button offers the highest
|
||||||
|
tag, so it would have been invisible anyway.
|
||||||
|
|
||||||
|
**The floor stays 0.314.0** — raising it needs all three test boxes and a green box walk, and this
|
||||||
|
evening two sessions released the same component.
|
||||||
|
|
||||||
|
| tag | state |
|
||||||
|
|---|---|
|
||||||
|
| 0.316.0 / .1 / .2 | published, superseded |
|
||||||
|
| **0.316.3** | published, **CONTAMINATED — never deploy** |
|
||||||
|
| 0.316.4 | never published (superseded) |
|
||||||
|
| **0.317.0** | published, deployed on demo-hp, carries this work |
|
||||||
|
|
||||||
|
## 8. The browser check, through the PUBLIC address
|
||||||
|
|
||||||
|
Chrome on the workstation, `https://felhom.enkisfelhom.hu`, **normal loads — no hard refresh**:
|
||||||
|
|
||||||
|
- The stylesheet URL is a real 8-hex per-build tag and the loaded sheet carries the `.app-tabs`
|
||||||
|
rules. **This is the fix working:** before it, the same page needed a hand-forced refetch.
|
||||||
|
- `.app-tab-active` computes `border-bottom: 2px rgb(46,168,245)` (`--blue-bright`); column
|
||||||
|
`max-width: 820px`; hero `border-top-width: 0px`.
|
||||||
|
- Across settings / data / guide / logs / plex / grocy / install: **1 column each, 1 `aria-current`
|
||||||
|
on an installed app and 0 on a not-installed one, 0 `.app-info-card`, 0 success banners.**
|
||||||
|
- Data tab: exactly **1 amber callout** (the same-disk warning). Settings, guide, grocy: none —
|
||||||
|
correct, nothing is asked and nothing is risky.
|
||||||
|
- **After the operator's report:** `.app-page` padding `0px 0px 32px`, `.content` padding `32px`,
|
||||||
|
measured gap **32px from the sidebar** (was 80) and **36px from the top** (was 64+).
|
||||||
|
- **Console clean on a fresh load**, on 0.316.2 and again on 0.317.0.
|
||||||
|
|
||||||
|
Screenshots: `felhom.eu/documentation/audits/app-page-2026-10-15b/browser/` —
|
||||||
|
`01-settings-boxes-still-there`, `02-settings-one-column-0.316.2`, `03-data-tab-amber-callout`,
|
||||||
|
`04-guide-tab-padding-fixed-0.317.0`.
|
||||||
|
|
||||||
|
**Scenario E's blue callout was NOT exercised live.** Plex's setup gate is open (the operator's real
|
||||||
|
claim, R-1060), so `Needed()` is false and the card is correctly hidden. Showing it live would mean
|
||||||
|
un-claiming the operator's real Plex server; not done. The branch is covered by
|
||||||
|
`TestAppPage_CalloutsOnlyForAskAndWarn` against a harness Plex with a closed gate.
|
||||||
|
|
||||||
|
## 9. Parity fixtures
|
||||||
|
|
||||||
|
Recaptured (the pages this task restyles): `app_settings_*` ×21, `app_data_*` ×9, `app_guide_*` ×4,
|
||||||
|
`app_logs`, `deploy_new{,_blocked,_memory_blocked}`. **All other fixtures are byte-identical** — and
|
||||||
|
now permanently independent of build identity: the harness normalises the asset tag on **both sides**
|
||||||
|
of the comparison, as it already did for the per-session CSRF token, so a build can no longer churn
|
||||||
|
148 files. The same normalisation was applied at the second comparison site in `i18n_wiring_test.go`,
|
||||||
|
which had the same assumption.
|
||||||
|
|
||||||
|
## 10. NOT yet validated
|
||||||
|
|
||||||
|
1. **The operator's own look** at AdventureLog and Plex on demo-hp through the public address. The
|
||||||
|
layout judgement is theirs. (The padding complaint from the first look is fixed and live.)
|
||||||
|
2. **A blue callout in a real browser** (§8).
|
||||||
|
3. **A catalog guide rendered from a real template** — no template carries `app_info.guide` yet.
|
||||||
|
|
||||||
|
## 11. Teardown — three layers
|
||||||
|
|
||||||
|
- **Machine:** nothing provisioned, no app installed, no throwaway Plex. Probe scripts, fetched
|
||||||
|
pages and the password file removed from guest 9201, demo-hp and DooPlex `/tmp`; the dashboard
|
||||||
|
password went file→file, was never printed, and no copy reached Windows or git.
|
||||||
|
- **Host:** both scratch clones and the `felhom.eu` sibling symlink deleted. The shared DooPlex
|
||||||
|
checkout was never written to by me — which is how the other session's work was distinguishable
|
||||||
|
from mine. `build.sh` in the build directory is now a symlink to the repo's (deliberate), with the
|
||||||
|
stale July copy kept beside it.
|
||||||
|
- **Hub:** nothing created; no floor change.
|
||||||
|
|
||||||
|
## 12. Observations
|
||||||
|
|
||||||
|
- **FILED: R-1081** — the registry's `0.315.0`, and now also `0.316.3`, hold content that is not
|
||||||
|
what their numbers say. Both caused by this session; both fixed at the root; no box affected.
|
||||||
|
- **NOT-A-FINDING (fixed in session):** the asset tag shipped dead — incident (ii).
|
||||||
|
- **NOT-A-FINDING (fixed in session):** the clean-tree rule had no mechanism — incident (iii).
|
||||||
|
- **NOT-A-FINDING (fixed in session):** `app_row_dedup_gate` convicted my `.app-row`, correctly —
|
||||||
|
that class already means „a row in the app list". Renamed `.app-field-row`; an over-broad rename
|
||||||
|
briefly took the list's own rule with it and was restored.
|
||||||
|
- **NOT-A-FINDING (fixed in session):** the one-column padding doubled against `.content`'s own
|
||||||
|
2rem. The mockup's numbers were the total the page should show, not an amount to add.
|
||||||
|
- **NOT-A-FINDING:** `build.sh`'s `workspace/` dirtied any clone it was run from; gitignored.
|
||||||
|
- **Register: 169 before → 170 after; 1 opened (R-1081), 1 opened-and-closed (R-1080).**
|
||||||
|
- **System poster:** no fact in `felhom-system-poster.facts.md` changed. Neither file edited.
|
||||||
|
- **Instruction files:** `.claude/rules/unprompted-work.md` item 6 in **all four** versioned copies
|
||||||
|
gains „a version number is pushed once", stated as a fact about what the build now enforces, not
|
||||||
|
as a new rule. The workspace-root copy is unversioned and not on this machine.
|
||||||
|
- **Worth the operator's attention:** two sessions released this repo within an hour, and the
|
||||||
|
second overwrote the first's `REPORT.md`. This file is the workaround; whether `REPORT.md` should
|
||||||
|
stay a single overwritten file in a repo two sessions can release is a question for the operator,
|
||||||
|
not a change I should make unasked.
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# REPORT — controller v0.346.1: traefik v3.7.16, the file manager 1.5.8-stable, cloudflared 2026.10.4 (security), 2026-10-27 (attended)
|
||||||
|
|
||||||
|
> A sibling of `REPORT.md`, not an overwrite: the release session of the same day (v0.346.0) owns `REPORT.md`.
|
||||||
|
|
||||||
|
## In plain words
|
||||||
|
|
||||||
|
- **What:** three box programs had public security notices: traefik (12 notices, none reaching our config), the file
|
||||||
|
manager (a TOTP re-enrolment and an upload-share flaw; 1.5.7 is skipped, it broke TOTP sign-ins) and cloudflared
|
||||||
|
(debug endpoints on its metrics server, not reachable from outside). Controller **0.346.1** = the released 0.346.0
|
||||||
|
(`b1b9be3`) + only the three new pins.
|
||||||
|
- **How a box takes them:** the reconcile at start recreates each container on its new image (traefik pinned by the new
|
||||||
|
test `TestEnsureTraefik_ANewImageRecreatesTraefik`, red-proved).
|
||||||
|
|
||||||
|
## Gates
|
||||||
|
|
||||||
|
`controller_gates.py` (full) green; `go test ./...` green (41 packages); `go build`, `go vet` green.
|
||||||
|
|
||||||
|
Evidence and the box proofs: felhom.eu `documentation/audits/security-app-updates-2026-10-27/part5/`. Register:
|
||||||
|
felhom.eu R-1304 (traefik), R-1305 (file manager).
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# REPORT — controller v0.345.1: cloudflared 2026.10.3 (security), 2026-10-26 evening (attended)
|
||||||
|
|
||||||
|
> A sibling of `REPORT.md`, not an overwrite: the night session (D53, R-1218/1219/1220) owns `REPORT.md` tonight and
|
||||||
|
> writes into this repo at the same time.
|
||||||
|
|
||||||
|
## In plain words
|
||||||
|
|
||||||
|
- **What:** Cloudflare said on 2026-10-20 that cloudflared before 2026.10.2 trusts eight bad certificate issuers
|
||||||
|
(eMudhra, weak keys). Every Felhom box ran cloudflared 2026.9.3 in its guest. Controller **0.345.1** = the released
|
||||||
|
0.345.0 + only the new cloudflared pin `2026.10.3`. Nothing from tonight's `main` is in it.
|
||||||
|
- **Did it work:** yes. Every box with a tunnel (Tester 1, demo-hp, demo-felhom) runs controller 0.345.1 and cloudflared
|
||||||
|
2026.10.3, healthy; the hub says „running (connected)" for all three; all 29 public names still redirect http → https.
|
||||||
|
Tester4 moved to 0.345.1 by the global floor (it has no tunnel). Tester 2 has no box.
|
||||||
|
- **Gaps:** the tunnel was down about 2 s (Tester 1), 4 s (demo-felhom) and 11 s (demo-hp) while cloudflared restarted.
|
||||||
|
|
||||||
|
## What changed
|
||||||
|
|
||||||
|
| Where | What |
|
||||||
|
|---|---|
|
||||||
|
| tag `v0.345.1` = `f3204024` (on `6bfb784`) | `infra.CloudflaredImage` → `cloudflare/cloudflared:2026.10.3`; test `TestEnsureCloudflared_ANewImageRecreatesTheTunnel`; CHANGELOG entry |
|
||||||
|
| `main` `a1c65b3d` | the same change, plus `build.sh`: a `--push` may build from the pushed tag `v<VERSION>` when it is HEAD (operator's yes, this session); 4 new cases in `scripts/test_build_push_once.sh` |
|
||||||
|
|
||||||
|
- Red-proofs: the new reconcile test failed with the „compose changed" check removed; the build cases failed both ways
|
||||||
|
(tag branch accepting anything: 4 of 20 fail; tag branch removed: 1 of 20 fails).
|
||||||
|
- Gates `--fast` green on both commits; `go test ./...` green on the tag commit (`internal/stacks` 450 s under the night
|
||||||
|
session's load). CI by commit: `a1c65b3d` job 2392 success; `f3204024` job 2393 success (run_attempt 1 each).
|
||||||
|
- Image `gitea.dooplex.hu/admin/felhom-controller:0.345.1` (and `:latest`) digest
|
||||||
|
`sha256:7cfdf7e1f835628de9c7d536e0a60c06bad5bbe19e8133765cc0a6bb732dbff6`, built from `f3204024`.
|
||||||
|
- cloudflared image index digest `sha256:faa8e0a1475f137c910be6025f43c8e4092fdd35461b31e19fd1390657a1ff39`.
|
||||||
|
- How a box takes it: `controller/internal/stacks/infra.go` `ensureCloudflared` — the rendered compose differs (the
|
||||||
|
`image:` line) → `compose up -d` recreates the container. Seen on all three boxes: `[infra] cloudflared compose
|
||||||
|
changed … recreating cloudflared` 1–2 s after `[selfupdate] Post-update startup: update successful (0.345.0 → 0.345.1)`.
|
||||||
|
|
||||||
|
## For the night session
|
||||||
|
|
||||||
|
`main` carries the bump (`a1c65b3d`). Your next release from `main` keeps cloudflared 2026.10.3 — no action needed.
|
||||||
|
Your CHANGELOG „Unreleased" block is unchanged; the v0.345.1 section sits between it and v0.345.0.
|
||||||
|
|
||||||
|
Evidence: felhom.eu `documentation/audits/cloudflared-2026.10.3-2026-10-26/`. Register: R-1300 (closed), R-1301
|
||||||
|
(opened). Full session report: felhom.eu `REPORT-cloudflared-2026-10-26.md`.
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# REPORT — the security watch's pin list (felhom.eu R-1303), 2026-10-26 night
|
||||||
|
|
||||||
|
> A sibling of `REPORT.md` (the night session owns it tonight). The full report: felhom.eu
|
||||||
|
> `REPORT-security-watch-2026-10-26.md`.
|
||||||
|
|
||||||
|
- **What changed here:** every pin now names where its security notices are published, and a push gate (`upstream`,
|
||||||
|
`--fast`) refuses a pin without one. The rule and its reader are shared: felhom.eu `scripts/security_watch_inventory.py`.
|
||||||
|
Decoys for the gate were red-proved with a reader that reads comment lines.
|
||||||
|
- **Why:** the nightly security watch (felhom.eu `scripts/security_watch.py`, CI 03:40 UTC) reads these lines. No
|
||||||
|
runtime change: nothing on a box changes, nothing is released.
|
||||||
|
- **First run:** see felhom.eu `documentation/audits/security-watch-2026-10-26/ADVISORIES-2026-10-26.md` and rows
|
||||||
|
R-1304 (traefik), R-1305 (the file manager), R-1306 (27 apps).
|
||||||
@@ -1,11 +1,14 @@
|
|||||||
# REPORT — controller v0.297.0 (2026-10-05, burn-down round 2)
|
# REPORT — controller 0.354.0 (2026-11-19)
|
||||||
|
|
||||||
Full session report: `felhom.eu/REPORT-burndown2-2026-10-05.md`. Baseline `114ff27` (v0.296.0). **MinAgent 0.131.0**.
|
Released in the attended run of 2026-11-19 (release 4). The full report is felhom.eu `REPORT-release-4-2026-11-19.md`.
|
||||||
|
|
||||||
24 rows fixed (see the CHANGELOG entry), plus two small twins found on the way (the banner countdown at 0 days; the rest
|
- **What:** the off-site copies of a removed app end 30 days after „delete backup data”; the remove dialog names the
|
||||||
of `deepCopyStack`'s shared references). R-126 and R-325 NOT done: R-126 needs an operator choice between two options;
|
day (and shows the older sentence about the nightly snapshots only where no day is shown); the Backups page marks
|
||||||
R-325 needs a same-step change in felhom.eu's `hub_copy_gate.py`. Tests + red-proofs:
|
the app with „keep it after all”; „delete in 30 days” for a removed app with copies and no mark. The household's
|
||||||
`felhom.eu/documentation/audits/burndown2-2026-10-05/controller-red-proofs.txt`.
|
notice is sent by the hub (≥ 0.183.0), not by the box.
|
||||||
|
- **Image:** `sha256:c88522ed…`, from `440711b`, CI run 2713. MinAgent 0.158.1 (unchanged).
|
||||||
`go build/vet/test ./...` green; `controller_gates.py --fast` green (incl. the new gofmt gate). Image, golden and
|
- **Proof:** rc.1 on demo-hp's guest 9201 (the test household): the press, the take-back, a second press and an
|
||||||
delivery: see the session report.
|
address change, each seen on the box, on the hub and in the inbox. The removal itself is first seen on 2026-12-22.
|
||||||
|
- **Floors:** tester-1 and demo-hp per box 09:29 UTC; global 09:32:18 UTC; the N100 by the floor at 09:32. Box walk
|
||||||
|
green on all three; per-box floors cleared.
|
||||||
|
- **Golden:** 0.354.0 baked and vouched 2026-11-19.
|
||||||
@@ -20,6 +20,7 @@
|
|||||||
| `appbackup.ValidateRelPath` / `ValidRoot` | controller/internal/appbackup/classify.go | `(root, path)` / `(root)` | THE single path-safety refusal set for every `${VAR}`-relative catalog path | Shared by `backup:` and `data_paths:`. **Do not write a second path validator.** |
|
| `appbackup.ValidateRelPath` / `ValidRoot` | controller/internal/appbackup/classify.go | `(root, path)` / `(root)` | THE single path-safety refusal set for every `${VAR}`-relative catalog path | Shared by `backup:` and `data_paths:`. **Do not write a second path validator.** |
|
||||||
| `stacks.ValidateDataPaths` | controller/internal/stacks/datapaths.go | `(entries, binds, appName, logger)` | `data_paths:` annotation validation | ASYMMETRIC on purpose (Fork-3): malformed PATH ⇒ whole-block reject (data handling, `backup:` precedent); unknown ROLE ⇒ fails OPEN, one WARN (presentation, `Lifecycle` precedent). |
|
| `stacks.ValidateDataPaths` | controller/internal/stacks/datapaths.go | `(entries, binds, appName, logger)` | `data_paths:` annotation validation | ASYMMETRIC on purpose (Fork-3): malformed PATH ⇒ whole-block reject (data handling, `backup:` precedent); unknown ROLE ⇒ fails OPEN, one WARN (presentation, `Lifecycle` precedent). |
|
||||||
| `web.fileBrowserLink` / `importFolderLink` | controller/internal/web/filebrowser_link.go | `(domain, sourceName, relPath)` | FileBrowser Quantum deep link | Template read out of the shipped router (SPIKE P2). **`url.PathEscape` per segment — NEVER `QueryEscape`** (space→`+` is a literal plus in a path). Let `html/template` do the attribute escaping; do not pre-escape. |
|
| `web.fileBrowserLink` / `importFolderLink` | controller/internal/web/filebrowser_link.go | `(domain, sourceName, relPath)` | FileBrowser Quantum deep link | Template read out of the shipped router (SPIKE P2). **`url.PathEscape` per segment — NEVER `QueryEscape`** (space→`+` is a literal plus in a path). Let `html/template` do the attribute escaping; do not pre-escape. |
|
||||||
|
| `web.fileBrowserOpenLink` · `web.ServeFilesOpen` / `ServeFilesAuth` · `infra.LoadOrCreateFileBrowserSSOHeader` / `FileBrowserSSOFor` (v0.332.0, R-1100) | controller/internal/web/filebrowser_link.go · controller/internal/web/files_sso.go · controller/internal/infra/filebrowser_sso.go | `(domain, sourceName, relPath)` · handlers · `(dataDir[, domain])` | A dashboard link to a FileBrowser folder that opens it signed in (the one sign-in) | **Every dashboard folder link uses `fileBrowserOpenLink`** (through `/__files/open`), never `fileBrowserLink` raw. The header NAME is the box's secret: only FileBrowser's config and traefik's route carry it — never a log, a page or a report. Never widen the dashboard cookie; the files cookie is derived per host from the session fingerprint (the R-976 shape) |
|
||||||
| `HumanizeBytes` | controller/internal/appbackup/appdata.go | `(b int64) string` | Human byte sizes | Exported canonical; private clones exist (§6) |
|
| `HumanizeBytes` | controller/internal/appbackup/appdata.go | `(b int64) string` | Human byte sizes | Exported canonical; private clones exist (§6) |
|
||||||
| `stablePathForName` / `agentWhere` | controller/internal/web/intermediary.go | `(name/registeredPath) string` | Map registry stable path `/mnt/felhom-drives/<n>` ↔ raw agent mount | Registry stores STABLE path; agent ops take the RAW mount — always convert |
|
| `stablePathForName` / `agentWhere` | controller/internal/web/intermediary.go | `(name/registeredPath) string` | Map registry stable path `/mnt/felhom-drives/<n>` ↔ raw agent mount | Registry stores STABLE path; agent ops take the RAW mount — always convert |
|
||||||
| `offsiteRestoreRootFor` | controller/internal/backup/offbox_verify_copies.go | `(drivePath string) string` | THE only place `backups/offsite-restore` is spelled | `offboxRestoreScratchDir` builds on it — the listing/delete surface MUST resolve byte-identical paths to what the restore wrote. Do not re-hardcode the segments (they were open-coded in 3 places before v0.147.0) |
|
| `offsiteRestoreRootFor` | controller/internal/backup/offbox_verify_copies.go | `(drivePath string) string` | THE only place `backups/offsite-restore` is spelled | `offboxRestoreScratchDir` builds on it — the listing/delete surface MUST resolve byte-identical paths to what the restore wrote. Do not re-hardcode the segments (they were open-coded in 3 places before v0.147.0) |
|
||||||
@@ -28,13 +29,14 @@
|
|||||||
| `stacks.RunAfterInstall` / `expandAfterInstall` / `web.defaultLoginInEffect` (v0.279.0, decision 45) | controller/internal/stacks/after_install.go · controller/internal/web/known_login.go | `(name, wait)` / `(cmd, allowed, env)` / `(meta, cfg, installed)` | A fresh install replaces a known default login; the page says when a default is still in effect | **Only from the deploy-done hook** — never after a restore/kept load (R-694). A `success:` marker is required (exit 0 lies). Never log the expanded command |
|
| `stacks.RunAfterInstall` / `expandAfterInstall` / `web.defaultLoginInEffect` (v0.279.0, decision 45) | controller/internal/stacks/after_install.go · controller/internal/web/known_login.go | `(name, wait)` / `(cmd, allowed, env)` / `(meta, cfg, installed)` | A fresh install replaces a known default login; the page says when a default is still in effect | **Only from the deploy-done hook** — never after a restore/kept load (R-694). A `success:` marker is required (exit 0 lies). Never log the expanded command |
|
||||||
| `stacks.OpenSetupGate` / `SetupGateTick` / `SetupGateHost` · `web.ServeGateAuth` / `ServeGateStart` (v0.280.0, decision 46) | controller/internal/stacks/setup_gate.go · controller/internal/web/setup_gate.go | `(name, by)` / `()` / `(host)` · handlers | The setup gate: a `setup_gate: true` install is closed to everyone but the household until its probe or the household's press opens it | **Write the gate BEFORE the first start** (spike F2). Open = record first, then remove the file. Never widen the dashboard cookie — the handshake mints a host-bound one-use token |
|
| `stacks.OpenSetupGate` / `SetupGateTick` / `SetupGateHost` · `web.ServeGateAuth` / `ServeGateStart` (v0.280.0, decision 46) | controller/internal/stacks/setup_gate.go · controller/internal/web/setup_gate.go | `(name, by)` / `()` / `(host)` · handlers | The setup gate: a `setup_gate: true` install is closed to everyone but the household until its probe or the household's press opens it | **Write the gate BEFORE the first start** (spike F2). Open = record first, then remove the file. Never widen the dashboard cookie — the handshake mints a host-bound one-use token |
|
||||||
| `stacks.OpenSignupWindow` / `SignupBlocked` / `SetupGateProbe` · `web.ServeSignupClosed` (v0.281.0, decision 47) | controller/internal/stacks/signup_block.go · controller/internal/web/setup_gate.go | `(name)` | Sign-up closed at the app's own address once the gate opens; the household's 15-minute window; the press asks the probe | **The block goes up BEFORE the gate comes down** (a failed write keeps the gate closed). Never on an app this box did not gate |
|
| `stacks.OpenSignupWindow` / `SignupBlocked` / `SetupGateProbe` · `web.ServeSignupClosed` (v0.281.0, decision 47) | controller/internal/stacks/signup_block.go · controller/internal/web/setup_gate.go | `(name)` | Sign-up closed at the app's own address once the gate opens; the household's 15-minute window; the press asks the probe | **The block goes up BEFORE the gate comes down** (a failed write keeps the gate closed). Never on an app this box did not gate |
|
||||||
| `family.Store` · `stacks.FamilyGateHost` / `familyGateTick` / `FamilyExceptRegexp` · `web.ServeFamilyGateAuth` / `ServeFamilyStart` / `ServeFamilyLogin` / `ServeFamilyLogout` (v0.287.0, decisions 63/64) | controller/internal/family/family.go · controller/internal/stacks/family_gate.go · controller/internal/web/family_gate.go | store `Add/Reset/Remove/Verify/NewSession/Valid/EndSession` · `(host)` / `()` / `(prefix)` · handlers | The PERMANENT family gate: family members with their own logins in front of a `family_gate: true` app | **A family cookie never opens the dashboard** (RequireAuth reads only `felhom_session`); the app cookie names a STORE session, so the store is asked on every request (reset/remove/logout end access at once); **every exception goes through `FamilyExceptRegexp`** (anchored — never a hand-written PathPrefix); door written before the first start, like the setup gate. `familyStoreOverride` is the test seam. Fifth atomic-write helper (family.json, fsync) — see §6 |
|
| `family.Store` · `stacks.FamilyGateHost` / `familyGateTick` / `FamilyExceptRegexp` · `web.ServeFamilyGateAuth` / `ServeFamilyStart` / `ServeFamilyLogin` / `ServeFamilyLogout` (v0.287.0, decisions 63/64) | controller/internal/family/family.go · controller/internal/stacks/family_gate.go · controller/internal/web/family_gate.go | store `Add/AddPerson/People/Reset/Remove/Verify/NewSession/HouseholdSession/Valid/EndSession/Find/EndAll` + `family.Fingerprint` + `family.LoginFrom` · `(host)` / `()` / `(prefix)` · handlers | The PERMANENT family gate: family members with their own logins in front of a `family_gate: true` app | **A family cookie never opens the dashboard** (RequireAuth reads only `felhom_session`); the app cookie carries a token DERIVED per app host from a STORE session (`familyAppToken`, R-976 — never the session id itself), so the store is asked on every request (reset/remove/logout end access at once); **every exception goes through `FamilyExceptRegexp`** (anchored — never a hand-written PathPrefix); door written before the first start, like the setup gate. `familyStoreOverride` is the test seam. Fifth atomic-write helper (family.json, fsync) — see §6. **R-1112: a session is stored as its FINGERPRINT (`Session.FP`, the R-35 shape), never the cookie value** — `NewSession` returns the value once; `Valid`/`EndSession` take the value and hash it; `Find` and `familyAppToken` work on the fingerprint. An old file (`"id"` = the value) is converted and rewritten in `Open`; a failed rewrite is an error. **R-1113: the household path uses `HouseholdSession`** (its live session, a new one only past half its life) — never `NewSession("")` per pass. **W12: a typed name goes through `AddPerson` (keeps the display, makes the login with `LoginFrom`, numbers a taken login); `Add` stays the strict login-only primitive. Any place that turns a typed member name into a login calls `LoginFrom` — never a second fold table** |
|
||||||
| `stacks.OpenInstallHold` / `installHoldTick` (v0.284.0, R-741) | controller/internal/stacks/install_hold.go | `(name, by)` / `()` | An `after_install` app held behind the setup gate's door until its known login is replaced | **Written before the first start**, like the gate; opens on `after_install` success or the household's "I changed it"; the door (`SetupGateHost`) reads holds first |
|
| `stacks.OpenInstallHold` / `installHoldTick` (v0.284.0, R-741) | controller/internal/stacks/install_hold.go | `(name, by)` / `()` | An `after_install` app held behind the setup gate's door until its known login is replaced | **Written before the first start**, like the gate; opens on `after_install` success or the household's "I changed it"; the door (`SetupGateHost`) reads holds first |
|
||||||
| `stacks.RetainImagesAfterUpdate` / `RetainImagesAfterRemove` / `RunImageRetentionOnce` (→ `(deleted, done)` since v0.294.0) / `RunImageRetentionOnceUntilDone` · seam `imageDocker` (v0.284.0, decision 53) | controller/internal/stacks/image_retention.go | `(name, previous)` / `(name, repos)` / `()` | Deletes an app's images older than its running + previous one | **The keep set is box-wide and read at delete time** (containers, installed composes, installed/previous records); exact id, never forced or pruned; skipped while any update runs AND while any image-pulling compose command runs (R-863, `dockerexec.TryImageCleanup`); the one-time pass writes its marker only after a pass that RAN; tests use the `imageDocker` seam, never Docker |
|
| `stacks.RetainImagesAfterUpdate` / `RetainImagesAfterRemove` / `RunImageRetentionOnce` (→ `(deleted, done)` since v0.294.0) / `RunImageRetentionOnceUntilDone` · seam `imageDocker` (v0.284.0, decision 53) | controller/internal/stacks/image_retention.go | `(name, previous)` / `(name, repos)` / `()` | Deletes an app's images older than its running + previous one | **The keep set is box-wide and read at delete time** (containers, installed composes, installed/previous records); exact id, never forced or pruned; skipped while any update runs AND while any image-pulling compose command runs (R-863, `dockerexec.TryImageCleanup`); the one-time pass writes its marker only after a pass that RAN; tests use the `imageDocker` seam, never Docker |
|
||||||
| `dockerexec.BeginImageWork(args)` / `TryImageCleanup()` / `ImagePulling(args)` (v0.294.0, R-863) | controller/internal/dockerexec/imagework.go | `defer dockerexec.BeginImageWork(args)()` | **Every NEW place that runs `compose up/pull/create/run` must hold it** (the stacks compose helpers, appexport's restore and the FileBrowser sync already do) | An image pulled by compose is named by no container until compose creates one; a clean-up pass in that window deleted it (measured, R-863). The pass takes the lock exclusively without waiting; pulling commands wait for a running pass (seconds) |
|
| `dockerexec.BeginImageWork(args)` / `TryImageCleanup()` / `ImagePulling(args)` (v0.294.0, R-863) | controller/internal/dockerexec/imagework.go | `defer dockerexec.BeginImageWork(args)()` | **Every NEW place that runs `compose up/pull/create/run` must hold it** (the stacks compose helpers, appexport's restore and the FileBrowser sync already do) | An image pulled by compose is named by no container until compose creates one; a clean-up pass in that window deleted it (measured, R-863). The pass takes the lock exclusively without waiting; pulling commands wait for a running pass (seconds) |
|
||||||
| `nightchain.Ledger` / `CatchUp` / `ResumeWatch` / `ComputeBanner` (v0.295.0, R-871) | controller/internal/nightchain/ | `Open(path, now)`, `MarkEnded(leg, t)`, `Missed(now, W, loc)`, `Evaluate(ctx, why)` | "was a night missed?" and making it up; the missed-backup banner's rule | The ledger is an ATTEMPT record (ran to its end) — never evidence a backup exists; a NEW nightly backup leg must be wrapped by `withLeg` in main.go and listed in `nightchain.Order`, or the catch-up never makes it up; never add the update leg to `catchUpLegs` |
|
| `nightchain.Ledger` / `CatchUp` / `ResumeWatch` / `ComputeBanner` (v0.295.0, R-871) | controller/internal/nightchain/ | `Open(path, now)`, `MarkEnded(leg, t)`, `Missed(now, W, loc)`, `Evaluate(ctx, why)` | "was a night missed?" and making it up; the missed-backup banner's rule | The ledger is an ATTEMPT record (ran to its end) — never evidence a backup exists; a NEW nightly backup leg must be wrapped by `withLeg` in main.go and listed in `nightchain.Order`, or the catch-up never makes it up; never add the update leg to `catchUpLegs` |
|
||||||
| `scheduler.DailyLateLimit` (v0.295.0) | controller/internal/scheduler/scheduler.go | — | a daily timer firing > 60 min late (host suspend) is skipped | do not "fix" a late fire by running it: the app-update leg would run at noon |
|
| `scheduler.DailyLateLimit` (v0.295.0) | controller/internal/scheduler/scheduler.go | — | a daily timer firing > 60 min late (host suspend) is skipped | do not "fix" a late fire by running it: the app-update leg would run at noon |
|
||||||
| `stacks.RetainControllerImages(ControllerImageRecord)` · `selfupdate.UpdateState.RecordedPrevious` (v0.285.0, decision 56) | controller/internal/stacks/controller_image_retention.go | `({Repo, Running, Previous})` | Deletes controller images older than the running + previous one | The previous comes from the SWAP RECORD (success onto the running version), version order only as the fallback; versions above the running one and non-version tags are kept; skipped while the controller swaps itself; same `imageDocker` seam |
|
| `stacks.RetainControllerImages(ControllerImageRecord)` · `selfupdate.UpdateState.RecordedPrevious` (v0.285.0, decision 56) | controller/internal/stacks/controller_image_retention.go | `({Repo, Running, Previous})` | Deletes controller images older than the running + previous one | The previous comes from the SWAP RECORD (success onto the running version), version order only as the fallback (a release preferred over a test build, v0.351.0); versions above the running one and non-version tags (`latest`) are kept — an `-rc` tag IS a version (`util.ParseVersionPre`) since v0.351.0; skipped while the controller swaps itself; same `imageDocker` seam |
|
||||||
|
| `stacks.RetainInfraImages(pins)` / `RunInfraImageRetention(ctx, pins, every, tries)` (v0.351.0, decision 285) | controller/internal/stacks/infra_image_retention.go | `(infra.Images())` | Deletes pinned infra images older than the pin + the previous pin | Per repository: the pin, newer versions, the previous pin and in-use images stay; untagged unused go; non-version tags stay; skipped (errImageRetentionBusy) while an app pulls (R-863) or the controller swaps; same `imageDocker` seam |
|
||||||
| `stacks.CloseSignupNow` / `CloseSignupOffered` / `applyNativeLock` (v0.282.0, decisions 47/49) | controller/internal/stacks/after_setup.go | `(name)` | The app's own sign-up switch after the setup; "close sign-up now" for an app installed before the rule | **Check the installed compose reads the variable** (an old install carries the old compose until its next update) — never record a lock that is not there. One run per app at a time (`nativeLockBusy`) |
|
| `stacks.CloseSignupNow` / `CloseSignupOffered` / `applyNativeLock` (v0.282.0, decisions 47/49) | controller/internal/stacks/after_setup.go | `(name)` | The app's own sign-up switch after the setup; "close sign-up now" for an app installed before the rule | **Check the installed compose reads the variable** (an old install carries the old compose until its next update) — never record a lock that is not there. One run per app at a time (`nativeLockBusy`) |
|
||||||
| `backup.judgeCopy` / `HollowCopies` / `SetHollowCopyNotify` (Part D, v0.279.0) | controller/internal/backup/hollow_watch.go | `(app, tier, unitDir)` | A RUNNING app whose newest copy holds no data → operator digest once/day + page sentence | Uses `unitCarriesData` (the manifest, never size); a stopped held app is never flagged |
|
| `backup.judgeCopy` / `HollowCopies` / `SetHollowCopyNotify` (Part D, v0.279.0) | controller/internal/backup/hollow_watch.go | `(app, tier, unitDir)` | A RUNNING app whose newest copy holds no data → operator digest once/day + page sentence | Uses `unitCarriesData` (the manifest, never size); a stopped held app is never flagged |
|
||||||
| `web.nightChain` (R-705, v0.279.0) | controller/internal/web/night_chain.go | `POST /api/debug/backup/night-chain` | The night's four legs now, in order | Refuses while any op/update/chain runs; the leg uses `RunUpdateLegNow` |
|
| `web.nightChain` (R-705, v0.279.0) | controller/internal/web/night_chain.go | `POST /api/debug/backup/night-chain` | The night's four legs now, in order | Refuses while any op/update/chain runs; the leg uses `RunUpdateLegNow` |
|
||||||
@@ -59,9 +61,12 @@
|
|||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| `util.KindErrorf` / `util.KindError` | controller/internal/util/errkind.go | `(kind error, format string, a ...interface{}) error` | ANY refusal a caller must tell apart: build the message exactly as `fmt.Errorf` would AND carry a sentinel for `errors.Is` | The message bytes are unchanged (pinned by tests); never `fmt.Errorf("%w: …")`, which would prepend the sentinel's own text to the customer's sentence |
|
| `util.KindErrorf` / `util.KindError` | controller/internal/util/errkind.go | `(kind error, format string, a ...interface{}) error` | ANY refusal a caller must tell apart: build the message exactly as `fmt.Errorf` would AND carry a sentinel for `errors.Is` | The message bytes are unchanged (pinned by tests); never `fmt.Errorf("%w: …")`, which would prepend the sentinel's own text to the customer's sentence |
|
||||||
| `stacks.ErrAlreadyDeployed` / `ErrRequiredField` / `ErrPathMissing` / `ErrNotEnoughMemory` | controller/internal/stacks/deploy_errors.go | sentinels | the API's deploy status code (`api.deployStatusFor`) | 409 / 400 / 400 / 400. Do NOT add a text signature beside them |
|
| `stacks.ErrAlreadyDeployed` / `ErrRequiredField` / `ErrPathMissing` / `ErrNotEnoughMemory` | controller/internal/stacks/deploy_errors.go | sentinels | the API's deploy status code (`api.deployStatusFor`) | 409 / 400 / 400 / 400. Do NOT add a text signature beside them |
|
||||||
|
| `stacks.ErrStackNotFound` / `ErrProtectedStack` / `ErrNotDeployed` / `ErrStillRunning` / `ErrNotOrphaned` | controller/internal/stacks/stack_errors.go | sentinels | the API's stop/start/restart/update, remove and delete status code (`api.stackOpStatusFor`, R-569) | 404 / 403 / 409 / 409 / 409. Only the producers in manager.go and delete.go carry them; a new refusal on those paths must carry one or it answers 500 |
|
||||||
| `backup.ErrOffsiteQuota` | controller/internal/backup/offbox.go | sentinel | `ClassifyOffsiteFailure` telling a quota over-run apart | The other arms of that switch stay TEXT matches on purpose — they are restic's and ssh's own English output, which we neither write nor translate |
|
| `backup.ErrOffsiteQuota` | controller/internal/backup/offbox.go | sentinel | `ClassifyOffsiteFailure` telling a quota over-run apart | The other arms of that switch stay TEXT matches on purpose — they are restic's and ssh's own English output, which we neither write nor translate |
|
||||||
| `monitor.WarnKind*` + `HealthReport.addWarning` / `WarningKindAt` | controller/internal/monitor/healthcheck.go | `(text, kind string)` | a health warning whose PLACEMENT the dashboard decides | Internal only: `internal/report/builder.go` copies Status/Issues/Warnings, so kinds never reach the hub (pinned) |
|
| `monitor.WarnKind*` + `HealthReport.addWarning` / `WarningKindAt` | controller/internal/monitor/healthcheck.go | `(text, kind string)` | a health warning whose PLACEMENT the dashboard decides | Internal only: `internal/report/builder.go` copies Status/Issues/Warnings, so kinds never reach the hub (pinned) |
|
||||||
| `settings.OffboxTarget.LastWarningKind` + `backup.OffboxWarnNoAppsSelected` | controller/internal/settings/settings.go | persisted string | the Távoli mentés page's stale-note substitution | Written and cleared with `LastWarning`; the text fallback in `offboxWarningDisplay` is LEGACY only (kind == "") and is removed when R-570 closes |
|
| `monitor.MsgRef` + `HealthReport.addWarningMsg` / `addIssue` / `WarningMsgAt` / `IssueMsgAt` | controller/internal/monitor/healthcheck.go | `MsgRef{Key, Args}` beside the wire text | a health warning/issue whose BANNER must follow the household's language (R-516 item 10) | The wire text (report health.*) stays byte-identical; `AlertManager.Refresh` renders the key and falls back to the text when Key is empty. Every issue goes through `addIssue` so the parallel slices cannot drift (pinned) |
|
||||||
|
| `AlertManager.GetBannerAlerts(page, lang)` + `bannerShows` (R-906, 2026-10-08) | controller/internal/web/alerts.go | the layout banner's list for ONE page, capped AFTER the page filter | any page that fills `data["Alerts"]` (`baseData` does it for you) | `GetAlerts` keeps Inline and other pages' alerts (debug dump, placement tests) and must not feed a banner: its cap counted alerts the layout then dropped, so a page showed „+ 5 további figyelmeztetés" and nothing above it. `bannerShows` mirrors the layout's own filter (pinned: `TestR906_*`) |
|
||||||
|
| `settings.OffboxTarget.LastWarningKind` + `backup.OffboxWarnNoAppsSelected` | controller/internal/settings/settings.go | persisted string | the Távoli mentés page's stale-note substitution | Written and cleared with `LastWarning`; the page decides on the kind ONLY — the legacy text fallback was removed when R-570 closed (2026-10-10) |
|
||||||
|
|
||||||
### HTTP/JSON envelopes + flash messages
|
### HTTP/JSON envelopes + flash messages
|
||||||
|
|
||||||
@@ -76,7 +81,15 @@
|
|||||||
| `restoreOpInFlight` + `hasRecentRestoreResult` | controller/internal/web/restore_wizard.go | `(backup.RestoreOpStatus) bool` / `(st, app, now) bool` | THE "is a restore running / did one just finish" display reads | **TRAP (v0.154.0 shipped this bug): `Manager` has TWO running flags.** `IsRunning()` reads the CONCURRENCY flag, acquired inside the goroutine — and `RestoreOffboxScratch` never acquires it, so it is false for the whole verification restore. Display must read `RestoreStatus().Running` (set synchronously by `BeginRestoreOp`). Read the status ONCE per render or the strip and the suppression can disagree. `hasRecentRestoreResult` is app-bound and window-bounded — a process-wide result must not light another app's „Eredmény" |
|
| `restoreOpInFlight` + `hasRecentRestoreResult` | controller/internal/web/restore_wizard.go | `(backup.RestoreOpStatus) bool` / `(st, app, now) bool` | THE "is a restore running / did one just finish" display reads | **TRAP (v0.154.0 shipped this bug): `Manager` has TWO running flags.** `IsRunning()` reads the CONCURRENCY flag, acquired inside the goroutine — and `RestoreOffboxScratch` never acquires it, so it is false for the whole verification restore. Display must read `RestoreStatus().Running` (set synchronously by `BeginRestoreOp`). Read the status ONCE per render or the strip and the suppression can disagree. `hasRecentRestoreResult` is app-bound and window-bounded — a process-wide result must not light another app's „Eredmény" |
|
||||||
| `restoreWizardPath` / `deriveWizardStep` / `resolveWizardApp` | controller/internal/web/restore_wizard.go | `(app) string` / `(restoreWizardInput) restoreWizardView` / `([]OffboxAppRow, name) *OffboxAppRow` | R-48 offsite restore wizard: URL builder + the PURE step/unlock derivation + the app-resolution refusals | The step is **never** taken from the request. Precedence is load-bearing: op-running outranks a stale `?full_prep=`, else a commit button reappears mid-restore. Truth table + red-proof: `restore_wizard_test.go`. Adding a form here that posts anywhere new breaks `TestRestoreWizard_NoNewMutationEndpoints` **by design** — R-48 adds no mutation surface |
|
| `restoreWizardPath` / `deriveWizardStep` / `resolveWizardApp` | controller/internal/web/restore_wizard.go | `(app) string` / `(restoreWizardInput) restoreWizardView` / `([]OffboxAppRow, name) *OffboxAppRow` | R-48 offsite restore wizard: URL builder + the PURE step/unlock derivation + the app-resolution refusals | The step is **never** taken from the request. Precedence is load-bearing: op-running outranks a stale `?full_prep=`, else a commit button reappears mid-restore. Truth table + red-proof: `restore_wizard_test.go`. Adding a form here that posts anywhere new breaks `TestRestoreWizard_NoNewMutationEndpoints` **by design** — R-48 adds no mutation surface |
|
||||||
| `restoreOpBlocked` | controller/internal/web/restore_wizard.go | `() (msg string, blocked bool)` | THE refusal gate before starting ANY restore | **Use this, never a bare `IsRunning()`.** It reads BOTH flags: `RestoreStatus().Running` (set synchronously by `BeginRestoreOp`, true for the whole off-box restore) and `IsRunning()` (the concurrency flag, the only one the nightly backup holds). **R-351: all seven handlers read only `IsRunning()`, which the goroutine acquires AFTER the handler returns — a second press started a second run and was told „…elindult".** Returns the Hungarian refusal, which names the running app and a route | **R-360 (v0.226.0): `offboxVerifyCopyDeleteHandler` was the LAST holdout and its doc comment claimed it already did this — the sentence is why nobody looked. `IsRunning()` is FALSE for the whole of a verification restore, so the copy a restore was writing into could be deleted from the UI (observed live 2026-08-21 22:35). No app-name comparison: refusing during ANY restore is stronger and uniform.**
|
| `restoreOpBlocked` | controller/internal/web/restore_wizard.go | `() (msg string, blocked bool)` | THE refusal gate before starting ANY restore | **Use this, never a bare `IsRunning()`.** It reads BOTH flags: `RestoreStatus().Running` (set synchronously by `BeginRestoreOp`, true for the whole off-box restore) and `IsRunning()` (the concurrency flag, the only one the nightly backup holds). **R-351: all seven handlers read only `IsRunning()`, which the goroutine acquires AFTER the handler returns — a second press started a second run and was told „…elindult".** Returns the Hungarian refusal, which names the running app and a route | **R-360 (v0.226.0): `offboxVerifyCopyDeleteHandler` was the LAST holdout and its doc comment claimed it already did this — the sentence is why nobody looked. `IsRunning()` is FALSE for the whole of a verification restore, so the copy a restore was writing into could be deleted from the UI (observed live 2026-08-21 22:35). No app-name comparison: refusing during ANY restore is stronger and uniform.**
|
||||||
|
| `Server.beginRestoreOp` → `backup.TryBeginRestoreOp` / `RestoreBusy` (R-1256 H6) | controller/internal/web/restore_wizard.go; controller/internal/backup/opstatus.go | `(op, stack) (msg string, ok bool)` / `(op, stack) (busy, mirrorApp string)` | THE way a restore op begins: the check for every other operation (a restore op, the backup run, a second-drive copy) and the record in ONE step under `m.mu` — the mirror asks under the same lock (`beginTier2Run`) | **Never call `BeginRestoreOp` from a handler** (`TestR1256_H6_NoHandlerBeginsARestoreUnchecked`): `restoreOpBlocked` asked early can be stale by the time the form is read, and a mirror that began in between ran beside the restore. `restoreOpBlocked` stays as the EARLY refusal; the kept loads begin inside `LoadKeptApp` / `LoadKeptOffsite` and return `ErrRestoreBusy` |
|
||||||
| `Manager.RestoreFromRecoveryUnitAt` / `RestoreFromRecoveryUnit` + `UnitRestoreResult` (R-353 v0.226.0; R-102 v0.229.0) | controller/internal/backup/restore_unit.go | `(stack, unitDir string) (UnitRestoreResult, error)` / `(stack string) (…)` | THE local recovery-unit restore, and the facts its surface must state | **Returns a RESULT, not just an error** — volumes replayed, DBs replayed, and what the manifest LISTED. The Manifest* counts are load-bearing: zero-replayed has two causes (the backup held no data / the backup listed data that did not come back) and they are opposite news. Pair it with `unitRestoreOutcomeMsg`; do NOT write a new sentence. **A claim about the APP is forbidden on this path** — it has no `SafetyDump` discriminator, unlike the off-site twin (CONTEXT.md ruling, 07-backup-architecture §6.3). `restoreDockerVolumes` now returns `(int, error)`; `restoreDockerVolumesFrom` is unchanged and still the shared implementation. **R-102: `…At` holds the whole body and takes the unit DIRECTORY; the one-argument form is the thin caller naming the primary unit.** THE SOURCE MOVES; THE DESTINATION DOES NOT — `GetAppDrivePath` still resolves where the data lands. The R-47 mutation order, the unit-over-guest secret precedence, the fail-closed data-key gate and the no-unit `RestoreApp` fallback are all pinned and unchanged. The volume leg goes through the R-354 `volumeReplayFrom` seam so the source directory is assertable without Docker |
|
| `Manager.RestoreFromRecoveryUnitAt` / `RestoreFromRecoveryUnit` + `UnitRestoreResult` (R-353 v0.226.0; R-102 v0.229.0) | controller/internal/backup/restore_unit.go | `(stack, unitDir string) (UnitRestoreResult, error)` / `(stack string) (…)` | THE local recovery-unit restore, and the facts its surface must state | **Returns a RESULT, not just an error** — volumes replayed, DBs replayed, and what the manifest LISTED. The Manifest* counts are load-bearing: zero-replayed has two causes (the backup held no data / the backup listed data that did not come back) and they are opposite news. Pair it with `unitRestoreOutcomeMsg`; do NOT write a new sentence. **A claim about the APP is forbidden on this path** — it has no `SafetyDump` discriminator, unlike the off-site twin (CONTEXT.md ruling, 07-backup-architecture §6.3). `restoreDockerVolumes` now returns `(int, error)`; `restoreDockerVolumesFrom` is unchanged and still the shared implementation. **R-102: `…At` holds the whole body and takes the unit DIRECTORY; the one-argument form is the thin caller naming the primary unit.** THE SOURCE MOVES; THE DESTINATION DOES NOT — `GetAppDrivePath` still resolves where the data lands. The R-47 mutation order, the unit-over-guest secret precedence, the fail-closed data-key gate and the no-unit `RestoreApp` fallback are all pinned and unchanged. The volume leg goes through the R-354 `volumeReplayFrom` seam so the source directory is assertable without Docker |
|
||||||
|
| `Manager.putBackAfterFailedRestore` + `liveVolumeCopy` (R-893 option A, v0.336.0) | controller/internal/backup/offbox_restore_undo.go | `(stack, cause, live, copy, volumesMoved, filesPlaced, restart, holdKey, restoreKind) error` (R-1340: `restoreKind` = `settings.RestoreKindOffsite`/`Local`; a failed put-back records its step in the hold's `MixedCause`/`FailedStep`/`DBReplay`) | THE restore undo — off-site (v0.336.0) and, since D22 (unreleased), the LOCAL unit restore (`RestoreFromRecoveryUnitAtWith`, so also the second drive's and a kept load): the live volumes it will replace, measured before the stop (`planLiveVolumeCopy`), copied right after it (`copyLiveVolumes`), poured back on any failure | One copy per restore under `<ns>/backups/restore-undo/<app>/` (no capture set reads `backups/`); the put-back uses the restore's own `volumeReplayFrom`/`restoreDockerVolumesFrom`, so there is one volume-replay implementation. A put-back that fails sets `keep` and HOLDS (option C) — never start on volumes that are not known to be back. Seams for tests without Docker: `undoVolumeProbeFn`, `undoVolumeTarFn`, `undoVolumeRemoveFn`; operator notice `SetRestorePutBackNotify` (leg `restore-put-back`). Pinned by `r893_putback_test.go` and `r1177_local_putback_test.go` |
|
||||||
|
| `Manager.SweepUnusedRestoreCopies` (R-1256 H8) | controller/internal/backup/restore_copy_sweep.go | `(now) []string` | THE only AUTOMATIC remover of a restore copy nothing names any more (`restore-copy-sweep`, every 6 h); the household's „Törlés most" is `DeleteRestoreCopy` (D62, restore_copies.go — same „needed" rule via `restoreCopyNeededFor`, check + removal under `m.mu`) | Removes a copy only when ALL hold: older than 30 days (D62), the app has no restore hold of ANY kind, the app-stop marker is readable and does not name the app, no restore op runs. It answers „no" when it cannot answer — a held or waiting copy is support's way back |
|
||||||
|
| `CrashPutBack` + `Manager.persistUndoForCrash` + `AppStopGuard.SetUndo` (D22 / R-1195, v0.338.0) | controller/internal/backup/restore_crash_putback.go | `NewCrashPutBack(stop, writeDef, logger)`; `PutBackInterruptedRestore(stack, undoDir) error` | A restore cut by a power loss is put back at start: the copy (volumes + `definition/` + `undo.json`) is recorded in the app-stop marker once whole; `Recover` pours it back BEFORE the restart | Call `persistUndoForCrash` right after `copyLiveVolumes` in any new restore path. `Recover` runs before the backup manager exists, so the put-back is wired in main.go with `stackMgr.StopStack` and the stack adapter's definition writer. A failed put-back = a FAILED recovery (app not started, marker kept). The household reads `note.restore.interrupted_put_back` (`LoadRestoreRecordAfterRecovery`). Pinned by `TestR1195_*` |
|
||||||
|
| `tier2CaptureSetFull(...) (legs, missing, warns, classified)` + `keptCopyRels` + `dropKeptCopiesUnder` (R-1252, unreleased) | controller/internal/backup/tier2_capture.go, tier2_kept.go | `classified` = the legs come from a VALID backup block | **The second-drive reconcile deletes only under a valid classification**; a rejected or absent block keeps every dest dir; kept copies (D25) are always in the keep set; a mirror deleted by Remove drops its kept records | A new reconcile caller must take `classified` and the kept rels too — never reconcile against the legacy legs. A rejected block is told by `Manager.BackupBlockRejected` (stacks; via the adapter's optional `BackupBlockRejected` method) and signalled once a day (`SetTier2SettingsUnreadableNotify`). Pinned by `r1252_rejected_block_keeps_copies_test.go` |
|
||||||
|
| `holdreport.Reporter` + `settings.RestoreHold.Why` / `WireReason` (D53, unreleased) | controller/internal/holdreport/holdreport.go · controller/internal/settings/settings.go | `New(store, notifier.PushEvent, logger)`; `Tick(now)` from the scheduler | Tells the hub every hold in place (`app_held`), every hold gone (`app_hold_cleared`), each again daily | **One observer of the hold store — never a send inside a hold writer.** A new hold writer needs nothing here. The hold sentence is `RestoreHold.Why()` (one per reason) — never a second copy. Pinned by `internal/holdreport/holdreport_test.go` |
|
||||||
|
| `AppStopGuard.ResumePutBack` / `ResumeWaitingPutBacks` + `HoldReasonPutBackPending` (R-1251, unreleased) | controller/internal/backup/appstop_putback_wait.go | `ResumePutBack(stack) bool` (true = nothing owed, the caller may start); `ResumeWaitingPutBacks() []string` (puts back, then starts through the gated starter) | A cut restore's copy on a drive that is not bound is WAITING: Recover writes the restore hold `putback_pending` (copy in `SafetyDump`) and starts nothing; the put-back runs when the drive binds, before any start | **Any new path that starts an app when its drive arrives calls `ResumePutBack` first** (the boot recreate and `restartStacks` do, in web via `Server.resumePutBack`). Every other start path is covered by the hold store it already honours — do not add a second check. A failed put-back (at start or on resume) writes the D20 hold (`restore_mixed`) and drops the app from the marker. Needs `SetHolds` + `SetUndoReachable` before `Recover` (main.go). Pinned by `r1251_putback_waits_test.go`, `TestR1251_DriveStartPathsPutBackBeforeTheyStart`, `TestR1251_MainWiresThePutBackWait` |
|
||||||
|
| `AppStopGuard.ClearHoldByOperator` + `clearHoldNow` / `listenHoldCtl` / `clearRestoreHoldCLI` (D64 = B, R-1343, unreleased) | controller/internal/backup/hold_clear.go · controller/cmd/controller/holdclear.go | `ClearHoldByOperator(stack) (RestoreHold, error)`; `clearHoldNow(deps, stack, who) (msg, error)` | THE operator's hold clear, any reason — the hub's `clear_hold` and the box command `--clear-restore-hold` both go through `clearHoldNow` in the RUNNING controller | **Never clear a hold from a second process** — the running controller's next save writes it back (R-1343, measured). The box command reaches the running controller over `<data dir>/ctl/hold.sock` (unix, 0600, peer uid checked; never TCP/HTTP). A `putback_pending` clear also drops the app from the app-stop marker (the copy stays). Refusals (`ErrHoldBadStack`, `ErrNotHeld`) change nothing. The update's in-memory held flag goes via `stacks.Manager.ForgetUpdateHeld`. Pinned by `cmd/controller/holdclear_test.go` |
|
||||||
| `Manager.RestoreTier2Unit` + `Tier2Coverage.CanRestoreUnit` / `Tier2CopyDate` (R-102/R-103, v0.229.0) | controller/internal/backup/tier2_restore.go | `(stack string) (UnitRestoreResult, error)` / `() bool` / `() (string, bool)` | THE full restore from the SECOND DRIVE's mirror, and the predicate that gates it | **Do NOT widen `CanRestore()`** — it answers only "can the additive file restore run?" and one predicate answering two questions is R-356. Fail-closed: `tier2UnitIsOpenable` requires a parseable manifest, because a directory is not a package. The single-writer flag is taken INSIDE `RestoreFromRecoveryUnitAt` — a second `acquireRunning()` here would refuse the restore it guards. `Tier2CopyDate` prefers the SUCCESS anchor over the attempt clock (R-101) and reports which it returned |
|
| `Manager.RestoreTier2Unit` + `Tier2Coverage.CanRestoreUnit` / `Tier2CopyDate` (R-102/R-103, v0.229.0) | controller/internal/backup/tier2_restore.go | `(stack string) (UnitRestoreResult, error)` / `() bool` / `() (string, bool)` | THE full restore from the SECOND DRIVE's mirror, and the predicate that gates it | **Do NOT widen `CanRestore()`** — it answers only "can the additive file restore run?" and one predicate answering two questions is R-356. Fail-closed: `tier2UnitIsOpenable` requires a parseable manifest, because a directory is not a package. The single-writer flag is taken INSIDE `RestoreFromRecoveryUnitAt` — a second `acquireRunning()` here would refuse the restore it guards. `Tier2CopyDate` prefers the SUCCESS anchor over the attempt clock (R-101) and reports which it returned |
|
||||||
| `unitRestoreOutcomeMsg` + its three message constants (R-353, v0.226.0) | controller/internal/web/handlers.go | `(app string, res backup.UnitRestoreResult) string` | THE customer sentence for a completed LOCAL restore | Twin of `reconstituteOutcomeMsg`; copy its SHAPE (clauses earned by having done the thing, no filesystem path, base names only), never its text. The constants are named because `r353_unit_outcome_test.go` asserts them verbatim — a silent edit is how an honest message drifts back into a comforting one, which is the documented history of the sentence it replaces |
|
| `unitRestoreOutcomeMsg` + its three message constants (R-353, v0.226.0) | controller/internal/web/handlers.go | `(app string, res backup.UnitRestoreResult) string` | THE customer sentence for a completed LOCAL restore | Twin of `reconstituteOutcomeMsg`; copy its SHAPE (clauses earned by having done the thing, no filesystem path, base names only), never its text. The constants are named because `r353_unit_outcome_test.go` asserts them verbatim — a silent edit is how an honest message drifts back into a comforting one, which is the documented history of the sentence it replaces |
|
||||||
| `offsiteNoSpaceMsgFmt` + `offsiteSizeUnknownMsg` (R-357, v0.226.0) | controller/internal/backup/offbox_restore.go | two consts | EVERY headroom refusal on the off-site restore surface | **All four gates share these** (prepare, scratch, place, and the destructive reconstitute). A customer meeting one wording on one path and a different one on another has to work out whether it is the same problem. **The reconstitute gate uses NO ×1.1 margin** — it copies a measured tree; `OffboxRestorePrepareFull`'s ×1.1 predicts a download. **Fail closed when either probe reads ≤ 0**: `free < need` with `need == 0` is FALSE, so an unmeasurable input sails through — a gate present and inert |
|
| `offsiteNoSpaceMsgFmt` + `offsiteSizeUnknownMsg` (R-357, v0.226.0) | controller/internal/backup/offbox_restore.go | two consts | EVERY headroom refusal on the off-site restore surface | **All four gates share these** (prepare, scratch, place, and the destructive reconstitute). A customer meeting one wording on one path and a different one on another has to work out whether it is the same problem. **The reconstitute gate uses NO ×1.1 margin** — it copies a measured tree; `OffboxRestorePrepareFull`'s ×1.1 predicts a download. **Fail closed when either probe reads ≤ 0**: `free < need` with `need == 0` is FALSE, so an unmeasurable input sails through — a gate present and inert |
|
||||||
@@ -91,6 +104,7 @@
|
|||||||
| `CheckPlacement` + `PlacementMismatchMessage` | controller/internal/backup/offbox_placement.go | `(*RecoveryManifest, liveDrive, liveNS) PlacementCheck` / `(stack, PlacementCheck) string` | Comparing where a backup SAYS the data lived against where a restore is about to write | Pure and total — nil/empty/blank manifest all give the same honest "not known, no mismatch". **An UNKNOWN is never a mismatch** (refusing on an absence strands every pre-field unit). Compares the DRIVE only (the namespace root is derived from it), Cleaned, so a trailing slash is not a difference. The message names BOTH values on purpose |
|
| `CheckPlacement` + `PlacementMismatchMessage` | controller/internal/backup/offbox_placement.go | `(*RecoveryManifest, liveDrive, liveNS) PlacementCheck` / `(stack, PlacementCheck) string` | Comparing where a backup SAYS the data lived against where a restore is about to write | Pure and total — nil/empty/blank manifest all give the same honest "not known, no mismatch". **An UNKNOWN is never a mismatch** (refusing on an absence strands every pre-field unit). Compares the DRIVE only (the namespace root is derived from it), Cleaned, so a trailing slash is not a difference. The message names BOTH values on purpose |
|
||||||
| `RecordedUnitForStack` + `RecordedAddress` | controller/internal/backup/offbox_placement.go | `(stack) (RecordedPlacement, RecordedAddress, bool)` | Reading back the address + data folder a backup recorded, for a reinstall prefill | Local file reads over every readable namespace root — **no network, no restic, no restore**; it exists for the NOT-INSTALLED case where `GetStackHDDPath` is `""`. **`RecordedAddress.Known()` requires BOTH halves:** an absent `SUBDOMAIN` makes the live deploy path fall back to the CATALOG default (`stacks/deploy.go:88-90`), and offering that back as "what your backup says" is a fabricated fact |
|
| `RecordedUnitForStack` + `RecordedAddress` | controller/internal/backup/offbox_placement.go | `(stack) (RecordedPlacement, RecordedAddress, bool)` | Reading back the address + data folder a backup recorded, for a reinstall prefill | Local file reads over every readable namespace root — **no network, no restic, no restore**; it exists for the NOT-INSTALLED case where `GetStackHDDPath` is `""`. **`RecordedAddress.Known()` requires BOTH halves:** an absent `SUBDOMAIN` makes the live deploy path fall back to the CATALOG default (`stacks/deploy.go:88-90`), and offering that back as "what your backup says" is a fabricated fact |
|
||||||
| **`Metadata.For(lang)` + `LocalizeStacks` / `LocalizeStackPtr` / `Stack.MetaFor` (R-560, v0.257.0)** | controller/internal/stacks/metadata_i18n.go | `(lang string) Metadata`; `([]Stack, lang) []Stack`; `(*Stack, lang) *Stack` | THE only way a page may reach catalog COPY — the app description, tagline, use cases, first steps, prerequisites, deploy-field labels and descriptions, optional-config text, integration labels, data-path labels and the initial-credentials note | Reading `stack.Meta.<copy>` off the manager renders HUNGARIAN to an English household, with no error and nothing wrong-looking on the page — `TestNoDirectMetaCopyReadOnPages` keeps the named, reasoned allow-list of every direct read in `internal/web`. **`For("hu")` is the parsed struct with `I18n` cleared** and nothing else (pinned over all 53 real catalog files), so a translation cannot change the Hungarian product. **Fallback is FIELD BY FIELD** — absent or blank English shows Hungarian, which is what makes a half-translated app shippable. **Lists replace WHOLE; every other list is matched by its own key** (`env_var`, option `value`, `match_group`, `target`, `path`) — position matching mistranslates silently the first time a field is inserted. **It never writes through:** the metadata is shared by concurrent requests, so an in-place merge leaks one household's language into another's page |
|
| **`Metadata.For(lang)` + `LocalizeStacks` / `LocalizeStackPtr` / `Stack.MetaFor` (R-560, v0.257.0)** | controller/internal/stacks/metadata_i18n.go | `(lang string) Metadata`; `([]Stack, lang) []Stack`; `(*Stack, lang) *Stack` | THE only way a page may reach catalog COPY — the app description, tagline, use cases, first steps, prerequisites, deploy-field labels and descriptions, optional-config text, integration labels, data-path labels and the initial-credentials note | Reading `stack.Meta.<copy>` off the manager renders HUNGARIAN to an English household, with no error and nothing wrong-looking on the page — `TestNoDirectMetaCopyReadOnPages` keeps the named, reasoned allow-list of every direct read in `internal/web`. **`For("hu")` is the parsed struct with `I18n` cleared** and nothing else (pinned over all 53 real catalog files), so a translation cannot change the Hungarian product. **Fallback is FIELD BY FIELD** — absent or blank English shows Hungarian, which is what makes a half-translated app shippable. **Lists replace WHOLE; every other list is matched by its own key** (`env_var`, option `value`, `match_group`, `target`, `path`) — position matching mistranslates silently the first time a field is inserted. **It never writes through:** the metadata is shared by concurrent requests, so an in-place merge leaks one household's language into another's page |
|
||||||
|
| `AppInfo.WithAddress` (R-498) | controller/internal/stacks/appinfo_address.go | `(subdomain, domain string) AppInfo` | Filling the catalog copy's `<label>.DOMAIN` / bare `DOMAIN` placeholder with the household's real address (effective subdomain + customer domain) | Returns a COPY (the metadata is shared); `\bDOMAIN\b` leaves `SUBDOMAIN`/`MAIL_DOMAIN` alone; no domain → unchanged. Apply AFTER `LocalizeStackPtr`. The deploy page still fills its post-deploy steps in JS (`deploy.html`), `knownLoginLine` its own line |
|
||||||
| `Metadata.HasDeployField` | controller/internal/stacks/metadata.go | `(envVar string) bool` | "Does this app have somewhere to PUT a recorded value?" | **13 of 53 templates declare `HDD_PATH`; 40 do not** (measured 2026-08-21). For the 40 a recorded placement is a FACT TO STATE, never a value to write into a field that does not exist |
|
| `Metadata.HasDeployField` | controller/internal/stacks/metadata.go | `(envVar string) bool` | "Does this app have somewhere to PUT a recorded value?" | **13 of 53 templates declare `HDD_PATH`; 40 do not** (measured 2026-08-21). For the 40 a recorded placement is a FACT TO STATE, never a value to write into a field that does not exist |
|
||||||
| `redirectTier2` | controller/internal/web/tier2_config_handler.go | `(w, r, name, flash, flashErr)` | Tier2 page flash redirects | Same convention |
|
| `redirectTier2` | controller/internal/web/tier2_config_handler.go | `(w, r, name, flash, flashErr)` | Tier2 page flash redirects | Same convention |
|
||||||
| `validStackName` | controller/internal/web/validate.go | `(name string) bool` | Any stack name from a request | Single-segment, no `/ \ ..` — blocks path traversal into stacks/userdata |
|
| `validStackName` | controller/internal/web/validate.go | `(name string) bool` | Any stack name from a request | Single-segment, no `/ \ ..` — blocks path traversal into stacks/userdata |
|
||||||
@@ -106,10 +120,12 @@
|
|||||||
| `settings.HubEscrowKeySHA256` + `SetHubEscrowKeySHA256` / `GetHubEscrowKeySHA256`, and `OffsiteRecoveryOffer` **shape (c)** (R-241, v0.206.0) | controller/internal/settings/settings.go, controller/internal/backup/offbox.go | `(sha, checkedAt string) error` / `() (string, string)` | **THE DISCRIMINATOR the recovery screen asks** — does the hub hold a package for a key other than the one we use? | **The comparison was ALREADY computed on every ACK since SLICE 3 and persisted nowhere** — that is R-241's second half. Wire the recorder in `main.go`'s `EscrowAutoConfirmer` literal or shape (c) reads an empty hash for ever and the fix ships INERT (pinned by `TestMainWiresRecordEscrowKeyHash`). **§7.2 staleness, decided:** a KNOWN DIFFERENCE offers **however old the reading** — age is deliberately NOT gated on, because gating makes a box offline from the hub silently stop offering; an **ABSENT hash falls back to (a)/(b)** and does NOT offer, because `""` is the hub positively saying its package seals no key (legacy hash-less escrow), not an unknown. `CheckedAt` is for diagnosis, never a gate |
|
| `settings.HubEscrowKeySHA256` + `SetHubEscrowKeySHA256` / `GetHubEscrowKeySHA256`, and `OffsiteRecoveryOffer` **shape (c)** (R-241, v0.206.0) | controller/internal/settings/settings.go, controller/internal/backup/offbox.go | `(sha, checkedAt string) error` / `() (string, string)` | **THE DISCRIMINATOR the recovery screen asks** — does the hub hold a package for a key other than the one we use? | **The comparison was ALREADY computed on every ACK since SLICE 3 and persisted nowhere** — that is R-241's second half. Wire the recorder in `main.go`'s `EscrowAutoConfirmer` literal or shape (c) reads an empty hash for ever and the fix ships INERT (pinned by `TestMainWiresRecordEscrowKeyHash`). **§7.2 staleness, decided:** a KNOWN DIFFERENCE offers **however old the reading** — age is deliberately NOT gated on, because gating makes a box offline from the hub silently stop offering; an **ABSENT hash falls back to (a)/(b)** and does NOT offer, because `""` is the hub positively saying its package seals no key (legacy hash-less escrow), not an unknown. `CheckedAt` is for diagnosis, never a gate |
|
||||||
| `backup.AbandonStatus` / `AbandonSweep` / `CancelAbandon` / `ClearAbandonPurgeIfConfirmed` / `ExtendAbandon` / `StopAbandon` + `AbandonGraceDays` (R-241, v0.206.0) | controller/internal/backup/offbox_abandon.go | see file | **The 14-day abandonment countdown** — the ONLY thing in the product that deletes a customer's off-site history | **BOTH HALVES OR NEITHER.** The set-aside store and the sealed package that protects it are two halves of one thing; removing only one leaves a package that opens nothing, or ciphertext nobody can decrypt. Not atomic across two machines, so it is a **two-phase commit**: delete the store, set `AbandonPurgeRequested`, and keep declaring it until the hub's ACK stops reporting a superseded package — the confirmation rides the SAME ACK as the request. **The countdown starts in `ResetOrphanedRepo`, NOT in the shared `resetOrphanedRepo`** — the helper is also the UNCLAIMED auto-reset, where nobody decided anything. **The recovery offer stays reachable for the whole grace** (a grace in which recovery is impossible is decorative). **Drive it with `SetOffboxClock`, never a shortened live timer** (§7.4). A transport failure leaves the countdown DUE so tomorrow retries; the operator levers REFUSE rather than no-op when nothing is running or the store is already gone |
|
| `backup.AbandonStatus` / `AbandonSweep` / `CancelAbandon` / `ClearAbandonPurgeIfConfirmed` / `ExtendAbandon` / `StopAbandon` + `AbandonGraceDays` (R-241, v0.206.0) | controller/internal/backup/offbox_abandon.go | see file | **The 14-day abandonment countdown** — the ONLY thing in the product that deletes a customer's off-site history | **BOTH HALVES OR NEITHER.** The set-aside store and the sealed package that protects it are two halves of one thing; removing only one leaves a package that opens nothing, or ciphertext nobody can decrypt. Not atomic across two machines, so it is a **two-phase commit**: delete the store, set `AbandonPurgeRequested`, and keep declaring it until the hub's ACK stops reporting a superseded package — the confirmation rides the SAME ACK as the request. **The countdown starts in `ResetOrphanedRepo`, NOT in the shared `resetOrphanedRepo`** — the helper is also the UNCLAIMED auto-reset, where nobody decided anything. **The recovery offer stays reachable for the whole grace** (a grace in which recovery is impossible is decorative). **Drive it with `SetOffboxClock`, never a shortened live timer** (§7.4). A transport failure leaves the countdown DUE so tomorrow retries; the operator levers REFUSE rather than no-op when nothing is running or the store is already gone |
|
||||||
| `settings.SyncRecoveryOfferEpoch` / `PostponeRecoveryNoticeForEpoch` / `OptOutRecoveryRemindersForEpoch` + `web.recoveryBannerCookie` (R-241, v0.206.0) | controller/internal/settings/settings.go, controller/internal/web/recovery_handlers.go | `(offered bool, now) (RecoveryOfferView, error)` | **The offer EPOCH** — "once per entry into the offered state", not once ever | **Sync the epoch FIRST and UNCONDITIONALLY in `recoveryInterrupts`.** The first draft returned early when the offer was false, so the FALLING edge was never recorded, `RecoveryOfferActive` stayed true through a settled period, and the next entry counted as a continuation — **the exact defect the epoch exists to fix, reintroduced inside the fix**. Dismissals are recorded against the epoch they were made in, so a fresh entry resets them **by arithmetic**, with nothing to clear. **Three levers, three scopes, and NONE removes the entry point on `/backups/remote`:** the banner cookie is a browser SESSION cookie (no MaxAge — cleared on login) and persists nothing; the reminder opt-out is durable but silences the BANNER ONLY; "most nem" suppresses the full page only |
|
| `settings.SyncRecoveryOfferEpoch` / `PostponeRecoveryNoticeForEpoch` / `OptOutRecoveryRemindersForEpoch` + `web.recoveryBannerCookie` (R-241, v0.206.0) | controller/internal/settings/settings.go, controller/internal/web/recovery_handlers.go | `(offered bool, now) (RecoveryOfferView, error)` | **The offer EPOCH** — "once per entry into the offered state", not once ever | **Sync the epoch FIRST and UNCONDITIONALLY in `recoveryInterrupts`.** The first draft returned early when the offer was false, so the FALLING edge was never recorded, `RecoveryOfferActive` stayed true through a settled period, and the next entry counted as a continuation — **the exact defect the epoch exists to fix, reintroduced inside the fix**. Dismissals are recorded against the epoch they were made in, so a fresh entry resets them **by arithmetic**, with nothing to clear. **Three levers, three scopes, and NONE removes the entry point on `/backups/remote`:** the banner cookie is a browser SESSION cookie (no MaxAge — cleared on login) and persists nothing; the reminder opt-out is durable but silences the BANNER ONLY; "most nem" suppresses the full page only |
|
||||||
|
| `Manager.guardUnitWrite` / `guardUnitDir` + `unitOwnerVerdict` + `setAsideUnit` (D47, R-1269, unreleased) | controller/internal/backup/unit_owner.go | `guardUnitWrite(stack, nsRoot, what) error` (nil = write) | **The one question every unit writer asks first**: is this unit this install's? Another install's unit is moved whole to `backups/set-aside/<app>/<stamp>` and recorded as a kept copy (kind `unit`, reason `earlier_install`); a move that fails refuses the write | **A new writer of `backups/primary/<app>` (or of a second-drive unit copy) calls it before its first byte** — never write and check later. Identity: `stacks.AppConfig.InstallID` via `RecoveryInfo.InstallID`; `EnsureInstallID` (optional provider method) mints one for an older app. Restore of a set-aside unit: `RestoreSetAsideUnit(id)` by its record only. Pinned by `unit_owner_test.go` |
|
||||||
|
| `Manager.keepCopy` / `releaseKeptCopy` / `RemoveKeptCopy` / `KeptCopies` + `settings.KeptCopy` (D25, R-1175/R-1181, 2026-10-21) | controller/internal/backup/tier2_kept.go, controller/internal/settings/kept_copies.go | see files | **A second-drive copy whose SOURCE is gone** (drive away/decommissioned, declared folder missing) — recorded, listed on the restore page, removed only by the household's „Eltávolítás" | **Never remove a kept copy by size, name or pattern** — `RemoveKeptCopy` takes the RECORD and checks path-inside-tree + device/inode; a swapped directory refuses. A share/leg reconcile walks ONLY its own key/legs (R-1175: walking every key with one group's legs deleted the other groups' copies). `emptiedSourceRefused` stops `rsync --delete` from emptying a full copy |
|
||||||
|
| `stacks.SaveImportedAppConfig` + `PrepareImportedApp` (R-1191, 2026-10-21) | controller/internal/stacks/import_record.go | `(stackDir, env) (fresh bool, error)`; `(stackDir, env, fresh) error` | The `.fab` import's app record + doors (family gate, sign-up lock) BEFORE the start | Reuses `carryLifeRecords` / `prepareFamilyGate` / `restoreSignupLock` — do not copy their logic. `PrepareImportedApp` must also update the IN-MEMORY record, or the gate reconcile removes the file on its next tick |
|
||||||
| `atomicWrite` | controller/internal/backup/recovery_unit.go | `(path, data, perm) error` | Atomic file writes (backup pkg) | tmp+rename; no dir creation, no fallback |
|
| `atomicWrite` | controller/internal/backup/recovery_unit.go | `(path, data, perm) error` | Atomic file writes (backup pkg) | tmp+rename; no dir creation, no fallback |
|
||||||
| `writeFileAtomic` | controller/internal/bootstrap/bootstrap.go | `(path, b) error` | controller.yaml writes from bootstrap | Always 0600 (holds local-api token + hub key) |
|
| `writeFileAtomic` | controller/internal/bootstrap/bootstrap.go | `(path, b) error` | controller.yaml writes from bootstrap | Always 0600 (holds local-api token + hub key) |
|
||||||
| `writeConfig0600` | controller/internal/api/router.go | `(path, body) error` | config writes via API | ALWAYS chmods 0600 even pre-existing (F8); direct-write fallback on bind-mount EBUSY (non-atomic!) |
|
| `writeConfig0600` | controller/internal/api/router.go | `(path, body) error` | config writes via API | ALWAYS chmods 0600 even pre-existing (F8); direct-write fallback on bind-mount EBUSY (non-atomic!) |
|
||||||
| `atomicWriteFile` | controller/internal/setup/handlers.go | `(path, data, perm) error` | setup-wizard writes | Same bind-mount fallback caveat |
|
|
||||||
| `Settings.save` (unexported) | controller/internal/settings/settings.go | via mutator methods only | ALL settings.json persistence | tmp+rename, then `.bak` last-known-good AFTER rename succeeds. Never write settings.json by hand |
|
| `Settings.save` (unexported) | controller/internal/settings/settings.go | via mutator methods only | ALL settings.json persistence | tmp+rename, then `.bak` last-known-good AFTER rename succeeds. Never write settings.json by hand |
|
||||||
| `settings.Load` | controller/internal/settings/settings.go | `(path, logger) (*Settings, error)` | Startup load | Corruption recovery: `.bak` restore → else preserve `.corrupt-<ts>` + safe defaults; never crash-loops |
|
| `settings.Load` | controller/internal/settings/settings.go | `(path, logger) (*Settings, error)` | Startup load | Corruption recovery: `.bak` restore → else preserve `.corrupt-<ts>` + safe defaults; never crash-loops |
|
||||||
| `Manager.writeJournal` / `loadJournal` | controller/internal/stacks/migrate.go | `(j *MigrationJob)` | Migration crash journal | Enables `RecoverMigration` at startup |
|
| `Manager.writeJournal` / `loadJournal` | controller/internal/stacks/migrate.go | `(j *MigrationJob)` | Migration crash journal | Enables `RecoverMigration` at startup |
|
||||||
@@ -117,11 +133,14 @@
|
|||||||
| `Manager.buildSharesPayload` / `classifiedShares` | controller/internal/backup/shares_payload.go | `() (dir, passdbOK, error)` / `() []classifiedShare` | the definitions+credential payload and the availability-filtered share set both tiers read | payload is SECRET-BEARING (0600 passdb.tar) — never log its bytes/name at INFO. `classifiedShares` is the single place a dead mount is dropped, so both jobs agree |
|
| `Manager.buildSharesPayload` / `classifiedShares` | controller/internal/backup/shares_payload.go | `() (dir, passdbOK, error)` / `() []classifiedShare` | the definitions+credential payload and the availability-filtered share set both tiers read | payload is SECRET-BEARING (0600 passdb.tar) — never log its bytes/name at INFO. `classifiedShares` is the single place a dead mount is dropped, so both jobs agree |
|
||||||
| `Manager.selectTier2TargetFrom` | controller/internal/backup/tier2.go | `(stack, sourceDrive, fullSize, stateOnlySize) (*Tier2Target, error)` | tier-2 target choice with the source drive supplied EXPLICITLY | the seam the shares job reuses — NEVER fork the headroom math; `selectTier2Target` is now a thin wrapper over it |
|
| `Manager.selectTier2TargetFrom` | controller/internal/backup/tier2.go | `(stack, sourceDrive, fullSize, stateOnlySize) (*Tier2Target, error)` | tier-2 target choice with the source drive supplied EXPLICITLY | the seam the shares job reuses — NEVER fork the headroom math; `selectTier2Target` is now a thin wrapper over it |
|
||||||
| `Manager.tier2ReconcileRoots` | controller/internal/backup/tier2.go | `(destBase, roots, legRels)` | staleness pruning with explicit dest roots | pure extraction from `tier2Reconcile` (which now calls it with `hdd`/`userdata`); reuse it rather than writing a second pruner |
|
| `Manager.tier2ReconcileRoots` | controller/internal/backup/tier2.go | `(destBase, roots, legRels)` | staleness pruning with explicit dest roots | pure extraction from `tier2Reconcile` (which now calls it with `hdd`/`userdata`); reuse it rather than writing a second pruner |
|
||||||
|
| `backup.Tier2CopyBlocksRestore` / `ClearLeftoverTier2Copies` / `MarkTier2CopyForTest` + the `tier2Docker` seam (the stray-copy fix, v0.340.0) | controller/internal/backup/tier2_copy_lifecycle.go | `(m) Tier2CopyBlocksRestore() (app, blocked)`; `ClearLeftoverTier2Copies(ctx) error`; `MarkTier2CopyForTest(app) func()` | a restore's refusal while a capped second-drive copy runs or a stray may run; the start-up removal of labelled copy containers; the test marker; `tier2Docker` is the docker seam (tests never reach real docker) | Row added 2026-10-24 (review round 2). The capped copy runs `rsync --delete` in its own container — never call `docker` directly for it; go through `tier2Docker`. |
|
||||||
| `Manager.liveShareRootOK` / `scratchJoin` | controller/internal/backup/shares_restore.go | `(dst) bool` / `(scratch, abs) string` | THE place guard for shares restore + scratch path reconstruction | a snapshot is UNTRUSTED layout input: require a STRICT descendant of a live registered root, refuse `..` and the drive root itself. `scratchJoin` strips the volume name — plain `filepath.Join` splices a drive letter mid-path |
|
| `Manager.liveShareRootOK` / `scratchJoin` | controller/internal/backup/shares_restore.go | `(dst) bool` / `(scratch, abs) string` | THE place guard for shares restore + scratch path reconstruction | a snapshot is UNTRUSTED layout input: require a STRICT descendant of a live registered root, refuse `..` and the drive root itself. `scratchJoin` strips the volume name — plain `filepath.Join` splices a drive letter mid-path |
|
||||||
| `infra.SambaContainerName` / `SambaPassdbVolume` / `SambaPassdbMount` | controller/internal/infra/samba.go | consts | single source of truth for the samba container identity | the compose renderer interpolates them; stacks/backup/monitor read them. The CONTAINER name (`felhom-samba`) is NOT the stack name (`samba`) — `EffectiveProtected` needs the container one |
|
| `infra.SambaContainerName` / `SambaPassdbVolume` / `SambaPassdbMount` | controller/internal/infra/samba.go | consts | single source of truth for the samba container identity | the compose renderer interpolates them; stacks/backup/monitor read them. The CONTAINER name (`felhom-samba`) is NOT the stack name (`samba`) — `EffectiveProtected` needs the container one |
|
||||||
| `sambaWriteAtomic` | controller/internal/stacks/samba.go | `(path, data, mode) error` | samba smb.conf/compose writes | tmp+**fsync**+rename (the only one of these that fsyncs). Fourth atomic-write helper in the tree — see §6 |
|
| `sambaWriteAtomic` | controller/internal/stacks/samba.go | `(path, data, mode) error` | samba smb.conf/compose writes | tmp+**fsync**+rename (the only one of these that fsyncs). Fourth atomic-write helper in the tree — see §6 |
|
||||||
| `Loop.writeMarker` / `Recover` | controller/internal/quiesce/quiesce.go | `(m Marker)` / `()` | Quiesce crash-safety | Marker written BEFORE stopping stacks; Recover restarts stranded stacks at boot |
|
| `Loop.writeMarker` / `Recover` | controller/internal/quiesce/quiesce.go | `(m Marker)` / `()` | Quiesce crash-safety | Marker written BEFORE stopping stacks; Recover restarts stranded stacks at boot |
|
||||||
| `quiesce.TieredBackend` + `Loop.resolveDueTiers` / `quiesceAndPollTiers` | controller/internal/quiesce/tiers.go, quiesce.go | `Tiers/DueFor/StartBackupFor/BackupStatusFor`; `resolveDueTiers(ctx) ([]dueTier,bool,error)` | THE R-82 multi-tier backup schedule — several whole-guest tiers (local daily + PBS weekly) reconciled into ONE quiesce window | **Both tiers due ⇒ ONE stop/start pair**, never two (two = two app outages for one night). Tiers run SEQUENTIALLY (vzdump holds a guest lock) and the app stays down until the LAST tier snapshots — resuming earlier loses app-consistency on the DR tier. Order is fast-first (agent advertises primary first) or downtime blows up. `ErrTiersUnsupported` (route 404) ⇒ pre-R-82 agent ⇒ degrade to the untargeted path and **STILL BACK UP** — never read it as "nothing due". |
|
| `quiesce.TieredBackend` + `Loop.resolveDueTiers` / `quiesceAndPollTiers` | controller/internal/quiesce/tiers.go, quiesce.go | `Tiers/DueFor/StartBackupFor/BackupStatusFor`; `resolveDueTiers(ctx) ([]dueTier,bool,error)` | THE multi-tier whole-guest backup schedule (local daily + PBS weekly) | **One stop per tier** (`09` §3 decision 156, v0.301.0 — REVERSES R-82's one window for both tiers): a window backs up only the FIRST due tier and resumes the apps at its `snapshotted`; another due tier waits for a later cycle. A tier that refuses to start (BUSY or an error) lets the next tier try in the same window. Order is agent order (primary first). `ErrTiersUnsupported` (route 404) ⇒ pre-R-82 agent ⇒ degrade to the untargeted path and **STILL BACK UP** — never read it as "nothing due". |
|
||||||
|
| `quiesce.InFlightProber` + `Loop.anotherTierInFlight` · `agentapi.Client.BackupJobsInFlight` (R-921) | controller/internal/quiesce/precheck.go · controller/internal/agentapi/backup_tiers.go | `BackupJobsInFlight(ctx) ([]string, error)` | Check first, stop second: no app is stopped for a tier the agent will refuse because ANOTHER tier's job is in flight | OPTIONAL interface (fakes without it keep the old path). Fails toward backing up on any read error. **It cannot see the agent's host-wide heavy-op gate** (OS step, restore-test, fstrim — no endpoint serves it): that refusal is met by the BUSY path's immediate resume (`TestR921_BusyRefusalResumesAtOnce`). The window's OWN tier in flight is not skipped (the agent answers with the running job) |
|
||||||
|
| `quiesce` whole-guest ledger — `Loop.pressOwesNight` / `recordWholeGuestSuccess`, `WithManualTrigger` / `IsManualTrigger` (R-899) | controller/internal/quiesce/nightowed.go | `pressOwesNight(led, target) bool`; `WithManualTrigger(ctx) ctx` | **A household press never cancels the night's whole-guest backup** (operator ruling 2026-10-08) | The ledger (`whole-guest-ledger.json` beside the marker) records SUCCESSES only, per tier, press vs scheduled — it decides due-ness and is never evidence that a copy exists (the agent's storage answers that). An „owed" tier never fires the window gate's safety valve (`withoutOwed`/`gateAge`). The press mark rides the context to the agent adapter (`agentapi.StartBackupForTrigger` → `trigger=manual`), so the agent runs no OS leg after a press. |
|
||||||
| `quiesce.failureBreaker` + `Loop.dropBackedOffTiers` / `noteTierFailure` / `noteTierSuccess` | controller/internal/quiesce/breaker.go, quiesce.go | `blocked/recordFailure/recordSuccess(target, now)`; `backoffFor(n) time.Duration` | **R-88** — a tier whose backups keep failing stops re-quiescing. Backoff 15m→30m→1h→2h→4h (cap), reset on success | **It gates the QUIESCE, not the backup** — the harm was never the failing backup, it was the app outage taken to attempt it, so backed-off tiers are dropped from the due set BEFORE any stack is stopped. **Per TARGET** — a broken offsite tier must never suppress a healthy local one (`TestBreaker_OneFailingTierDoesNotSuppressAHealthyOne`). **Never permanent** — the cap bounds the retry INTERVAL, it never stops retrying; a latched breaker is a silent backup outage, worse than the loop it replaces. **`TriggerNow` is never gated** (it already bypasses due-ness and the window gate), though a manual run still RECORDS its outcome. **`stillRunning` is NOT a failure** — a first full offsite snapshot legitimately runs for hours. State is **in-memory on purpose**: a restart forgets the backoff and re-attempts, which is the cheap direction to fail. Log the deferral ONCE when armed, never per tick. |
|
| `quiesce.failureBreaker` + `Loop.dropBackedOffTiers` / `noteTierFailure` / `noteTierSuccess` | controller/internal/quiesce/breaker.go, quiesce.go | `blocked/recordFailure/recordSuccess(target, now)`; `backoffFor(n) time.Duration` | **R-88** — a tier whose backups keep failing stops re-quiescing. Backoff 15m→30m→1h→2h→4h (cap), reset on success | **It gates the QUIESCE, not the backup** — the harm was never the failing backup, it was the app outage taken to attempt it, so backed-off tiers are dropped from the due set BEFORE any stack is stopped. **Per TARGET** — a broken offsite tier must never suppress a healthy local one (`TestBreaker_OneFailingTierDoesNotSuppressAHealthyOne`). **Never permanent** — the cap bounds the retry INTERVAL, it never stops retrying; a latched breaker is a silent backup outage, worse than the loop it replaces. **`TriggerNow` is never gated** (it already bypasses due-ness and the window gate), though a manual run still RECORDS its outcome. **`stillRunning` is NOT a failure** — a first full offsite snapshot legitimately runs for hours. State is **in-memory on purpose**: a restart forgets the backoff and re-attempts, which is the cheap direction to fail. Log the deferral ONCE when armed, never per tick. |
|
||||||
| `quiesce.TierNotifier` + `Loop.SetTierNotifier` / `noteTierFailure` / `noteTierSuccess` | controller/internal/quiesce/breaker.go, quiesce.go | `BackupFailed(tier,msg,err)` / `BackupRecovered(tier,msg)`; `SetTierNotifier(n)` INIT-ONLY | **R-97a** — the whole-guest backup tier reports its outcome to the hub | A **seam, not an import** — quiesce keeps no dependency on `internal/notify` (same reason `windowStartFn` is injected). Wired by a setter because main.go builds the notifier AFTER the loop; `nil` = unprovisioned guest, not an error. **Edge-triggered:** failure fires only when the breaker ARMS (`n == 1`), never per retry — the cadence is 15m/30m/1h/2h/4h and an event per attempt is an inbox nobody reads. Recovery rides `recordSuccess`'s existing bool. **Event types are OPERATOR-ONLY** (`whole_guest_backup_failed`/`_recovered`, hub >= v0.78.0) — NOT `backup_failed`, which has a customerMessages entry AND sits in live `enabled_events`, so it would email the CUSTOMER about a backup they cannot act on. `WholeGuestBackupDetails.Tier` is load-bearing: the hub keys its per-tier cooldown on it. |
|
| `quiesce.TierNotifier` + `Loop.SetTierNotifier` / `noteTierFailure` / `noteTierSuccess` | controller/internal/quiesce/breaker.go, quiesce.go | `BackupFailed(tier,msg,err)` / `BackupRecovered(tier,msg)`; `SetTierNotifier(n)` INIT-ONLY | **R-97a** — the whole-guest backup tier reports its outcome to the hub | A **seam, not an import** — quiesce keeps no dependency on `internal/notify` (same reason `windowStartFn` is injected). Wired by a setter because main.go builds the notifier AFTER the loop; `nil` = unprovisioned guest, not an error. **Edge-triggered:** failure fires only when the breaker ARMS (`n == 1`), never per retry — the cadence is 15m/30m/1h/2h/4h and an event per attempt is an inbox nobody reads. Recovery rides `recordSuccess`'s existing bool. **Event types are OPERATOR-ONLY** (`whole_guest_backup_failed`/`_recovered`, hub >= v0.78.0) — NOT `backup_failed`, which has a customerMessages entry AND sits in live `enabled_events`, so it would email the CUSTOMER about a backup they cannot act on. `WholeGuestBackupDetails.Tier` is load-bearing: the hub keys its per-tier cooldown on it. |
|
||||||
| `quiesce.Loop.SuppressedStacks` + `markQuiesced` / `markUnquiesced` | controller/internal/quiesce/suppress.go | `() map[string]bool` (nil-safe on a nil *Loop) | **R-97b** — an app THIS controller stopped for a backup is not a fault | Consumed at the SINGLE derivation point `classifyRunStates` (which computes both the banner dead-list and the notifier Down-set — keep it one place). **Cycle-keyed, not state-based:** v0.164.0's `!= StateStopped` filter cannot see an app caught MID-RESTART (`starting`/`unhealthy`), which is how BookStack alarmed on 2026-07-27. The window (`quiesceAlarmGrace` = 180 s, derived from the deploy flow's 120 s health timeout and Mealie's 60 s start_period) **EXPIRES** — permanent suppression turns a loud false alarm into a silent real one. Open-ended while the cycle runs (a first offsite snapshot legitimately takes hours). **This set alone is NOT the whole answer** — see `AppStopGuard.SuppressedStacks` (R-330) for the per-app operations; `classifyRunStates` consumes the union of both. |
|
| `quiesce.Loop.SuppressedStacks` + `markQuiesced` / `markUnquiesced` | controller/internal/quiesce/suppress.go | `() map[string]bool` (nil-safe on a nil *Loop) | **R-97b** — an app THIS controller stopped for a backup is not a fault | Consumed at the SINGLE derivation point `classifyRunStates` (which computes both the banner dead-list and the notifier Down-set — keep it one place). **Cycle-keyed, not state-based:** v0.164.0's `!= StateStopped` filter cannot see an app caught MID-RESTART (`starting`/`unhealthy`), which is how BookStack alarmed on 2026-07-27. The window (`quiesceAlarmGrace` = 180 s, derived from the deploy flow's 120 s health timeout and Mealie's 60 s start_period) **EXPIRES** — permanent suppression turns a loud false alarm into a silent real one. Open-ended while the cycle runs (a first offsite snapshot legitimately takes hours). **This set alone is NOT the whole answer** — see `AppStopGuard.SuppressedStacks` (R-330) for the per-app operations; `classifyRunStates` consumes the union of both. |
|
||||||
@@ -131,6 +150,7 @@
|
|||||||
|
|
||||||
| Symbol | File | Short signature | Use for | Gotchas |
|
| Symbol | File | Short signature | Use for | Gotchas |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
|
| `stacks.Manager.admitCompose` / `privpolicy.Admit` (v0.328.0, R-971) | controller/internal/stacks/allowlist.go, controller/internal/privpolicy/privpolicy.go | `admitCompose(name, data, env) error` | THE question before ANY write of an app compose (and before a settings change or restore commits an env): the box's catalog allow-list on the RENDERED compose | A new compose writer must call it first — `TestAllowList_IsWiredIntoEveryComposeWriter` fails otherwise; a refusal records the page line + one hub event per definition; the allow-list is `privpolicy/allowlist.json` (exact app+service+setting; EMPTY since v0.329.0) plus `appdata_folders` (an app's `${HDD_PATH}/appdata/<folder>` when the folder is not its name — `privpolicy.AppdataFolder`, R-1142), and the catalog's `scripts/privilege-allowlist.json` must stay byte-identical |
|
||||||
| `Manager.DeployStack` | controller/internal/stacks/deploy.go | `(req DeployRequest) (string, error)` | Full deploy flow | Sets in-memory `Deployed` BEFORE compose up (slow-pull race), reverts on failure |
|
| `Manager.DeployStack` | controller/internal/stacks/deploy.go | `(req DeployRequest) (string, error)` | Full deploy flow | Sets in-memory `Deployed` BEFORE compose up (slow-pull race), reverts on failure |
|
||||||
| `DeclaredVolumeNames` (R-658, v0.268.0) | controller/internal/stacks/undo.go | `(composePath) (own, external []string, err)` | THE app's named volumes as Docker names them: `name:` else `<project>_<key>`, project = top-level `name:` else the stack dir | **Never select an app's volumes by the `com.docker.compose.project` label** — a restore before v0.268.0 made volumes without it, and the undo then copied nothing (R-658). The label is a cross-check only |
|
| `DeclaredVolumeNames` (R-658, v0.268.0) | controller/internal/stacks/undo.go | `(composePath) (own, external []string, err)` | THE app's named volumes as Docker names them: `name:` else `<project>_<key>`, project = top-level `name:` else the stack dir | **Never select an app's volumes by the `com.docker.compose.project` label** — a restore before v0.268.0 made volumes without it, and the undo then copied nothing (R-658). The label is a cross-check only |
|
||||||
| `renderDigests` / `RenderWithLadderDigests` / `CarryDigests` / `StripDigest` (v0.269.0/.1) | controller/internal/stacks/digest.go | compose bytes → the same with `ref@sha256` from the ladder entry for its refs | writing a compose that RUNS (update; the sync for an app NOT yet installed) — an INSTALLED app's sync uses `CarryDigests` (v0.269.1), which keeps the digest the app runs | Pins and records are digest-free by construction (`parseComposeImagesBytes` and the installed record strip) — never compare a raw `.Config.Image` against a pin |
|
| `renderDigests` / `RenderWithLadderDigests` / `CarryDigests` / `StripDigest` (v0.269.0/.1) | controller/internal/stacks/digest.go | compose bytes → the same with `ref@sha256` from the ladder entry for its refs | writing a compose that RUNS (update; the sync for an app NOT yet installed) — an INSTALLED app's sync uses `CarryDigests` (v0.269.1), which keeps the digest the app runs | Pins and records are digest-free by construction (`parseComposeImagesBytes` and the installed record strip) — never compare a raw `.Config.Image` against a pin |
|
||||||
@@ -148,9 +168,9 @@
|
|||||||
| `backup.AppStopGuard` (`Begin`/`End`/`Recover`) (R-166, v0.189.0) | controller/internal/backup/appstop_marker.go | `(opID, reason, stacks) error` / `()` / `() *AppStopRecovery` | THE crash marker for stop→work→start windows (volume dump, offbox reconstitute, `.fab` export) | Its **own** file (`appstop-state.json`), never quiesce's — one file, one writer. **A `defer` is NOT the mechanism** (Campaign 8 fault 10: SIGKILL runs no defer); the marker is. Written BEFORE the stop, cleared ONLY after a restart that succeeded; a FAILED restart deliberately KEEPS it. `Recover` RETURNS its outcome rather than notifying, because it must complete before the boot reconciler while the notifier does not exist yet |
|
| `backup.AppStopGuard` (`Begin`/`End`/`Recover`) (R-166, v0.189.0) | controller/internal/backup/appstop_marker.go | `(opID, reason, stacks) error` / `()` / `() *AppStopRecovery` | THE crash marker for stop→work→start windows (volume dump, offbox reconstitute, `.fab` export) | Its **own** file (`appstop-state.json`), never quiesce's — one file, one writer. **A `defer` is NOT the mechanism** (Campaign 8 fault 10: SIGKILL runs no defer); the marker is. Written BEFORE the stop, cleared ONLY after a restart that succeeded; a FAILED restart deliberately KEEPS it. `Recover` RETURNS its outcome rather than notifying, because it must complete before the boot reconciler while the notifier does not exist yet |
|
||||||
| `backup.AppStopGuard.SuppressedStacks` + `markStopped` / `releaseStarted` / `ReleaseFailed` (R-330, v0.224.0) | controller/internal/backup/appstop_suppress.go | `() map[string]bool` (nil-safe on a nil *AppStopGuard); `ReleaseFailed(stacks ...string)` | **R-330** — an app a PER-APP operation is holding stopped (nightly volume dump, offbox reconstitute, `.fab` export) is not a fault | The **twin** of `quiesce.Loop.SuppressedStacks` above, and the two are unioned by `unionSuppressed` in main.go before `classifyRunStates` — **consult BOTH or the bug comes back**: R-330 shipped because the alarm read only the quiesce set while the per-app legs stopped apps through a different path. Rides `Begin`/`End`, so all three call sites got it with no call-site change. Grace is `appStopAlarmGrace` = 180 s, deliberately the SAME constant and derivation as quiesce's — two windows over one alarm that disagreed would be a bug on whichever path used the shorter one. **It must never latch**, and unlike quiesce's loop `End()` runs ONLY on a restart that succeeded: (1) every failure path calls `ReleaseFailed`, which drops the entry IMMEDIATELY so the app alarms on the next scan; (2) `Begin` REPLACES the set (one marker file = one operation); (3) `appStopMaxHold` (6 h) caps an open-ended hold and logs at WARN. **Deliberately NOT persisted** — after a crash the guard holds nothing and a down app must alarm. `ReleaseFailed` drops the suppression and KEEPS the durable marker; the two are independent and a test pins that |
|
| `backup.AppStopGuard.SuppressedStacks` + `markStopped` / `releaseStarted` / `ReleaseFailed` (R-330, v0.224.0) | controller/internal/backup/appstop_suppress.go | `() map[string]bool` (nil-safe on a nil *AppStopGuard); `ReleaseFailed(stacks ...string)` | **R-330** — an app a PER-APP operation is holding stopped (nightly volume dump, offbox reconstitute, `.fab` export) is not a fault | The **twin** of `quiesce.Loop.SuppressedStacks` above, and the two are unioned by `unionSuppressed` in main.go before `classifyRunStates` — **consult BOTH or the bug comes back**: R-330 shipped because the alarm read only the quiesce set while the per-app legs stopped apps through a different path. Rides `Begin`/`End`, so all three call sites got it with no call-site change. Grace is `appStopAlarmGrace` = 180 s, deliberately the SAME constant and derivation as quiesce's — two windows over one alarm that disagreed would be a bug on whichever path used the shorter one. **It must never latch**, and unlike quiesce's loop `End()` runs ONLY on a restart that succeeded: (1) every failure path calls `ReleaseFailed`, which drops the entry IMMEDIATELY so the app alarms on the next scan; (2) `Begin` REPLACES the set (one marker file = one operation); (3) `appStopMaxHold` (6 h) caps an open-ended hold and logs at WARN. **Deliberately NOT persisted** — after a crash the guard holds nothing and a down app must alarm. `ReleaseFailed` drops the suppression and KEEPS the durable marker; the two are independent and a test pins that |
|
||||||
| `backup.ErrStartRefused` + `AppStopRecovery.Refused`/`Alarming()` (R-174, v0.191.0) | controller/internal/backup/appstop_marker.go | `errors.Is(err, ErrStartRefused)` / `() bool` | THE refusal-vs-failure split in the app-stop crash recovery | **A gated starter's refusal is NOT a restart failure.** `Recover`'s starter MUST be the gated `gatedAppStopStarter` (cmd/controller/main.go), never the raw `stacks.Manager` — that was the v0.189.0 defect, which started apps onto ABSENT drives at boot (R-171 one path over). A refusal goes to `Refused` (marker KEPT, silent), a real error to `Failed` (marker kept, ALARMS). Collapsing them routes a deliberate hold into `NotifyBackupFailed`, a customer-enabled type — the R-171 false alarm again. `main.go` must guard the notify with `Alarming()`, not `!= nil` |
|
| `backup.ErrStartRefused` + `AppStopRecovery.Refused`/`Alarming()` (R-174, v0.191.0) | controller/internal/backup/appstop_marker.go | `errors.Is(err, ErrStartRefused)` / `() bool` | THE refusal-vs-failure split in the app-stop crash recovery | **A gated starter's refusal is NOT a restart failure.** `Recover`'s starter MUST be the gated `gatedAppStopStarter` (cmd/controller/main.go), never the raw `stacks.Manager` — that was the v0.189.0 defect, which started apps onto ABSENT drives at boot (R-171 one path over). A refusal goes to `Refused` (marker KEPT, silent), a real error to `Failed` (marker kept, ALARMS). Collapsing them routes a deliberate hold into `NotifyBackupFailed`, a customer-enabled type — the R-171 false alarm again. `main.go` must guard the notify with `Alarming()`, not `!= nil` |
|
||||||
| `Manager.DeleteStack` / `RemoveStack` | controller/internal/stacks/delete.go | `(name, removeHDDData[, backupPaths])` | THE guarded removal paths | Orphan/protected/deploying/running checks + ProtectedHDDPaths filter before any RemoveAll. **R-442 (v0.236.0): the drive is the app's OWN `app.yaml` `HDD_PATH` (`appHDDPath`), never `cfg.Paths.HDDPath`; a data removal that cannot be resolved returns a typed `*RemoveRefusedError` BEFORE `compose down` — handlers `errors.As` it to 409 + `Message`** |
|
| `Manager.DeleteStack` / `RemoveStack` | controller/internal/stacks/delete.go | `(name, removeHDDData[, backupPaths])` | THE guarded removal paths | Orphan/protected/deploying/running checks + ProtectedHDDPaths filter before any RemoveAll. **R-442 (v0.236.0): the drive is the app's OWN `app.yaml` `HDD_PATH` (`appHDDPath`), never a global (`cfg.Paths.HDDPath` was deleted in R-492); a data removal that cannot be resolved returns a typed `*RemoveRefusedError` BEFORE `compose down` — handlers `errors.As` it to 409 + `Message`** |
|
||||||
| `resolveContainerState` / `aggregateState` | controller/internal/stacks/manager.go | `(dockerState, dockerStatus)` / `([]ContainerInfo)` | State classification | `.State` says "running" even when unhealthy — `.Status` parse is the fix |
|
| `resolveContainerState` / `aggregateState` | controller/internal/stacks/manager.go | `(dockerState, dockerStatus)` / `([]ContainerInfo)` | State classification | `.State` says "running" even when unhealthy — `.Status` parse is the fix |
|
||||||
| `Manager.recordInstalledImages` (v0.233.0) | controller/internal/stacks/installed.go | `(name, stackDir string, env []string)` | writing down what each compose SERVICE is ACTUALLY running, into `app.yaml.installed_images` | Called after a successful compose up from `StartStack`/`RestartStack`/`UpdateStack`/`runComposeDeploy`. **Reads the CONTAINER, never `docker-compose.yml`** — that file is the value the syncer has already moved (spike §3: 25 minutes of disagreement). **A failed write NEVER refuses the action** — the deliberate OPPOSITE of `SetDesiredState`: intent refused, observation logged at ERROR. **NOT from `StartStackServices`** (the R-47 DB-only window would overwrite a complete record with a partial one). Skips the write when ref+digest are unchanged, and carries `at` forward so it means "running since". Its OWN seam (`installedExecFn`) with a **context + 30 s timeout** — the two existing exec helpers have neither |
|
| `Manager.recordInstalledImages` (v0.233.0) | controller/internal/stacks/installed.go | `(name, stackDir string, env []string)` | writing down what each compose SERVICE is ACTUALLY running, into `app.yaml.installed_images` | Called after a successful compose up from `StartStack`/`RestartStack`/the deploy path/the end of the guarded update and of the undo (`UpdateStack` was deleted in v0.237.0). **Reads the CONTAINER, never `docker-compose.yml`** — that file is the value the syncer has already moved (spike §3: 25 minutes of disagreement). **A failed write NEVER refuses the action** — the deliberate OPPOSITE of `SetDesiredState`: intent refused, observation logged at ERROR. **NOT from `StartStackServices`** (the R-47 DB-only window would overwrite a complete record with a partial one). Skips the write when ref+digest are unchanged, and carries `at` forward so it means "running since". Its OWN seam (`installedExecFn`) with a **context + 30 s timeout** — the two existing exec helpers have neither |
|
||||||
| `Manager.SetPin` / `AdoptPins` / `RenderPlanFor` / `AppliedComposePath` (v0.235.0) | controller/internal/stacks/pin.go | `SetPin(name, stackDir, pin, composeSrc) error` | THE version freeze — `app.yaml.pinned_images` + the stored `applied-compose.yml` | **`PinnedImages` is INTENT, `InstalledImages` is an OBSERVATION — never feed one from the other** (the R-166 category error, one field over). Four writers only: deploy, the guarded update (via `advancePinToCatalog`, which advances the pin and re-renders BEFORE the pull, and REFUSES the update if the pin cannot be written; a failed pull puts the pin BACK via `SetPin`), the restore adapter (this is what closes R-441), and `AdoptPins`. `AdoptPins` reuses `observationCoversTemplate` — do NOT write a second completeness rule — and skips loudly rather than inventing a pin. Absent pin = pre-v0.235.0 behaviour |
|
| `Manager.SetPin` / `AdoptPins` / `RenderPlanFor` / `AppliedComposePath` (v0.235.0) | controller/internal/stacks/pin.go | `SetPin(name, stackDir, pin, composeSrc) error` | THE version freeze — `app.yaml.pinned_images` + the stored `applied-compose.yml` | **`PinnedImages` is INTENT, `InstalledImages` is an OBSERVATION — never feed one from the other** (the R-166 category error, one field over). Four writers only: deploy, the guarded update (via `advancePinToCatalog`, which advances the pin and re-renders BEFORE the pull, and REFUSES the update if the pin cannot be written; a failed pull puts the pin BACK via `SetPin`), the restore adapter (this is what closes R-441), and `AdoptPins`. `AdoptPins` reuses `observationCoversTemplate` — do NOT write a second completeness rule — and skips loudly rather than inventing a pin. Absent pin = pre-v0.235.0 behaviour |
|
||||||
| `Manager.UpdatePreflight` / `StartGuardedUpdate` / `RecoverUpdates` / `ResumeInterruptedUpdates` (v0.237.0) | controller/internal/stacks/update.go | `UpdatePreflight(name) *UpdateRefusal`; `StartGuardedUpdate(name) error` | THE update — refusals, then a 202 job with phases on `Stack.Updating/UpdatePhase/UpdateError` | **Never report an update complete before health is known (R-443).** Every cheap refusal runs BEFORE the intent write. Safety dump BEFORE the pin moves; pin BEFORE pull; pull failure → pin back; health failure → stop + HOLD, pin stays. Journal-before-mutate (`update-journal.json`); `RecoverUpdates` MUST run before the boot sweep and `ResumeInterruptedUpdates` AFTER `SetUpdateGuards`. Seams: `updateComposeFn`, `updateHealthFn`, `updateMemoryFn`, `updateDiskFreeFn`, `updateNowFn` (R-457: the age check and the test read ONE clock). Unwired guards ⇒ every update refused |
|
| `Manager.UpdatePreflight` / `StartGuardedUpdate` / `RecoverUpdates` / `ResumeInterruptedUpdates` (v0.237.0) | controller/internal/stacks/update.go | `UpdatePreflight(name) *UpdateRefusal`; `StartGuardedUpdate(name) error` | THE update — refusals, then a 202 job with phases on `Stack.Updating/UpdatePhase/UpdateError` | **Never report an update complete before health is known (R-443).** Every cheap refusal runs BEFORE the intent write. Safety dump BEFORE the pin moves; pin BEFORE pull; pull failure → pin back; health failure → stop + HOLD, pin stays. Journal-before-mutate (`update-journal.json`); `RecoverUpdates` MUST run before the boot sweep and `ResumeInterruptedUpdates` AFTER `SetUpdateGuards`. Seams: `updateComposeFn`, `updateHealthFn`, `updateMemoryFn`, `updateDiskFreeFn`, `updateNowFn` (R-457: the age check and the test read ONE clock). Unwired guards ⇒ every update refused |
|
||||||
| `stacks.UpdateGuards` + `updateGuardsAdapter` (v0.237.0; tiers v0.239.0) | controller/internal/stacks/update.go, controller/cmd/controller/main.go | `HoldFor`, `Busy`, `RestorePoints`, `CanBackUp`, `BackupNow`, `SafetyDump`, `HoldAfterFailedUpdate` | the ONLY bridge from the update job to the backup side (stacks cannot import backup) | Wired by `stackMgr.SetUpdateGuards` — pinned by `TestSlice4_UpdateGuardsAreWiredAtStartup`. Add a guard HERE, never by importing backup into stacks |
|
| `stacks.UpdateGuards` + `updateGuardsAdapter` (v0.237.0; tiers v0.239.0) | controller/internal/stacks/update.go, controller/cmd/controller/main.go | `HoldFor`, `Busy`, `RestorePoints`, `CanBackUp`, `BackupNow`, `SafetyDump`, `HoldAfterFailedUpdate` | the ONLY bridge from the update job to the backup side (stacks cannot import backup) | Wired by `stackMgr.SetUpdateGuards` — pinned by `TestSlice4_UpdateGuardsAreWiredAtStartup`. Add a guard HERE, never by importing backup into stacks |
|
||||||
@@ -158,7 +178,7 @@
|
|||||||
| `backup.Manager.UpdateRestorePoints` + `CanBackUpApp` (v0.239.0, R-475) | controller/internal/backup/update_guard.go | `(ctx, stack, accept func(UpdateTierPoint) bool) (UpdateTierPoint, bool, []UpdateTierPoint)` | "which backup can this update lean on" — walks Tier 2, 1, 3 and returns the first copy `accept` admits | **The age rule lives in the caller's `accept`** (stacks' `freshRestorePoint`), so it is ONE rule for every tier. **The ORDER is `UpdateTierOrderFor` (v0.241.0, R-479): 2 → 3 → 1 for an app with classified binds (`DataOutsideUnit`), 2 → 1 → 3 otherwise; `UpdateCopyHolds` is the matching phrase for the hold.** Stops at the first accepted copy, so Tier 3 (restic, 15 s bound, unreachable = absent + WARN) is reached only when needed. Seams: `updateTier2PointFn`, `updateTier1PointsFn`, `updateOffsiteTimesFn` (v0.240.0: Tier 3 reads `OffsiteSnapshotTimes` — snapshots only, never the inventory's per-app `stats`). stacks adds R-478's rule: a copy older than `deployed_at` does not count (`usableRestorePoint`). Tier numbers are pinned equal across stacks/backup by `TestR475_TierConstantsAgree` |
|
| `backup.Manager.UpdateRestorePoints` + `CanBackUpApp` (v0.239.0, R-475) | controller/internal/backup/update_guard.go | `(ctx, stack, accept func(UpdateTierPoint) bool) (UpdateTierPoint, bool, []UpdateTierPoint)` | "which backup can this update lean on" — walks Tier 2, 1, 3 and returns the first copy `accept` admits | **The age rule lives in the caller's `accept`** (stacks' `freshRestorePoint`), so it is ONE rule for every tier. **The ORDER is `UpdateTierOrderFor` (v0.241.0, R-479): 2 → 3 → 1 for an app with classified binds (`DataOutsideUnit`), 2 → 1 → 3 otherwise; `UpdateCopyHolds` is the matching phrase for the hold.** Stops at the first accepted copy, so Tier 3 (restic, 15 s bound, unreachable = absent + WARN) is reached only when needed. Seams: `updateTier2PointFn`, `updateTier1PointsFn`, `updateOffsiteTimesFn` (v0.240.0: Tier 3 reads `OffsiteSnapshotTimes` — snapshots only, never the inventory's per-app `stats`). stacks adds R-478's rule: a copy older than `deployed_at` does not count (`usableRestorePoint`). Tier numbers are pinned equal across stacks/backup by `TestR475_TierConstantsAgree` |
|
||||||
| `backup.Manager.Tier2MirrorDirsForApp` / `RemoveTier2Mirrors` + `settings.DeleteAppBackupPrefs` (v0.240.0, R-474 / R-486) | controller/internal/backup/r474_remove_mirrors.go | `(stack) []string`; `(stack, dirs) []string` | deleting an app's backups on removal — the Tier-2 mirror lives on ANOTHER drive, outside RemoveStack's per-app base; the same dirs size the backup card (R-485) | Read the mirror dirs BEFORE the prefs are forgotten. Deletes only `<root>/backups/secondary/<stack>` for a known root; never `_shares`, never a path that merely cleans to it. **The Tier-2 RECORD goes only with `remove_backups`** (R-486) — a removal that keeps the backups must keep the record, or the mirror is unrestorable. Pinned by `TestR474_RemoveHandlerDeletesUnitMirrorAndPrefs` + `TestR486_RemovalKeepsTheTier2RecordUnlessBackupsGo` |
|
| `backup.Manager.Tier2MirrorDirsForApp` / `RemoveTier2Mirrors` + `settings.DeleteAppBackupPrefs` (v0.240.0, R-474 / R-486) | controller/internal/backup/r474_remove_mirrors.go | `(stack) []string`; `(stack, dirs) []string` | deleting an app's backups on removal — the Tier-2 mirror lives on ANOTHER drive, outside RemoveStack's per-app base; the same dirs size the backup card (R-485) | Read the mirror dirs BEFORE the prefs are forgotten. Deletes only `<root>/backups/secondary/<stack>` for a known root; never `_shares`, never a path that merely cleans to it. **The Tier-2 RECORD goes only with `remove_backups`** (R-486) — a removal that keeps the backups must keep the record, or the mirror is unrestorable. Pinned by `TestR474_RemoveHandlerDeletesUnitMirrorAndPrefs` + `TestR486_RemovalKeepsTheTier2RecordUnlessBackupsGo` |
|
||||||
| `appbackup.dbTypeForImage` (R-484, v0.240.0) | controller/internal/appbackup/dbservices.go | `(image) (DBType, bool)` | the ONE place an image is judged a database — nightly dumps, pre-update safety dump, DB-only replay | Derived Postgres images (`postgis`, `pgvector`, `timescaledb`) are Postgres. A new engine image goes HERE and in `dbservices_test.go`'s table, never in a second matcher |
|
| `appbackup.dbTypeForImage` (R-484, v0.240.0) | controller/internal/appbackup/dbservices.go | `(image) (DBType, bool)` | the ONE place an image is judged a database — nightly dumps, pre-update safety dump, DB-only replay | Derived Postgres images (`postgis`, `pgvector`, `timescaledb`) are Postgres. A new engine image goes HERE and in `dbservices_test.go`'s table, never in a second matcher |
|
||||||
| `backup.Manager.HoldAfterFailedUpdate` / `RunAppBackupNow` / `WriteUpdateSafetyDump` / `UpdateBusy` (v0.237.0) | controller/internal/backup/update_guard.go | see file | the update's hold, per-app backup-now, safety dump, busy check | The hold is `settings.RestoreHold` with `Reason: update_failed` — SAME store and gate as R-379, never a second map. `RunAppBackupNow` composes the nightly legs for ONE app (admission, DB dump, volume dump, capture, Tier-2) — do not write a second backup orchestration. A successful unit restore lifts an UPDATE hold only. **`isHeld` is ALSO true while a guarded update is moving the app (`SetUpdatingCheck`, v0.238.1)** — found live: the periodic capture overwrote a primary unit during a health wait |
|
| `backup.Manager.HoldAfterFailedUpdate` / `RunAppBackupNow` / `WriteUpdateSafetyDump` / `UpdateBusy` (v0.237.0) | controller/internal/backup/update_guard.go | see file | the update's hold, per-app backup-now, safety dump, busy check | The hold is `settings.RestoreHold` with `Reason: update_failed` — SAME store and gate as R-379, never a second map. `RunAppBackupNow` composes the nightly legs for ONE app (admission, DB dump, volume dump, capture, Tier-2) — do not write a second backup orchestration. A successful unit restore lifts an UPDATE hold only. **`isHeld` is ALSO true while a guarded update is moving the app (`SetUpdatingCheck`, v0.238.1)** — found live: the periodic capture overwrote a primary unit during a health wait. **R-645: every night leg (DB dump, volume dump, capture, Tier-2) also skips an app whose pin is not what it runs (`versionSkip`, wired by `SetVersionCheck` → `stacks.Manager.PinNotRunning`); unknown never skips. The page line is `VersionSkipFor`** |
|
||||||
| `stacks.Manager.memoryVerdict` (v0.237.0) | controller/internal/stacks/deploy.go | `(newReq, newLimit, releasedReq, releasedLimit int) (refusal, warning string)` | the deploy's memory check, shared with the update | An update RELEASES the app's current request first. Deploy passes `0, 0` and is byte-identical in wording and log line |
|
| `stacks.Manager.memoryVerdict` (v0.237.0) | controller/internal/stacks/deploy.go | `(newReq, newLimit, releasedReq, releasedLimit int) (refusal, warning string)` | the deploy's memory check, shared with the update | An update RELEASES the app's current request first. Deploy passes `0, 0` and is byte-identical in wording and log line |
|
||||||
| `Syncer.SetRenderPlanFn` + `renderSource` (v0.235.0) | controller/internal/sync/sync.go | `func(appName string) stacks.RenderPlan` | the catalog render table | **NIL-SAFE: no seam = copy verbatim = the old product.** Catalog images == pin → verbatim (fixes flow + self-healing, both deliberately kept); differ → the WHOLE stored definition, **never a ref substitution into a newer template** (`wger 2.6`). `.felhom.yml` always verbatim (R-458). The syncer must NEVER read app.yaml. Re-reads the applied file before writing it — a test caught it writing an empty compose over a live app |
|
| `Syncer.SetRenderPlanFn` + `renderSource` (v0.235.0) | controller/internal/sync/sync.go | `func(appName string) stacks.RenderPlan` | the catalog render table | **NIL-SAFE: no seam = copy verbatim = the old product.** Catalog images == pin → verbatim (fixes flow + self-healing, both deliberately kept); differ → the WHOLE stored definition, **never a ref substitution into a newer template** (`wger 2.6`). `.felhom.yml` always verbatim (R-458). The syncer must NEVER read app.yaml. Re-reads the applied file before writing it — a test caught it writing an empty compose over a live app |
|
||||||
| `Stack.CatalogImages` vs `Stack.TemplateImages` (v0.235.0) | controller/internal/stacks/manager.go | both `map[string]string` | badge input vs "what the next `up -d` gives this app" | **THE TRAP: same type, same shape, opposite meaning after the freeze.** `TemplateImages` reads the LIVE (possibly frozen) compose file; `CatalogImages` reads the syncer's clone. `web.compareInstalledToTemplate` MUST use `CatalogImages` or it answers „Naprakész" on exactly the apps that are behind, with every test green. Red-proved |
|
| `Stack.CatalogImages` vs `Stack.TemplateImages` (v0.235.0) | controller/internal/stacks/manager.go | both `map[string]string` | badge input vs "what the next `up -d` gives this app" | **THE TRAP: same type, same shape, opposite meaning after the freeze.** `TemplateImages` reads the LIVE (possibly frozen) compose file; `CatalogImages` reads the syncer's clone. `web.compareInstalledToTemplate` MUST use `CatalogImages` or it answers „Naprakész" on exactly the apps that are behind, with every test green. Red-proved |
|
||||||
@@ -199,6 +219,12 @@
|
|||||||
| `maskRepoURL` | controller/internal/sync/sync.go | `(url) string` | Logging git URLs | Strips embedded credentials |
|
| `maskRepoURL` | controller/internal/sync/sync.go | `(url) string` | Logging git URLs | Strips embedded credentials |
|
||||||
| `metrics.RedactLine` | controller/internal/metrics/redact.go | `(s string) string` | ANY log line shipped off-box (issue context, log tails) | Masks password/passwd/secret/token/api-key/authorization/bearer values + 64-hex; apply BEFORE the line leaves the box — controller-side redaction is authoritative |
|
| `metrics.RedactLine` | controller/internal/metrics/redact.go | `(s string) string` | ANY log line shipped off-box (issue context, log tails) | Masks password/passwd/secret/token/api-key/authorization/bearer values + 64-hex; apply BEFORE the line leaves the box — controller-side redaction is authoritative |
|
||||||
| `settingsRetrievalPasswordRevealHandler` | controller/internal/web/handlers.go | `POST /settings/retrieval-password/reveal` | **THE PATTERN for showing a secret in the UI** — an XHR that returns only the value | **Never template a secret into a page and hide it with CSS.** `display:none` / `hidden` / `type="password"` stop a browser DRAWING the value; the plaintext is still in the response body, so a `curl` of the page returns it, and it reaches caches, history and any screen-share of the source. R-249 shipped exactly that for two months and was found by it landing in a transcript. The page carries a **boolean** (`HasRetrievalPassword`); the value comes from a POST (CSRF-covered, uncacheable) and the reveal is **logged as an act**. `escrow_handlers.go` states the same rule for R. **Test on the RESPONSE BODY** — a test asserting what the customer *sees* cannot see this class at all. **Both R-254 sites are now FIXED the same way** — `POST /apps/<slug>/initial-credentials/reveal` (re-reads the container, never a cached copy) and `POST /stacks/<name>/auto-field/reveal` (authorised on the field being a `type: secret` auto-field of that stack). **Per-secret, never one generic reveal-any-named-secret endpoint.** The PRE-DEPLOY hidden input is deliberate and untouched — a form must carry what it submits (README §318). Enforced by `scripts/secret_in_markup_gate.py`, whose measured blind spot (a secret under a neutral page-data key) is in its docstring; runtime body-assertion covers 4 of 27 pages — R-255. |
|
| `settingsRetrievalPasswordRevealHandler` | controller/internal/web/handlers.go | `POST /settings/retrieval-password/reveal` | **THE PATTERN for showing a secret in the UI** — an XHR that returns only the value | **Never template a secret into a page and hide it with CSS.** `display:none` / `hidden` / `type="password"` stop a browser DRAWING the value; the plaintext is still in the response body, so a `curl` of the page returns it, and it reaches caches, history and any screen-share of the source. R-249 shipped exactly that for two months and was found by it landing in a transcript. The page carries a **boolean** (`HasRetrievalPassword`); the value comes from a POST (CSRF-covered, uncacheable) and the reveal is **logged as an act**. `escrow_handlers.go` states the same rule for R. **Test on the RESPONSE BODY** — a test asserting what the customer *sees* cannot see this class at all. **Both R-254 sites are now FIXED the same way** — `POST /apps/<slug>/initial-credentials/reveal` (re-reads the container, never a cached copy) and `POST /stacks/<name>/auto-field/reveal` (authorised on the field being a `type: secret` auto-field of that stack). **Per-secret, never one generic reveal-any-named-secret endpoint.** The PRE-DEPLOY hidden input is deliberate and untouched — a form must carry what it submits (README §318). Enforced by `scripts/secret_in_markup_gate.py`, whose measured blind spot (a secret under a neutral page-data key) is in its docstring; runtime body-assertion covers 4 of 27 pages — R-255. |
|
||||||
|
| `storedValuePresent` / `appLoginFields` | controller/internal/web/app_login.go | the settings tab's login panel and „Cím és kulcsok" rows (v0.319.0) | **A field the box holds no value for is a sentence, never an eye.** `storedValuePresent` is the ONE definition of „stored", read by the page AND by `appAutoFieldRevealHandler`'s 404 branch — so the page cannot offer a reveal the endpoint refuses. The page gets a boolean per login field, never the value (R-254/R-709). Pinned by `TestAppPage_NoStoredValueShowsSentence`. |
|
||||||
|
| `loginAnswerFor` | controller/internal/web/app_login.go | the settings tab's ONE login answer (v0.320.0) | `fields` · `initial` · the catalog's `app_info.login_kind` via `AppInfo.EffectiveLoginKind` (`first_visit` default; an unknown value reads as it). An infra stack with no login gets no panel. Pinned by `TestAppPage_EveryInstalledAppHasOneLoginAnswer`. |
|
||||||
|
| `filesButtonLink` / `mediaFolderCards` / `drivePresent` | controller/internal/web/datapath_card.go | the „Fájlok ↗" target and the media folder rows (v0.320.0) | **A folder whose drive is not bound into FileBrowser now is TEXT, never a link** — `drivePresent` reads `stacks.PresentMediaDrives` (the same gates `buildFileBrowserPaths` applies); tests seam it with `Server.presentDrivesFn`. Links only through `fileBrowserOpenLink` (R-1100; the folder path built by `fileBrowserLink`). Pinned by `TestAppPage_FilesButtonTarget`, `_UnknownSourceIsTextNotLink`. |
|
||||||
|
| `infraMetaIn` | controller/internal/web/inframeta.go | an infra stack's curated name/description in a language | The ONE place for both the `infraMeta` template func and the app page. |
|
||||||
|
| `Manager.FileBrowserStoredPasswordRefused` | controller/internal/stacks/filebrowser_password.go | is the stored FileBrowser password still valid (v0.321.0, R-1101) | TRUE only on FileBrowser's own 401/403 in the `generated` state; FileBrowser not answering is FALSE (an unproven refusal must not tell the household its password changed). 3 s bound. Web seam: `Server.fbStoredRefused`. |
|
||||||
|
| `Manager.ResetFileBrowserAdminPassword` | controller/internal/stacks/filebrowser_password.go | FileBrowser's admin password without the old one (v0.320.0) | Only in `operator`; holds `infraMu` (the base tick must not start the stopped server), and the web handler holds `fileBrowserMu` (the mount sync must not recreate it). Stop → `docker run --rm --volumes-from filebrowser … set -u admin,<pw>` → start (detached from the request's cancel) → verify → store encrypted. TRAP: the CLI opens the DB with no lock timeout — never run it against a running server. Seam: `fbSetPassword`. |
|
||||||
|
|
||||||
### Storage registry + mount detection
|
### Storage registry + mount detection
|
||||||
|
|
||||||
@@ -209,6 +235,11 @@
|
|||||||
| `registerStoragePath` | controller/internal/web/storage_handlers.go | `(where, label, setDefault) error` | Post-enroll registration | The single funnel used by init/attach/manual-add |
|
| `registerStoragePath` | controller/internal/web/storage_handlers.go | `(where, label, setDefault) error` | Post-enroll registration | The single funnel used by init/attach/manual-add |
|
||||||
| `system.IsMountPoint` / `IsWritable` / `PathsOverlap` | controller/internal/system/mounts_linux.go | `(path) bool` | Mount checks | `_other.go` stubs return permissive values — Linux behavior is the real one |
|
| `system.IsMountPoint` / `IsWritable` / `PathsOverlap` | controller/internal/system/mounts_linux.go | `(path) bool` | Mount checks | `_other.go` stubs return permissive values — Linux behavior is the real one |
|
||||||
| `system.CheckBackupDestination` | controller/internal/system/mounts_linux.go | `(path) DestinationHealth` | Tier2/offbox target vetting | Detects same-physical-device (`SamePhysicalDevice`) |
|
| `system.CheckBackupDestination` | controller/internal/system/mounts_linux.go | `(path) DestinationHealth` | Tier2/offbox target vetting | Detects same-physical-device (`SamePhysicalDevice`) |
|
||||||
|
| `system.FilesystemKey` (R-1371) | controller/internal/system/fskey.go | `(path) (key uint64, ok bool)` | "Are these two paths ONE filesystem?" — the fill watch's de-duplication | **Never compare `st_dev` (or `SamePhysicalDevice`) for a path that may be the container's "/"**: an overlay has its own device number and filesystem id. An overlay path gets the device of a Docker-kept file (`/etc/hostname` …) that lies on the data-root. `ok=false` = cannot tell → treat as a filesystem of its own. Seam: `filesystemKeyWith` |
|
||||||
|
| `backup.Manager.diskRelation` | controller/internal/backup/backup.go | `(a, b) (DiskRelation, reason)` — DiskDifferent / DiskSame / DiskUnknown | EVERY Tier-2 or one-copy "same disk?" decision (v0.317.0, felhom.eu `16-storage-physical-identity.md` §4) | Asks the host agent (`SetDiskJudge`, FeatureSameDisk ≥ agent 0.157.0); an older agent or an `unmapped` path → the old `sameDevice`/st_dev rule. Never call `sameDevice` directly for a Tier-2 decision — st_dev calls two partitions of one disk "different". Pinned by diskrelation_test.go |
|
||||||
|
| `web.Server.ensureInternalPlace` / `refuseInternalLifecycle` | controller/internal/web/internal_place.go | drive-gate tick hook; `(w, r, where) bool` | the internal data place (v0.318.0, `16` §5): bind on one tick, register (kind internal, default when none) on the next; refuse eject/decommission/wipe | Only an agent row of kind `internal` is enrolled without a press — a household drive never is. Pinned by internal_place_test.go + stacks d4_needs_drive_test.go (a media app lands on it) |
|
||||||
|
| `web.Server.offerRelationFor` | controller/internal/web/backup_target_offer.go | `(ctx, drive) offerRelation` (sameDiskFn seam) | the whole-box backup offer's disk question (R-1084) | Older agent → today's offer; an error → no promise. Pinned by r1084_offer_identity_test.go |
|
||||||
|
| `web.withoutSystemVolume` / `deviceBacksRegistered` / `freePartitions` | controller/internal/web/attach_sources.go, agent_disk_handlers.go | pure filters | R-1082 (sys_drive never offered, by device) and partitions (`16` §6: free parts of an in-use disk stay, the whole disk never; server-side refusal) | Pinned by r1082_sysdrive_hidden_test.go + partitions_test.go |
|
||||||
| `system.ProbeStoragePath` | controller/internal/system/mounts_linux.go | `(path) ProbeResult` | Disconnect detection | — |
|
| `system.ProbeStoragePath` | controller/internal/system/mounts_linux.go | `(path) ProbeResult` | Disconnect detection | — |
|
||||||
| `appexport.DiskFree` | controller/internal/appexport/estimate.go | `(path) int64` | Free bytes for space gates (df-based, 0 on any error) | Exported v0.128.0 for the browser-upload gate; test seam = `web.uploadDiskFree` package var |
|
| `appexport.DiskFree` | controller/internal/appexport/estimate.go | `(path) int64` | Free bytes for space gates (df-based, 0 on any error) | Exported v0.128.0 for the browser-upload gate; test seam = `web.uploadDiskFree` package var |
|
||||||
| `stacks.ExportDataMounts` | controller/internal/stacks/delete.go | `(composePath, hddPath) []string` | THE .fab-export mount discovery (v0.130.0 C6B-F1) | Unions `${HDD_PATH}` binds + the `${USERDATA_PATH}` ROOT (single `userdata` entry — basename must round-trip the import's `<HDD_PATH>/<subdir>` mapping; NEVER return per-bind userdata subpaths). Containment-deduped. Backup-side `stackAdapter` deliberately does NOT use it |
|
| `stacks.ExportDataMounts` | controller/internal/stacks/delete.go | `(composePath, hddPath) []string` | THE .fab-export mount discovery (v0.130.0 C6B-F1) | Unions `${HDD_PATH}` binds + the `${USERDATA_PATH}` ROOT (single `userdata` entry — basename must round-trip the import's `<HDD_PATH>/<subdir>` mapping; NEVER return per-bind userdata subpaths). Containment-deduped. Backup-side `stackAdapter` deliberately does NOT use it |
|
||||||
@@ -225,7 +256,7 @@
|
|||||||
| `agentapi.New` | controller/internal/agentapi/client.go | `(endpoint, token, fingerprintHex) (*Client, error)` | Pinned-TLS client to felhom-agent | Leaf-DER SHA-256 pin replaces chain verify; fails closed. Bounded idle pool (leak fix) |
|
| `agentapi.New` | controller/internal/agentapi/client.go | `(endpoint, token, fingerprintHex) (*Client, error)` | Pinned-TLS client to felhom-agent | Leaf-DER SHA-256 pin replaces chain verify; fails closed. Bounded idle pool (leak fix) |
|
||||||
| `Server.agentClient` | controller/internal/web/agent_disk_handlers.go | `() (*agentapi.Client, error)` | THE memoized client accessor | Always use this, never a fresh `agentapi.New` per request (§3) |
|
| `Server.agentClient` | controller/internal/web/agent_disk_handlers.go | `() (*agentapi.Client, error)` | THE memoized client accessor | Always use this, never a fresh `agentapi.New` per request (§3) |
|
||||||
| `Server.ProbeAgentChannel` | controller/internal/web/agent_disk_handlers.go | `(ctx) (constructionErr bool, err error)` | Channel health probe | Probes via the PRODUCTION client on purpose (self-heals, mirrors UI) |
|
| `Server.ProbeAgentChannel` | controller/internal/web/agent_disk_handlers.go | `(ctx) (constructionErr bool, err error)` | Channel health probe | Probes via the PRODUCTION client on purpose (self-heals, mirrors UI) |
|
||||||
| `Client.FormatDisk` | controller/internal/agentapi/client.go | `(ctx, device, fstype, confirmed, durableID)` | ONLY format/wipe entry | Sentinels: `ErrNeedsConfirmation` (user-data, resubmit confirmed+durableID) / `ErrFormatRefused` (system/backup — operator opsign only). Agent re-checks role server-side |
|
| `Client.FormatDisk` | controller/internal/agentapi/client.go | `(ctx, device, fstype, confirmed, durableID)` | ONLY format/wipe entry | Sentinels: `ErrNeedsConfirmation` (user-data, resubmit confirmed+durableID) / `ErrFormatRefused` (system/backup — operator opsign only) / `ErrNoDurableID` (v0.329.0, R-1069: a blank disk with no durable id, e.g. virtio without a serial — show `disk.err.no_durable_id`). Agent re-checks role server-side. `Client.Decommission` returns `*DecommissionRefusedError{Status 403|409}` for the agent's two policy refusals (R-1063) — ask the agent BEFORE marking anything |
|
||||||
| `Client.EjectDisk` / `Decommission` / `AssignDisk` / `GuestAttach` / `ListCandidates` | controller/internal/agentapi/client.go | disk lifecycle | Delegate ALL disk ops to agent | Controller holds no Proxmox creds — never shell out to disk tools in-guest |
|
| `Client.EjectDisk` / `Decommission` / `AssignDisk` / `GuestAttach` / `ListCandidates` | controller/internal/agentapi/client.go | disk lifecycle | Delegate ALL disk ops to agent | Controller holds no Proxmox creds — never shell out to disk tools in-guest |
|
||||||
| `Client.AddNetStorage/ListNetStorage/RemoveNetStorage` | controller/internal/agentapi/client.go | NAS mounts (A1) | Network storage | Password passes through to agent's 0600 cred file; controller NEVER persists it |
|
| `Client.AddNetStorage/ListNetStorage/RemoveNetStorage` | controller/internal/agentapi/client.go | NAS mounts (A1) | Network storage | Password passes through to agent's 0600 cred file; controller NEVER persists it |
|
||||||
| `agentapi.StatusError` | controller/internal/agentapi/client.go | `{Path, Code}` typed non-2xx GET error | Distinguishing HTTP statuses from transport errors (`errors.As`) | NEVER string-match agent error text — the capability probe keys on `Code==404` |
|
| `agentapi.StatusError` | controller/internal/agentapi/client.go | `{Path, Code}` typed non-2xx GET error | Distinguishing HTTP statuses from transport errors (`errors.As`) | NEVER string-match agent error text — the capability probe keys on `Code==404` |
|
||||||
@@ -242,6 +273,7 @@
|
|||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| `Notifier.PushEvent` | controller/internal/notify/notifier.go | `(eventType, severity, message, details)` | Hub events | Async goroutine, 3 attempts/3s backoff. NEW event types MUST be added to hub `allowedEventTypes` or POST /event 400s. **SEVERITY IS AN EXACT WIRE CONTRACT: `{"info","warning","error","critical"}` and nothing else.** The hub silently COERCES any other string to `"info"` (`hub/internal/api/handler.go`, the ingest severity switch) and `severityNotifies` (`hub/internal/notify/dispatcher.go`) emails only warning/error/critical — so a typo'd severity is stored and delivered to NOBODY, with no error anywhere. **`"warn"` is not a severity.** It shipped on `disk_health_degraded` (fixed v0.215.0, R-328) and is STILL live on `app_start_failed` (R-329) |
|
| `Notifier.PushEvent` | controller/internal/notify/notifier.go | `(eventType, severity, message, details)` | Hub events | Async goroutine, 3 attempts/3s backoff. NEW event types MUST be added to hub `allowedEventTypes` or POST /event 400s. **SEVERITY IS AN EXACT WIRE CONTRACT: `{"info","warning","error","critical"}` and nothing else.** The hub silently COERCES any other string to `"info"` (`hub/internal/api/handler.go`, the ingest severity switch) and `severityNotifies` (`hub/internal/notify/dispatcher.go`) emails only warning/error/critical — so a typo'd severity is stored and delivered to NOBODY, with no error anywhere. **`"warn"` is not a severity.** It shipped on `disk_health_degraded` (fixed v0.215.0, R-328) and is STILL live on `app_start_failed` (R-329) |
|
||||||
| `notify.DiskAlert` / `DiskAlertKind` / `DiskAlertKind.Severity()` | controller/internal/notify/notifier.go | `NotifyDiskHealthDegraded(DiskAlert)` | The disk-health alert payload + its five Hungarian message shapes | The notifier owns customer copy — pass a `DiskAlert`, never a pre-formatted string, or Hungarian scatters across packages. `Severity()` is the ONE mapping kind→hub severity and is exported so any package can assert the contract instead of duplicating the literal |
|
| `notify.DiskAlert` / `DiskAlertKind` / `DiskAlertKind.Severity()` | controller/internal/notify/notifier.go | `NotifyDiskHealthDegraded(DiskAlert)` | The disk-health alert payload + its five Hungarian message shapes | The notifier owns customer copy — pass a `DiskAlert`, never a pre-formatted string, or Hungarian scatters across packages. `Severity()` is the ONE mapping kind→hub severity and is exported so any package can assert the contract instead of duplicating the literal |
|
||||||
|
| `Notifier.PushEventHousehold` (v0.309.0, R-521 F7) | controller/internal/notify/notifier.go | `(eventType, severity, message, household, details)` | A producer that renders BOTH languages itself because its sentence carries figures it computed (fillwatch) | Prefer `pushEventMsg` (one key, both renderings) inside notify; this is for a sentence built outside. `household` "" for a Hungarian household. Registered in the R-329 severity contract (`severityArg`) |
|
||||||
| `Notifier.Notify*` convenience methods | controller/internal/notify/notifier.go | typed wrappers (backup/DB/storage/channel/DR…) | Standard events | Add a typed wrapper rather than raw PushEvent calls |
|
| `Notifier.Notify*` convenience methods | controller/internal/notify/notifier.go | typed wrappers (backup/DB/storage/channel/DR…) | Standard events | Add a typed wrapper rather than raw PushEvent calls |
|
||||||
| `report.BuildReport` / `Pusher.Push` | controller/internal/report/builder.go + pusher.go | periodic hub report | Box→hub reporting | ACK carries `config_version` → `ConfigRefresher.Reconcile` |
|
| `report.BuildReport` / `Pusher.Push` | controller/internal/report/builder.go + pusher.go | periodic hub report | Box→hub reporting | ACK carries `config_version` → `ConfigRefresher.Reconcile` |
|
||||||
| `report.Trigger` (`NewTrigger`/`Fire`/`Run`) | controller/internal/report/trigger.go | `Fire()` after a hub-relevant user action | THE out-of-cycle report push (v0.139.0) — fire via `api.Router.reportPushNow` / `web.Server.reportTriggerNow`, both nil-safe | Coalesce-and-eventually-fire (trailing edge; quiet 2s, min spacing 15s). NEVER add retries (Pusher owns them); NEVER reuse the `internal/sync` REFUSE-debounce for hub pushes (a refused fire loses the update until the next cycle). Fire only AFTER a successful local commit |
|
| `report.Trigger` (`NewTrigger`/`Fire`/`Run`) | controller/internal/report/trigger.go | `Fire()` after a hub-relevant user action | THE out-of-cycle report push (v0.139.0) — fire via `api.Router.reportPushNow` / `web.Server.reportTriggerNow`, both nil-safe | Coalesce-and-eventually-fire (trailing edge; quiet 2s, min spacing 15s). NEVER add retries (Pusher owns them); NEVER reuse the `internal/sync` REFUSE-debounce for hub pushes (a refused fire loses the update until the next cycle). Fire only AFTER a successful local commit |
|
||||||
@@ -250,20 +282,27 @@
|
|||||||
| `ConfigRefresher.Reconcile` | controller/internal/report/config_refresh.go | `(ackVersion int)` | Pull-based config refresh | Re-pulls controller.yaml (re-merging local_api), then graceful self-restart; first-run = baseline, no restart |
|
| `ConfigRefresher.Reconcile` | controller/internal/report/config_refresh.go | `(ackVersion int)` | Pull-based config refresh | Re-pulls controller.yaml (re-merging local_api), then graceful self-restart; first-run = baseline, no restart |
|
||||||
| `offsiteapply.HubRegistrar` / `HubWindowClient` / `PinnedProber` (v0.289.0, decisions 68–69) | controller/internal/offsiteapply/seams.go | `Register(ctx,pub)(fp,err)` · `Confirm` · `MoveAside` · `Open/Close` window · `Probe(ctx,host,user,port,kh,privPEM) bool` | EVERY off-site key install, the hub move-aside, the clean-up window | **The box never handles the sub-account password** — there is no consume path any more. `PinnedProber` is a POSITIVE observable (exit 0 + rclone output); "authenticates" is NOT enough — an unpinned key authenticates and can delete. |
|
| `offsiteapply.HubRegistrar` / `HubWindowClient` / `PinnedProber` (v0.289.0, decisions 68–69) | controller/internal/offsiteapply/seams.go | `Register(ctx,pub)(fp,err)` · `Confirm` · `MoveAside` · `Open/Close` window · `Probe(ctx,host,user,port,kh,privPEM) bool` | EVERY off-site key install, the hub move-aside, the clean-up window | **The box never handles the sub-account password** — there is no consume path any more. `PinnedProber` is a POSITIVE observable (exit 0 + rclone output); "authenticates" is NOT enough — an unpinned key authenticates and can delete. |
|
||||||
| `Manager.offsiteWindowRetention` + `offsiteGuard` (v0.289.0, R-822) | controller/internal/backup/offbox_window.go | `(ctx, base, env, why)` · pure `(all, plan, now, newestAllowed, max) (ids, refuse)` | THE retention step for both callers (after a run, over quota) | Pinned tier: no window → nothing deleted; the guard runs BEFORE any forget; "young" = fewer than `keepDaily` CALENDAR days old (v0.294.0, R-867 — the line is built from the same constants as `retentionPolicy`; never an hour count); a young snapshot superseded the same day is EXCLUDED, any other young removal / future date / plan above `max_remove` REFUSES; tests run restic 0.14.0's policy itself (`restic0140Plan`, proven identical to the binary); forget is by explicit ids, oldest first. A due abandonment goes to `OffsiteAbandonClient` (hub, 7-day wait). NAS tier: the old SP-2 policy, unchanged. |
|
| `Manager.offsiteWindowRetention` + `offsiteGuard` (v0.289.0, R-822) | controller/internal/backup/offbox_window.go | `(ctx, base, env, why)` · pure `(all, plan, now, newestAllowed, max) (ids, refuse)` | THE retention step for both callers (after a run, over quota) | Pinned tier: no window → nothing deleted; the guard runs BEFORE any forget; "young" = fewer than `keepDaily` CALENDAR days old (v0.294.0, R-867 — the line is built from the same constants as `retentionPolicy`; never an hour count); a young snapshot superseded the same day is EXCLUDED, any other young removal / future date / plan above `max_remove` REFUSES; tests run restic 0.14.0's policy itself (`restic0140Plan`, proven identical to the binary); forget is by explicit ids, oldest first. A due abandonment goes to `OffsiteAbandonClient` (hub, 7-day wait). NAS tier: the old SP-2 policy, unchanged. |
|
||||||
|
| `Manager.StartOffsiteEnd` / `KeepOffsiteCopies` + `settings.OffsiteEnd` (D72/D84, felhom.eu `07` §8.2f; built, not released) | controller/internal/backup/offbox_ended.go, controller/internal/settings/offsite_ends.go | `StartOffsiteEnd(app) (rec, created, err)` · pure `dueOffsiteEnds`, `endedCandidates`, `endedToRemove` | The off-site copies of a removed app end 30 days after „delete backup data”: the record, the press, the take-back, and the ended apps' ids in the weekly window | **NO RECORD = NO DELETION.** `StartOffsiteEnd` is the ONLY writer (it sends the household's one mail when it really wrote); an install deletes the record (`stacks.DeployStack`). The window removes an ended app's snapshot only when every app tag on it is a due record, the hub sent its id back (`OffsiteWindow.EndedAllowed`) and the box named it in the same window. `SetOffsiteEndLiving` not wired → nothing is ever due (wired to `stacks.Manager.IsLivingApp`). Only on the hub-provisioned (pinned) tier. **„The app became installed” is ONE point: `stacks.SaveAppConfig` → `noteAppInstalled`** — never add a second writer of an app's `app.yaml` (`TestD72_TheInstallWritersAreListed`). The window reads the records again right before the forget (`lastLookAtEnded`). |
|
||||||
| `offsiteapply.SettleProvider` / `SettleFunc` / `Bridge.AwaitSettle` / `ReconcileWhenSettled` (R-71a, v0.162.0) | controller/internal/offsiteapply/offsiteapply.go + seams.go | `SettleState() (version, floor string, updateRunning, floorKnown bool)` | THE settle-gate: defers the offsite one-time-password consume past a managed day-0 floor-update (the F10 race). Wire the `SettleFunc` adapter over `updater.GetFloor()`/`IsUpdateRunning()` — **the updater's knowledge is the ONE floor source; never fetch the floor a second way**. Gate ONLY the bridge goroutine, and only when an updater exists (nil `Settle` = reconcile immediately). Bounds `settlePoll`/`settleFloorSubBound`/`settleOverallBound`; the floor is in-memory (report-ACK-derived, ~5–10 s), NOT persisted → unknown until the first ACK on any restart. Inject `Now`/`Sleep` in tests (no real sleeps). B′: at/above-floor GOes on the first poll, zero wait. Do NOT touch the consume/persist order or the 404 contract — ordering only |
|
| `offsiteapply.SettleProvider` / `SettleFunc` / `Bridge.AwaitSettle` / `ReconcileWhenSettled` (R-71a, v0.162.0) | controller/internal/offsiteapply/offsiteapply.go + seams.go | `SettleState() (version, floor string, updateRunning, floorKnown bool)` | THE settle-gate: defers the offsite one-time-password consume past a managed day-0 floor-update (the F10 race). Wire the `SettleFunc` adapter over `updater.GetFloor()`/`IsUpdateRunning()` — **the updater's knowledge is the ONE floor source; never fetch the floor a second way**. Gate ONLY the bridge goroutine, and only when an updater exists (nil `Settle` = reconcile immediately). Bounds `settlePoll`/`settleFloorSubBound`/`settleOverallBound`; the floor is in-memory (report-ACK-derived, ~5–10 s), NOT persisted → unknown until the first ACK on any restart. Inject `Now`/`Sleep` in tests (no real sleeps). B′: at/above-floor GOes on the first poll, zero wait. Do NOT touch the consume/persist order or the 404 contract — ordering only |
|
||||||
| `bootstrap.MaybeIngest` / `RefreshConfig` | controller/internal/bootstrap/bootstrap.go | bootstrap.json → controller.yaml | Day-0 + refresh | Overwrites controller.yaml, NEVER settings.json |
|
| `bootstrap.MaybeIngest` / `RefreshConfig` | controller/internal/bootstrap/bootstrap.go | bootstrap.json → controller.yaml | Day-0 + refresh | Overwrites controller.yaml, NEVER settings.json |
|
||||||
| `api.GracefulSelfRestart` | controller/internal/api/selfrestart.go | `(logger)` | Controller self-restart | Detached exit; bootstrap unit re-runs the image |
|
| `api.GracefulSelfRestart` | controller/internal/api/selfrestart.go | `(logger)` | Controller self-restart | Detached exit; bootstrap unit re-runs the image |
|
||||||
|
| `settings.NotificationGroups` + `NotificationGroupState` / `NotificationPrefs.GroupState` (R-388 slice 1, v0.309.0) | controller/internal/settings/notif_groups.go | `(enabled []string, key) "on"\|"off"\|"custom"` | THE `08` §8.1 group membership of every customer-switchable detector — the notification page's three switches | A group is a VIEW over `enabled_events`, never a stored field. A new detector with a page switch MUST join exactly one group (`TestR388_EveryPageSwitchIsInExactlyOneGroup` fails otherwise). The save rule lives in `Server.applyNotificationGroupSwitches`: only a MOVED group switch overrides the per-detector switches — an untouched „egyedi" group is saved back unchanged |
|
||||||
| `Settings.AddPendingEvent/DrainPendingEvents` | controller/internal/settings/settings.go | offline event queue | Events while hub unreachable | — |
|
| `Settings.AddPendingEvent/DrainPendingEvents` | controller/internal/settings/settings.go | offline event queue | Events while hub unreachable | — |
|
||||||
| `Manager.SetUnitNotify` + `UnitSpace` (R-158/R-167, v0.191.0) | controller/internal/backup/recovery_unit.go | `(func(stack string, err error, *UnitSpace))` | THE per-app Tier-1 recovery-unit capture failure alert — fires PER APP from `captureAllRecoveryUnits`, loop continues | **OPERATOR-TIER** (`recovery_unit_capture_failed`, in the hub's `operatorOnlyEvents`). **NEVER route it to `backup_failed`** — that type is in `DefaultEnabledEvents` and carries Hungarian copy, so it emails the CUSTOMER about a failure they cannot act on (D-c; R-158's own proposal said `backup_failed` and D-c overrides it). `UnitSpace` is **nil when the target filesystem is unreadable** and renders as *"unavailable"*, never as zeros — "0 GB free" and "we could not look" are opposite diagnoses. No controller-side cooldown: the hub owns it |
|
| `Manager.SetUnitNotify` + `UnitSpace` (R-158/R-167, v0.191.0) | controller/internal/backup/recovery_unit.go | `(func(stack string, err error, *UnitSpace))` | THE per-app Tier-1 recovery-unit capture failure alert — fires PER APP from `captureAllRecoveryUnits`, loop continues | **OPERATOR-TIER** (`recovery_unit_capture_failed`, in the hub's `operatorOnlyEvents`). **NEVER route it to `backup_failed`** — that type is in `DefaultEnabledEvents` and carries Hungarian copy, so it emails the CUSTOMER about a failure they cannot act on (D-c; R-158's own proposal said `backup_failed` and D-c overrides it). `UnitSpace` is **nil when the target filesystem is unreadable** and renders as *"unavailable"*, never as zeros — "0 GB free" and "we could not look" are opposite diagnoses. No controller-side cooldown: the hub owns it |
|
||||||
| `Manager.beginRunSummary` / `noteFailure` / `noteAttempted` / `emitRunSummary` / `SetRunSummaryNotify` (R-182, v0.194.0) | controller/internal/backup/runsummary.go | `(kind, runID) func()` / `(app, leg, reason)` / `(RunSummary)` | **THE per-run operator digest.** One `backup_run_failures` event at the end of a run listing every failed app, its leg and its reason — emitted ONLY when something failed | **The RECORD and the NOTIFICATION are different things and must stay so.** The per-app `recovery_unit_capture_failed` event is the record (hub routes it *record-only*, stored + logged every time); this digest is the notification. Before R-182 one event was both, and did neither: nine arrived, two were mailed, seven vanished before `LogNotification`. **Lifetime is `admissionSet`'s exactly** — absent collector means "no run in flight", never a stale answer. **A refusal is noted ONCE, inside `admitApp` where the verdict is taken**, not at the three legs that consult it: R-181's one-verdict-covers-all-three contract makes per-leg noting produce "2 of 1 apps failed". **Deliberate skips (disconnected / decommissioned) must NEVER be noted** — they have their own alert and a nightly digest about an unplugged drive is an ignored digest. **A clean run emits NOTHING**; silence is safe only because the hub's deadline check (`monitor/deadline.go:396,417`) raises a missed backup from report freshness independently — if that is ever weakened this design loses its footing. **`run_id` is unique per real run** (so the hub's 1-h cooldown cannot collapse a manual run into the nightly one) and **deliberately EMPTY on the periodic refresh sweep**, which must stay under that cooldown or a polled status page becomes a mail flood |
|
| `Manager.beginRunSummary` / `noteFailure` / `noteAttempted` / `emitRunSummary` / `SetRunSummaryNotify` (R-182, v0.194.0) | controller/internal/backup/runsummary.go | `(kind, runID) func()` / `(app, leg, reason)` / `(RunSummary)` | **THE per-run operator digest.** One `backup_run_failures` event at the end of a run listing every failed app, its leg and its reason — emitted ONLY when something failed | **The RECORD and the NOTIFICATION are different things and must stay so.** The per-app `recovery_unit_capture_failed` event is the record (hub routes it *record-only*, stored + logged every time); this digest is the notification. Before R-182 one event was both, and did neither: nine arrived, two were mailed, seven vanished before `LogNotification`. **Lifetime is `admissionSet`'s exactly** — absent collector means "no run in flight", never a stale answer. **A refusal is noted ONCE, inside `admitApp` where the verdict is taken**, not at the three legs that consult it: R-181's one-verdict-covers-all-three contract makes per-leg noting produce "2 of 1 apps failed". **Deliberate skips (disconnected / decommissioned) must NEVER be noted** — they have their own alert and a nightly digest about an unplugged drive is an ignored digest. **A clean run emits NOTHING**; silence is safe only because the hub's deadline check (`monitor/deadline.go:396,417`) raises a missed backup from report freshness independently — if that is ever weakened this design loses its footing. **`run_id` is unique per real run** (so the hub's 1-h cooldown cannot collapse a manual run into the nightly one) and **deliberately EMPTY on the periodic refresh sweep**, which must stay under that cooldown or a polled status page becomes a mail flood |
|
||||||
| `Manager.admitApp` / `beginAdmissionRun` / `decideAdmission` / `estimatedWriteBytes` (R-181, v0.193.0) | controller/internal/backup/admission.go | `(stackName) bool` / `() func()` | **THE reserve gate. Call it before ANY per-app backup write** — one verdict per app per run, covering the DB dump, the volume dump and the unit capture (all three write under one per-app root) | **Decided LAZILY at the app's first write, never once at run start** — app A's dump can put app B under the reserve, so a run-start verdict reads a disk that no longer exists. **Never re-decided between an app's own legs**: that is exactly the split R-181 closed (bulk written, capture refused). **Reset per run** via the closer `beginAdmissionRun` returns. **Must sit ahead of `DumpAppVolumesSafe`**, which stops the stack as its first act — a refusal decided inside it has already bounced the app. Fires **exactly one** `unitNotify` per refused app per run. Nil admission set (periodic status refresh) → decides fresh, which is still once per app per sweep. Wiring pinned by an **AST walk** in `TestAdmission_IsWiredIntoEveryProductionWriteLeg`, not `strings.Contains` |
|
| `Manager.admitApp` / `beginAdmissionRun` / `decideAdmission` / `estimatedWriteBytes` (R-181, v0.193.0) | controller/internal/backup/admission.go | `(stackName) bool` / `() func()` | **THE reserve gate. Call it before ANY per-app backup write** — one verdict per app per run, covering the DB dump, the volume dump and the unit capture (all three write under one per-app root) | **Decided LAZILY at the app's first write, never once at run start** — app A's dump can put app B under the reserve, so a run-start verdict reads a disk that no longer exists. **Never re-decided between an app's own legs**: that is exactly the split R-181 closed (bulk written, capture refused). **Reset per run** via the closer `beginAdmissionRun` returns. **Must sit ahead of `DumpAppVolumesSafe`**, which stops the stack as its first act — a refusal decided inside it has already bounced the app. Fires **exactly one** `unitNotify` per refused app per run. Nil admission set (periodic status refresh) → decides fresh, which is still once per app per sweep. Wiring pinned by an **AST walk** in `TestAdmission_IsWiredIntoEveryProductionWriteLeg`, not `strings.Contains` |
|
||||||
| `Manager.floorVerdict` + `FloorUsedPercent`/`FloorFreeGiB` / `ErrCaptureFloor` / `floorReason` (R-165 B2 v0.192.0, size term R-181 v0.193.0) | controller/internal/backup/recovery_unit.go | `(*UnitSpace, estGiB float64) (*UnitSpace, floorReason)` | The pure two-question predicate behind `admitApp`: is the filesystem already below the reserve (`floorHeadroom`), and would THIS app's write take it below (`floorSize`)? | **Headroom is about the FILESYSTEM, never a per-unit cap** — a size cap is R-163 rebuilt inside one volume; the size term bounds the *delta*, not the unit. **REFUSES, never deletes:** nothing here is generational (a unit is one fixed path per app, a DB dump one fixed name), so pruning could only destroy a DIFFERENT app's only local copy — **never repurpose `pruneStalePrimaryDirs`**, which removes ORPHANED dirs from an app that moved drives and has no notion of age. Two terms (97% / 1 GiB) in `fillwatch`'s shape, deliberately BEYOND its critical band (95% / 2 GiB) so the customer is always warned first — pinned by `TestFloorSitsBelowTheCriticalWarningBand`. **`estGiB == 0` degrades to headroom-only on purpose** — refusing an app with no history makes the FIRST backup the one that can never happen. A nil reading neither refuses nor warns (§8.4). Inject `unitSpaceFn` in tests rather than manufacturing occupancy on a real disk |
|
| `Manager.floorVerdict` + `FloorUsedPercent`/`FloorFreeGiB` / `ErrCaptureFloor` / `floorReason` (R-165 B2 v0.192.0, size term R-181 v0.193.0) | controller/internal/backup/recovery_unit.go | `(*UnitSpace, estGiB float64) (*UnitSpace, floorReason)` | The pure two-question predicate behind `admitApp`: is the filesystem already below the reserve (`floorHeadroom`), and would THIS app's write take it below (`floorSize`)? | **Headroom is about the FILESYSTEM, never a per-unit cap** — a size cap is R-163 rebuilt inside one volume; the size term bounds the *delta*, not the unit. **REFUSES, never deletes:** nothing here is generational (a unit is one fixed path per app, a DB dump one fixed name), so pruning could only destroy a DIFFERENT app's only local copy — **never repurpose `pruneStalePrimaryDirs`**, which removes ORPHANED dirs from an app that moved drives and has no notion of age. Two terms (97% / 1 GiB) in `fillwatch`'s shape, deliberately BEYOND its critical band (95% / 2 GiB) so the customer is always warned first — pinned by `TestFloorSitsBelowTheCriticalWarningBand`. **`estGiB == 0` degrades to headroom-only on purpose** — refusing an app with no history makes the FIRST backup the one that can never happen. A nil reading neither refuses nor warns (§8.4). Inject `unitSpaceFn` in tests rather than manufacturing occupancy on a real disk |
|
||||||
| `fillwatch.Watcher` (`New`/`SetNotify`/`Check`) (R-167, v0.191.0) | controller/internal/fillwatch/fillwatch.go | `(statePath, logger, targetsFn, usageFn)` → `Check() error` | THE customer fill warning — warns BEFORE a filesystem fills, per FILESYSTEM (never per app: one full disk holding ten apps would fire ten times) | Emits the **pre-existing** `disk_warning`/`disk_critical` pair, which was allowlisted + copy'd + default-enabled with **no producer in any repo** until now — do NOT mint a new type beside it. **Two threshold terms, whichever trips first** (85% / 5 GiB; critical 95% / 2 GiB) because a percentage alone lies at both ends of this fleet's size range. **Edge-triggered on ESCALATION ONLY**, state persisted; de-escalation is silent and re-arms. Hysteresis dead zone between clear (75% / 7 GiB) and warn — pinned by `TestThresholdsKeepTheirHysteresisGap`. **A nil usage read is NEVER a warning** (§8.4). The hub has **no `customerMessages` entry** for either type on purpose — an entry would override the dynamic message and discard the drive label + free space |
|
| `fillwatch.Watcher` (`New`/`SetNotify`/`Check`) (R-167, v0.191.0) | controller/internal/fillwatch/fillwatch.go | `(statePath, logger, targetsFn, usageFn)` → `Check() error` | THE customer fill warning — warns BEFORE a filesystem fills, per FILESYSTEM (never per app: one full disk holding ten apps would fire ten times) | Emits the **pre-existing** `disk_warning`/`disk_critical` pair, which was allowlisted + copy'd + default-enabled with **no producer in any repo** until now — do NOT mint a new type beside it. **Two threshold terms, whichever trips first** (85% / 5 GiB; critical 95% / 2 GiB) because a percentage alone lies at both ends of this fleet's size range. **Edge-triggered on ESCALATION ONLY**, state persisted; de-escalation is silent and re-arms. Hysteresis dead zone between clear (75% / 7 GiB) and warn — pinned by `TestThresholdsKeepTheirHysteresisGap`. **A nil usage read is NEVER a warning** (§8.4). The hub has **no `customerMessages` entry** for either type on purpose — an entry would override the dynamic message and discard the drive label + free space. **Both languages (v0.309.0, R-521 F7):** the sentence is the bundle's `event.fill.*`, the household's rendering rides as `message_customer` via `Notifier.PushEventHousehold` (`SetLang`; `SetExtra` takes the language); a built-in area carries a `LabelKey`, a household's own drive label is used as written. Hungarian pinned byte-for-byte by `TestMessageHungarianWireText` (v0.309.0 dropped the formal „Kérjük," — R-516) **One target per filesystem (R-1371):** `fillTargets` (cmd/controller/main.go) de-duplicates by `system.FilesystemKey`, first target wins (app area, system area, drives); a new built-in target goes into that order on purpose. |
|
||||||
|
|
||||||
### Scheduler / time / UI
|
### Scheduler / time / UI
|
||||||
|
|
||||||
| Symbol | File | Short signature | Use for | Gotchas |
|
| Symbol | File | Short signature | Use for | Gotchas |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
|
| `Scheduler.RunNow` / `scheduler.OnDemand` | controller/internal/scheduler/scheduler.go | `RunNow(name) error`; `OnDemand(ctx) bool` | Run a registered job once now (operator action `run_job`, decision 185) | Refuses unknown and already-running jobs; a job that checks due-ness reads `OnDemand(ctx)` to skip that check on demand |
|
||||||
|
| `report.OperatorActions` | controller/internal/report/opactions.go | `Reconcile(reply)` → results in the next report | Hub-requested actions in the report reply — the `selftail.go` pattern plus results | The action table is CLOSED and pinned by `TestOpActions_ClosedList`; once per id in memory; every entry must be safe to repeat |
|
||||||
|
| `web.sessionFingerprint` / `loadSessions` / `saveSessionsLocked` / `saveSessionsRevokingLocked` | controller/internal/web/session_store.go | dashboard sessions on disk (R-35) | Any session lookup | The map is keyed by sha256(cookie), NEVER the cookie — hash with `sessionFingerprint` first; a path that ENDS sessions uses the revoking save |
|
||||||
|
| `web.endEverySession` / `rotateGateKey` (R-976, v0.324.0) | controller/internal/web/auth.go · controller/internal/web/setup_gate.go | `(why string)` / `()` | A dashboard password change or claim/reset — ANY act that must end every way in | Ends the dashboard sessions, every family session (`family.Store.EndAll`) AND every setup-gate pass / family app cookie (the gate key is replaced; a failed save REMOVES the old key file so a restart cannot bring old passes back). Call this, never `invalidateAllSessions` alone — that ends only the dashboard's. Pinned by `TestR976_PasswordChangeEndsFamilyAndGateSessions` / `TestR976_ClaimResetEndsFamilyAndGateSessions` |
|
||||||
|
| `web.reserveLoginAttempt` / `reserveAttempt` / `shareReserve` / `familyReserve` / `allowResetRequest` (R-983, v0.324.0; R-1111) | controller/internal/web/auth.go · share.go · family_gate.go · claim.go | `(key) → may go ahead` | Any limiter in front of a slow check (bcrypt, a hub call) | **Check and count in ONE locked step, BEFORE the slow work** — a count taken after the compare lets N parallel tries all pass the check (the shape R-983 removed from the dashboard and family sign-ins, and R-1111 from the share password and the escrow re-auth). A success clears the count afterwards. `reserveAttempt(mu, &map, key)` is the one body of the 5-per-minute password limiters — a new one passes its OWN map to it, never a third shape; the escrow re-auth counts on the login map (`reserveLoginAttempt`), the share password on its own (`shareReserve`). The compare goes through `comparePassword`, so `passwordCompare` (the slow-compare seam) reaches all three |
|
||||||
| `Scheduler.Every` / `Daily` | controller/internal/scheduler/scheduler.go | `(name, interval/"HH:MM", fn)` | ALL background jobs | Daily is Europe/Budapest, DST-safe (`nextDailyRun` avoids Add(24h)); register in main.go block (§5) |
|
| `Scheduler.Every` / `Daily` | controller/internal/scheduler/scheduler.go | `(name, interval/"HH:MM", fn)` | ALL background jobs | Daily is Europe/Budapest, DST-safe (`nextDailyRun` avoids Add(24h)); register in main.go block (§5) |
|
||||||
| `Scheduler.UpdateDaily` | controller/internal/scheduler/scheduler.go | `(name, "HH:MM") bool` | Retime a daily job at runtime (no restart) | Per-job buffered `resched` chan + select case in `runDailyJob`; false (WARN) on invalid time / unknown-or-non-daily name; read `Schedule` under the mutex in the loop |
|
| `Scheduler.UpdateDaily` | controller/internal/scheduler/scheduler.go | `(name, "HH:MM") bool` | Retime a daily job at runtime (no restart) | Per-job buffered `resched` chan + select case in `runDailyJob`; false (WARN) on invalid time / unknown-or-non-daily name; read `Schedule` under the mutex in the loop |
|
||||||
| `backupwindow.*` (LegTimes / GateWindow / EffectiveWindow / ParseHHMM / FmtHHMM / Valid) | controller/internal/backupwindow/backupwindow.go | pure `string`↔`int` | Backup-window arithmetic (v0.168.0) | Offsets (W+60m/W+105m, gate W+2h..W+6h) are CONSTANTS — derived, never stored; wrap-safe modulo 1440; `EffectiveWindow(settings, yaml)` = settings>yaml>"02:30" |
|
| `backupwindow.*` (LegTimes / GateWindow / EffectiveWindow / ParseHHMM / FmtHHMM / Valid) | controller/internal/backupwindow/backupwindow.go | pure `string`↔`int` | Backup-window arithmetic (v0.168.0) | Offsets (W+60m/W+105m, gate W+2h..W+6h) are CONSTANTS — derived, never stored; wrap-safe modulo 1440; `EffectiveWindow(settings, yaml)` = settings>yaml>"02:30" |
|
||||||
@@ -272,9 +311,11 @@
|
|||||||
| `i18n.Bundle` (`Shared` / `Msg` / `Plural` / `Expand`) | controller/internal/i18n/i18n.go | `Msg(lang, key) string` | ALL customer copy that has been converted (v0.247.0) | hu.json is authoritative; a key missing in en shows Hungarian (counted), never blank; `Expand` runs BEFORE template parse — never add a runtime `T` func (escaping would change Hungarian bytes). A template edit to converted copy goes in hu.json + en.json, then `TestI18nParity` must still pass |
|
| `i18n.Bundle` (`Shared` / `Msg` / `Plural` / `Expand`) | controller/internal/i18n/i18n.go | `Msg(lang, key) string` | ALL customer copy that has been converted (v0.247.0) | hu.json is authoritative; a key missing in en shows Hungarian (counted), never blank; `Expand` runs BEFORE template parse — never add a runtime `T` func (escaping would change Hungarian bytes). A template edit to converted copy goes in hu.json + en.json, then `TestI18nParity` must still pass |
|
||||||
| `huTemplateSource` (test) | controller/internal/web/i18n_wiring_test.go | `(name) ([]byte, error)` | A test that asserts a template's Hungarian WORDING | Reads the expansion, not the raw file — since slice 1 the wording lives in hu.json. Never use `templateFS.ReadFile` for a wording assertion |
|
| `huTemplateSource` (test) | controller/internal/web/i18n_wiring_test.go | `(name) ([]byte, error)` | A test that asserts a template's Hungarian WORDING | Reads the expansion, not the raw file — since slice 1 the wording lives in hu.json. Never use `templateFS.ReadFile` for a wording assertion |
|
||||||
| `Server.langFor` / `templatesFor` / `addLanguageData` | controller/internal/web/server.go + i18n_web.go | request → lang → template set | Rendering a page in the household's language | Only `executeTemplate` is language-aware; `s.tmpl` is the Hungarian set; Go-side titles via `data["TitleKey"]` |
|
| `Server.langFor` / `templatesFor` / `addLanguageData` | controller/internal/web/server.go + i18n_web.go | request → lang → template set | Rendering a page in the household's language | Only `executeTemplate` is language-aware; `s.tmpl` is the Hungarian set; Go-side titles via `data["TitleKey"]` |
|
||||||
|
| `bootstrap.Unconfigured` / `WaitForConfig` / `WaitingHandler` (v0.308.0, R-554) | controller/internal/bootstrap/waiting.go | `WaitForConfig(ctx, ln, configPath, cfg, logger, pull, every, version) *config.Config` | The ONLY unconfigured-box path: the bilingual waiting page + a retry of `MaybeIngest` every minute; returns the configured config (nil on stop) | Replaces the deleted setup wizard. `/api/health` stays 200 while waiting; a nil listener still retries |
|
||||||
|
| `i18n.FormatDateTime` / `FormatDate` / `FormatMonthDayTime` / `FormatDecimal` / `LocalizeDecimals` | controller/internal/i18n/format.go | `(lang, …) string` | EVERY date or decimal number shown on the dashboard (R-562, v0.308.0): hu „2026. 10. 10. 15:04" + decimal comma, en „2026-10-10 15:04" + point | Pass the time already in Budapest; `LocalizeDecimals` is only for a size another package already formatted („1.5 GB") — new code calls `FormatDecimal`. Templates use the bound names in `formatFuncs(lang)` (funcmap.go: `fmtTime`, `fmtTimeStr`, `fmtGB`, `fmtBytes`, `numText`, …); Go page data uses `fmtLocalTime(lang, t)` / `fmtRFC3339Local(lang, s)` / `fmtSizeBytes(lang, n)`; page scripts use `fhNum` / `fhDateTime` / `fhIsoDate` / `fhMonthDay` (layout.html). Never a `"2006-01-02 15:04"` literal for display. CSS widths keep `printf "%.1f"` |
|
||||||
| `timeAgoStr` | controller/internal/web/funcmap.go | `(s RFC3339 string) string` | Ago-format for STRING timestamps | Exists because `timeAgo(time.Time)` 500'd on strings (v0.93 bug) |
|
| `timeAgoStr` | controller/internal/web/funcmap.go | `(s RFC3339 string) string` | Ago-format for STRING timestamps | Exists because `timeAgo(time.Time)` 500'd on strings (v0.93 bug) |
|
||||||
| `Server.baseData` / `executeTemplate` | controller/internal/web/handlers.go + server.go | page-data plumbing | New pages | baseData injects nav/alerts/version; templates must pass `controller/scripts/template_id_gate.py` + `controller/scripts/emoji_gate.py` |
|
| `Server.baseData` / `executeTemplate` | controller/internal/web/handlers.go + server.go | page-data plumbing | New pages | baseData injects nav/alerts/version; templates must pass `controller/scripts/template_id_gate.py` + `controller/scripts/emoji_gate.py` |
|
||||||
| `Server.RequireAuth` / `CsrfProtect` / `csrfField` | controller/internal/web/auth.go + csrf.go | middleware | Any new authed route/form | csrfField emits the hidden input; setup wizard has its OWN csrf (§6) |
|
| `Server.RequireAuth` / `CsrfProtect` / `csrfField` | controller/internal/web/auth.go + csrf.go | middleware | Any new authed route/form | csrfField emits the hidden input |
|
||||||
| `LogBuffer` + `Lines(maxBytes)` | controller/internal/web/logbuffer.go | ring buffer io.Writer | In-memory log capture for the debug UI + the report `controller_log_tail` source | v0.116.0: ALWAYS constructed (any logging.level) — the logger is `MultiWriter(LevelFilterWriter(stdout, level), ring)`; `Lines` drops OLDEST to honor the byte budget |
|
| `LogBuffer` + `Lines(maxBytes)` | controller/internal/web/logbuffer.go | ring buffer io.Writer | In-memory log capture for the debug UI + the report `controller_log_tail` source | v0.116.0: ALWAYS constructed (any logging.level) — the logger is `MultiWriter(LevelFilterWriter(stdout, level), ring)`; `Lines` drops OLDEST to honor the byte budget |
|
||||||
| `logx.Debugf/Infof/Warnf/Errorf` | controller/internal/logx/logx.go | `(l *log.Logger, format, args…)` | ALL NEW leveled log lines (the v0.116.0 sweep standard) | routing is the WRITER's job — Debugf always reaches the ring, stdout filters; nil logger = no-op; caller-attributed (Output calldepth 3) |
|
| `logx.Debugf/Infof/Warnf/Errorf` | controller/internal/logx/logx.go | `(l *log.Logger, format, args…)` | ALL NEW leveled log lines (the v0.116.0 sweep standard) | routing is the WRITER's job — Debugf always reaches the ring, stdout filters; nil logger = no-op; caller-attributed (Output calldepth 3) |
|
||||||
| `web.LevelFilterWriter` | controller/internal/web/levelfilter.go | `NewLevelFilterWriter(w, minLevel)` | stdout leveling under the always-on ring | untagged lines parse INFO; always reports full length written |
|
| `web.LevelFilterWriter` | controller/internal/web/levelfilter.go | `NewLevelFilterWriter(w, minLevel)` | stdout leveling under the always-on ring | untagged lines parse INFO; always reports full length written |
|
||||||
@@ -298,6 +339,7 @@
|
|||||||
| Streaming subprocess progress | controller/internal/backup/offbox_progress.go | `offboxStreamRunner` seam (stdout scanned line-by-line, stderr buffered, output tail-bounded) + a PURE line parser + a mutex-guarded published snapshot. Traps it encodes: a source reporting nothing is **normal** (restic sends 0 bytes for a whole incremental run) and the progress source may only update on unit completion — degrade bytes → files → current item + elapsed, never fake a percentage |
|
| Streaming subprocess progress | controller/internal/backup/offbox_progress.go | `offboxStreamRunner` seam (stdout scanned line-by-line, stderr buffered, output tail-bounded) + a PURE line parser + a mutex-guarded published snapshot. Traps it encodes: a source reporting nothing is **normal** (restic sends 0 bytes for a whole incremental run) and the progress source may only update on unit completion — degrade bytes → files → current item + elapsed, never fake a percentage |
|
||||||
| Post-start async verification | controller/internal/stacks/manager.go `logPostStartStatus` | goroutine + sleep, INFO log, never blocks/fails the operation |
|
| Post-start async verification | controller/internal/stacks/manager.go `logPostStartStatus` | goroutine + sleep, INFO log, never blocks/fails the operation |
|
||||||
| Startup wiring order | controller/cmd/controller/main.go | init-only setters (`SetStackProvider` M2 contract: exactly once, before scheduler/HTTP), scheduler registration block |
|
| Startup wiring order | controller/cmd/controller/main.go | init-only setters (`SetStackProvider` M2 contract: exactly once, before scheduler/HTTP), scheduler registration block |
|
||||||
|
| Tabbed page (one subject, several URLs) | controller/internal/web/app_page.go + templates/app_shell.html | ONE data builder for what every tab shows (`appCommonData`), one shell partial (header + page-level banners + tab bar), one page template per tab calling `{{template "app_shell_start" .}}`. Tabs are `<a>` links with `aria-current`, never hidden panels — a link in an alert must land ON a tab and a poller must run on its tab only. The default tab is RENDERED at the bare URL, never redirected to. A key the tab owns (`Page`, `Title`, `TitleKey`, `TitleArgs`, `ActiveTab`, `AppTabs`) is listed in `appPageDataKeysOwnedByTab` so a merged data builder cannot overwrite it |
|
||||||
|
|
||||||
## 3. Dangerous lookalikes — do NOT reuse
|
## 3. Dangerous lookalikes — do NOT reuse
|
||||||
|
|
||||||
@@ -309,8 +351,9 @@
|
|||||||
| `timeAgo` on an RFC3339 string field | Template 500 (OffboxTarget.LastRun bug, fixed v0.96.0) | `timeAgoStr` |
|
| `timeAgo` on an RFC3339 string field | Template 500 (OffboxTarget.LastRun bug, fixed v0.96.0) | `timeAgoStr` |
|
||||||
| `backup.Manager.DumpAppVolumes` on a running DB app | Inconsistent tar of live DB volume | `DumpAppVolumesSafe` (stop → dump → restart, both errors surfaced) |
|
| `backup.Manager.DumpAppVolumes` on a running DB app | Inconsistent tar of live DB volume | `DumpAppVolumesSafe` (stop → dump → restart, both errors surfaced) |
|
||||||
| `stacks.Manager.execCommand` / `composeExecCustomEnv` for NEW long-running calls | No context/timeout — a hung docker CLI blocks forever | `exec.CommandContext` + explicit timeout (copy `rsyncCopy` or appexport `composeExecEnv`) |
|
| `stacks.Manager.execCommand` / `composeExecCustomEnv` for NEW long-running calls | No context/timeout — a hung docker CLI blocks forever | `exec.CommandContext` + explicit timeout (copy `rsyncCopy` or appexport `composeExecEnv`) |
|
||||||
| `config.LoadPermissive` | Skips validation — setup-mode only (customer.id/domain may be unset) | `config.Load` everywhere else |
|
| `config.LoadPermissive` | Skips validation — first boot only (customer.id/domain may be unset until `bootstrap.WaitForConfig` gets the configuration, R-554) | `config.Load` everywhere else |
|
||||||
| `ExportDataMounts` / `ParseComposeHDDMounts` as **backup-classification** input | `ExportDataMounts` unions the `${USERDATA_PATH}` ROOT (export-capture logic, not per-bind); `ParseComposeHDDMounts` resolves absolutes AND drops the `:ro` flag — classification needs `${VAR}`-relative paths + read-only awareness | `ParseComposeClassifiableBinds` (controller/internal/stacks/classify_binds.go) |
|
| `ExportDataMounts` / `ParseComposeHDDMounts` as **backup-classification** input | `ExportDataMounts` unions the `${USERDATA_PATH}` ROOT (export-capture logic, not per-bind); `ParseComposeHDDMounts` resolves absolutes AND drops the `:ro` flag — classification needs `${VAR}`-relative paths + read-only awareness | `ParseComposeClassifiableBinds` (controller/internal/stacks/classify_binds.go) |
|
||||||
|
| any settings getter/setter or helper that ends in one (`m.note`, `boxLang`) INSIDE a `settings.UpdateOffboxStatus`/`UpdateCrossDriveStatus` callback (R-578) | The callback runs under the settings WRITE lock and `sync.RWMutex` is not reentrant — it DEADLOCKS holding the lock and wedges settings.json for the box | Resolve the value BEFORE the callback (`lang := m.boxLang()`); `TestR578NothingTakesTheSettingsLockInsideASettingsCallback` (controller/internal/settings/r578_callback_lock_gate_test.go) convicts it in every package |
|
||||||
| `docker compose restart` (any wrapper) | Does not pick up new images or env | `RedeployFromEnv` / composeExec `up -d` |
|
| `docker compose restart` (any wrapper) | Does not pick up new images or env | `RedeployFromEnv` / composeExec `up -d` |
|
||||||
| `backup.WholeOnTier` vs `UpdateCopyHolds` (R-659) | `UpdateCopyHolds` says what a copy HOLDS; it does not say the restore will ACCEPT it — a file app's second-drive copy holds the files and its unit restore still refuses | `WholeOnTier` (asks `DeclaredDriveFileLegs`, the refusal's own predicate) before a sentence names a copy as a way back |
|
| `backup.WholeOnTier` vs `UpdateCopyHolds` (R-659) | `UpdateCopyHolds` says what a copy HOLDS; it does not say the restore will ACCEPT it — a file app's second-drive copy holds the files and its unit restore still refuses | `WholeOnTier` (asks `DeclaredDriveFileLegs`, the refusal's own predicate) before a sentence names a copy as a way back |
|
||||||
|
|
||||||
@@ -320,6 +363,8 @@
|
|||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `diskAgent` | controller/internal/web/storage_handlers.go | `*agentapi.Client` | `mockAgent` in controller/internal/web/storage_handlers_test.go |
|
| `diskAgent` | controller/internal/web/storage_handlers.go | `*agentapi.Client` | `mockAgent` in controller/internal/web/storage_handlers_test.go |
|
||||||
| `netAgent` + `Server.netAgentFn/netProbeFn/netListFn` | controller/internal/web/netstorage_job.go (+ server.go fields) | `*agentapi.Client` / `runNetProbe` (linux re-exec) / `agent.ListNetStorage` | `fakeNetAgent` + fn injections in controller/internal/web/netstorage_job_test.go — the NAS add orchestration never shells/TLS-dials in tests |
|
| `netAgent` + `Server.netAgentFn/netProbeFn/netListFn` | controller/internal/web/netstorage_job.go (+ server.go fields) | `*agentapi.Client` / `runNetProbe` (linux re-exec) / `agent.ListNetStorage` | `fakeNetAgent` + fn injections in controller/internal/web/netstorage_job_test.go — the NAS add orchestration never shells/TLS-dials in tests |
|
||||||
|
| `faultPoint(point) error` (D63, TEST BUILDS ONLY) | controller/cmd/controller/faultpoint_{off,on}.go | a no-op without `-tags faultinject` (the release image); with it, a file `<data>/faults/<point>` = „<skip> <fail>" fails the named point | `TestD63_TheReleaseBuildHasNoFaultSwitch` (release build: no-op; build.sh/Dockerfile pass no tag), `TestD63_TheTestBuildFailsTheArmedPointOnDemand` (`go test -tags faultinject`). Points: `defwrite-after-compose`, `stop-<app>`. A live proof of a branch Docker cannot be made to take on demand goes here — never an env switch in the release binary |
|
||||||
|
| `healthSettle` / `healthInterval` / `healthTimeout` (package vars, R-488) | controller/internal/backup/restore.go | production 3 s / 5 s / 90 s — `waitForHealthy`'s clock, used by every restore path | shortened ONCE in controller/internal/backup/main_test.go `TestMain` (0 / 2 ms / 50 ms; the package went 444 s → ~2 s); `TestR488_HealthWaitDefaultsAreProduction` pins the production values. A new real-clock wait in this package goes behind the same kind of var, not a per-test sleep. Also: `newOffboxManager` installs a failing `SetOffboxSSH` fake, so no backup test spawns a real `ssh` |
|
||||||
| `Server.agentLogsFn` (func seam) | controller/internal/web/server.go | nil → `agentClient().DebugLogs` (agent GET /debug/logs) | injected in controller/internal/web/observability_test.go (incl. the pre-0.83 typed-404 notice path) |
|
| `Server.agentLogsFn` (func seam) | controller/internal/web/server.go | nil → `agentClient().DebugLogs` (agent GET /debug/logs) | injected in controller/internal/web/observability_test.go (incl. the pre-0.83 typed-404 notice path) |
|
||||||
| `escrowAgent` + `Server.escrowAgentFn/escrowStageFn/escrowStaleFn` | controller/internal/web/escrow_handlers.go (+ server.go fields) | `*agentapi.Client` / `PushOffboxPasswordForEscrow` / `report.EscrowAutoConfirmer.StaleBlob` (SetEscrowStale) | `fakeEscrowAgent` + fn injections in escrow_wizard_test.go — call-ORDER assertions (stage BEFORE trigger) + agent-never-called gates. The claim leg is the ONLY surface R crosses: no-store, never logged, never templated |
|
| `escrowAgent` + `Server.escrowAgentFn/escrowStageFn/escrowStaleFn` | controller/internal/web/escrow_handlers.go (+ server.go fields) | `*agentapi.Client` / `PushOffboxPasswordForEscrow` / `report.EscrowAutoConfirmer.StaleBlob` (SetEscrowStale) | `fakeEscrowAgent` + fn injections in escrow_wizard_test.go — call-ORDER assertions (stage BEFORE trigger) + agent-never-called gates. The claim leg is the ONLY surface R crosses: no-store, never logged, never templated |
|
||||||
| `offboxCeremonyWaitState` + `escrowCeremonyGraceWindow` | controller/internal/web/handlers.go | pure pick: (awaiting, timedOut) from `OffboxTarget.{EscrowState,CeremonyCompletedAt}` — the v0.138.0 "megerősítésre vár" card. Stamp SET on claim (escrow_handlers.go), CLEARED on the flip (main.go Flip + offbox_handlers.go manual confirm) | escrow_wait_state_test.go truth table (escrowed/unstamped/unparseable → plain CTA; boundary via `>=`) |
|
| `offboxCeremonyWaitState` + `escrowCeremonyGraceWindow` | controller/internal/web/handlers.go | pure pick: (awaiting, timedOut) from `OffboxTarget.{EscrowState,CeremonyCompletedAt}` — the v0.138.0 "megerősítésre vár" card. Stamp SET on claim (escrow_handlers.go), CLEARED on the flip (main.go Flip + offbox_handlers.go manual confirm) | escrow_wait_state_test.go truth table (escrowed/unstamped/unparseable → plain CTA; boundary via `>=`) |
|
||||||
@@ -348,9 +393,16 @@
|
|||||||
| `Manager.execFn` (func seam) + `restartPolicyLookup` / `inspectRestartPolicyFn` (R-51, v0.156.0) | controller/internal/stacks/manager.go | nil → real `exec.Command` / `docker inspect -f {{.HostConfig.RestartPolicy.Name}}` | `scriptedDocker` in controller/internal/stacks/degraded_test.go drives the WHOLE production path (docker ps → aggregateState → docker inspect) — an aggregateState-only test proves the function, not the caller. Policy answers are cached per container+state and pruned to the live `docker ps` set; a FAILED inspect is deliberately never cached (a hiccup must not pin a container to "unknown") and reads as SUPERVISED, i.e. fail-closed — the opposite of `IsDownState`'s fail-open, because there the state is ambiguous while here a member is known dead |
|
| `Manager.execFn` (func seam) + `restartPolicyLookup` / `inspectRestartPolicyFn` (R-51, v0.156.0) | controller/internal/stacks/manager.go | nil → real `exec.Command` / `docker inspect -f {{.HostConfig.RestartPolicy.Name}}` | `scriptedDocker` in controller/internal/stacks/degraded_test.go drives the WHOLE production path (docker ps → aggregateState → docker inspect) — an aggregateState-only test proves the function, not the caller. Policy answers are cached per container+state and pruned to the live `docker ps` set; a FAILED inspect is deliberately never cached (a hiccup must not pin a container to "unknown") and reads as SUPERVISED, i.e. fail-closed — the opposite of `IsDownState`'s fail-open, because there the state is ambiguous while here a member is known dead |
|
||||||
| `bootrecon.StackProvider` (R-52, v0.156.0) | controller/internal/bootrecon/bootrecon.go | `*stacks.Manager` (GetStacks/StartStack/RefreshStatus) | `fakeStacks` counts StartStack per app; the load-bearing assertion is the NEGATIVE — a zero-container stack (a UI Stop = `compose down` = containers removed) must record **0** starts, while a boot orphan (containers present, Exited) records exactly 1. `Reconciler.sleep` is injected so the 30 s gap costs nothing |
|
| `bootrecon.StackProvider` (R-52, v0.156.0) | controller/internal/bootrecon/bootrecon.go | `*stacks.Manager` (GetStacks/StartStack/RefreshStatus) | `fakeStacks` counts StartStack per app; the load-bearing assertion is the NEGATIVE — a zero-container stack (a UI Stop = `compose down` = containers removed) must record **0** starts, while a boot orphan (containers present, Exited) records exactly 1. `Reconciler.sleep` is injected so the 30 s gap costs nothing |
|
||||||
| `bootReconcileFn` + `runBootReconcile` (package-main seam, v0.156.0) | controller/cmd/controller/main.go | `bootrecon.New(mgr, logger).Run` | controller/cmd/controller/bootrecon_wiring_test.go. **The wiring itself is asserted by an AST walk** over `func main()`, not a `strings.Contains` — the substring version passed its own red-proof because a commented-out call still contains the string. Comments are not callers |
|
| `bootReconcileFn` + `runBootReconcile` (package-main seam, v0.156.0) | controller/cmd/controller/main.go | `bootrecon.New(mgr, logger).Run` | controller/cmd/controller/bootrecon_wiring_test.go. **The wiring itself is asserted by an AST walk** over `func main()`, not a `strings.Contains` — the substring version passed its own red-proof because a commented-out call still contains the string. Comments are not callers |
|
||||||
|
| `crashboot.Probe` / `crashboot.Grace` (R-856) | controller/internal/crashboot/crashboot.go | `crashboot.AgentProbe(agentClient.CrashGuard)` (GET /host/crash-guard) | `fixed(Fact, err)` in crashboot_test.go. The dead-app check gates on `bootGrace.Within(now)` — 90 s normally, `CrashGrace` (15 min) when the HOST's last boot was unclean and within `BootWindow` of the controller start. **Unknown (no agent, 404, no state) is a normal boot** — never a longer silence on a guess. Asserted by AST walk in cmd/controller/r856_wiring_test.go |
|
||||||
| `classifyRunStates` (pure fix-3 derivation, v0.164.0) | controller/cmd/controller/main.go | `([]stacks.Stack, quiesced, failedRestart map[string]bool, now time.Time)` → `(dead []web.DeadApp, states []notify.AppRunState)` | classify_runstates_test.go. **THE single fix-3 rule: down = `(IsDownState(st.State) || st.CrashLooping(now)) && !userStopped && !quiesced`.** **`quiesced` is a UNION of TWO suppression sets** (R-330, v0.224.0): `quiesce.Loop.SuppressedStacks()` (whole-guest vzdump/PBS) and `backup.AppStopGuard.SuppressedStacks()` (per-app volume dump / offbox reconstitute / `.fab` export), merged by `unionSuppressed` in `scanDeployedAppRunStates`. **Adding a third way to stop an app means adding its set here** — R-330 was 61 false customer e-mails caused by exactly that omission, with a working suppressor sitting three lines away. C9-F2 (v0.183.0) added the crash-loop term: `restarting` is NOT in `IsDownState` and must not be — adding it alarms on every deploy and update fleet-wide — so a SUSTAINED restarting run (`stacks.crashLoopAfter` = 5 m, above the 120 s deploy timeout, Mealie's 60 s start_period AND R-97b's 180 s grace) becomes down instead. `now` is injected so the threshold is a testable contract. A deliberate UI stop (`compose down` → zero containers → StateStopped, I1) must not alarm — banner OR email — while faults (Exited/Degraded) alarm byte-identically; I2 (P2 census: all catalog services `unless-stopped`) is why a crash never rests at stopped. **Do NOT touch `IsDownState`** (other callers rely on stopped=down) and do NOT filter in `buildDeadAppAlerts`/`NotifyAppStartFailures` — one derivation point. If I1 or I2 changes, revisit the suppression |
|
| `classifyRunStates` (pure fix-3 derivation, v0.164.0) | controller/cmd/controller/main.go | `([]stacks.Stack, quiesced, failedRestart map[string]bool, now time.Time)` → `(dead []web.DeadApp, states []notify.AppRunState)` | classify_runstates_test.go. **THE single fix-3 rule: down = `(IsDownState(st.State) || st.CrashLooping(now)) && !userStopped && !quiesced`.** **`quiesced` is a UNION of TWO suppression sets** (R-330, v0.224.0): `quiesce.Loop.SuppressedStacks()` (whole-guest vzdump/PBS) and `backup.AppStopGuard.SuppressedStacks()` (per-app volume dump / offbox reconstitute / `.fab` export), merged by `unionSuppressed` in `scanDeployedAppRunStates`. **Adding a third way to stop an app means adding its set here** — R-330 was 61 false customer e-mails caused by exactly that omission, with a working suppressor sitting three lines away. C9-F2 (v0.183.0) added the crash-loop term: `restarting` is NOT in `IsDownState` and must not be — adding it alarms on every deploy and update fleet-wide — so a SUSTAINED restarting run (`stacks.crashLoopAfter` = 5 m, above the 120 s deploy timeout, Mealie's 60 s start_period AND R-97b's 180 s grace) becomes down instead. `now` is injected so the threshold is a testable contract. A deliberate UI stop (`compose down` → zero containers → StateStopped, I1) must not alarm — banner OR email — while faults (Exited/Degraded) alarm byte-identically; I2 (P2 census: all catalog services `unless-stopped`) is why a crash never rests at stopped. **Do NOT touch `IsDownState`** (other callers rely on stopped=down) and do NOT filter in `buildDeadAppAlerts`/`NotifyAppStartFailures` — one derivation point. If I1 or I2 changes, revisit the suppression |
|
||||||
| `report.SetPendingControllerLog` / `SetControllerLogSource` | controller/internal/report/selftail.go | ACK-armed consume-once self-log pull (the logtail.go shape) | selftail_test.go; source = `logBuffer.Lines`, wired once in main.go |
|
| `report.SetPendingControllerLog` / `SetControllerLogSource` | controller/internal/report/selftail.go | ACK-armed consume-once self-log pull (the logtail.go shape) | selftail_test.go; source = `logBuffer.Lines`, wired once in main.go |
|
||||||
| `util.ParseVersion` / `util.Version.Compare` | controller/internal/util/version.go | THE one semver comparator (house rule: never a second) — selfupdate aliases it; agentapi's MinAgent comparison uses it | rejects pre-release/dev/latest (callers fall back, never trust); numeric compare (0.100 > 0.81) |
|
| `util.ParseVersion` / `util.Version.Compare` | controller/internal/util/version.go | THE one semver comparator (house rule: never a second) — selfupdate aliases it; agentapi's MinAgent comparison uses it | rejects pre-release/dev/latest (callers fall back, never trust); numeric compare (0.100 > 0.81) |
|
||||||
|
| `util.ParseVersionPre` | controller/internal/util/version.go | the same comparator, reading `X.Y.Z-rc.N` as BELOW `X.Y.Z` (v0.314.0, R-1053) — ONLY for „is this box below the floor?" | never use it to pick a tag to offer: the button must not see a test build |
|
||||||
|
| `upwatch.Source` / `upwatch.Explainer` / `Watcher.Now` (v0.342.0, the upload watch) | controller/internal/upwatch/ | `DockerAPI` (Engine API on the socket, exact counters) / the qBittorrent, Transmission and Plex clients | `fakeSource`, `fakeApp` and a minute clock in watch_test.go drive the WHOLE judge path; the app clients are tested against httptest servers that behave as measured on 9202. **Exact counters come from the Engine API, never from `docker stats` text** (three significant digits) |
|
||||||
|
| `upwatch.QBittorrent.SetUploadLimit` + `ApplyQBLimit` | controller/internal/upwatch/qblimit.go | the one writer of qBittorrent's global upload limit | compare against the value qBittorrent STORED (KiB/s rounding), never the requested one; a limit the household touched is theirs for good |
|
||||||
|
| `upwatch.Service.Measured` / `RefreshMeasured` / `MeasuredLine` + `agentapi.Client.LineTest` (R-1247) | controller/internal/upwatch/service.go · controller/internal/agentapi/linetest.go · cmd/controller/upwatch_wiring.go `agentLineTest` | GET /host/line-test (agent ≥ 0.164.0): the host's weekly iperf3 line test | **qBittorrent's limit reads `MeasuredLine` only — never `Line()`** (the push floor is a far lower bound; D41). `Line()` = the higher of the two, for the watch. Read at start + every 15 min; a failed read KEEPS the last value; 404 / present:false = not measured. Pinned by `TestService_QBLimitFromTheTestedLineOnly` |
|
||||||
|
| `mediawire.PlexURL` | controller/internal/mediawire/plexaddr.go | Plex's base URL BY ADDRESS, resolved at each call (v0.314.0, R-1060) — every controller call to Plex | Plex refuses the Host name `plex` as non-local (401); never cache the address |
|
||||||
|
| `stacks.GateCapture` / `stacks.ReadGateAtBackup` | controller/internal/stacks/restore_gate.go | the setup gate a per-app backup records, and the restore's read of it (v0.314.0, R-1057) | the unit `app.yaml` key is `setup_gate:` — the live file's keys, so either reads the same |
|
||||||
| `agentapi.AgentVersionReporter` + `featureMinAgent` | controller/internal/agentapi/features.go | version-first Supports (v0.82.0 header channel); probe = fallback for header-less agents | a coupled feature adds BOTH a featureProbes row AND a featureMinAgent row; v0.116.0: `SupportsWithSource` also reports HOW the verdict was reached (version/probe-cache/probe) for the gate log line |
|
| `agentapi.AgentVersionReporter` + `featureMinAgent` | controller/internal/agentapi/features.go | version-first Supports (v0.82.0 header channel); probe = fallback for header-less agents | a coupled feature adds BOTH a featureProbes row AND a featureMinAgent row; v0.116.0: `SupportsWithSource` also reports HOW the verdict was reached (version/probe-cache/probe) for the gate log line |
|
||||||
| `netProbeReadBack` (package var) | controller/internal/web/netprobe.go | `os.ReadFile` | overridden in TestNetProbeChild (nonce-tamper + cleanup-fail rows); package var because the child is a RE-EXEC'd process in production |
|
| `netProbeReadBack` (package var) | controller/internal/web/netprobe.go | `os.ReadFile` | overridden in TestNetProbeChild (nonce-tamper + cleanup-fail rows); package var because the child is a RE-EXEC'd process in production |
|
||||||
| `system.ClassifyPathFS(Timeout)` + `netProbeFSClass` / `Server.classifyFSPath` / `Router.classifyFSPath` | controller/internal/system/fsclass*.go (+ web/netprobe.go, web/server.go, api/router.go seams) | statfs f_type → network/autofs/stub/unknown in THIS namespace (RCA fix 2) | idle autofs = HEALTHY, never force-mount; unknown = fail OPEN; seams injected in netprobe_stub_test.go / networkstub_test.go / deploygate_test.go |
|
| `system.ClassifyPathFS(Timeout)` + `netProbeFSClass` / `Server.classifyFSPath` / `Router.classifyFSPath` | controller/internal/system/fsclass*.go (+ web/netprobe.go, web/server.go, api/router.go seams) | statfs f_type → network/autofs/stub/unknown in THIS namespace (RCA fix 2) | idle autofs = HEALTHY, never force-mount; unknown = fail OPEN; seams injected in netprobe_stub_test.go / networkstub_test.go / deploygate_test.go |
|
||||||
@@ -393,20 +445,22 @@ Cross-repo edges:
|
|||||||
- **New startup self-check**: append check fn in `selftest.Run` (controller/internal/selftest/selftest.go).
|
- **New startup self-check**: append check fn in `selftest.Run` (controller/internal/selftest/selftest.go).
|
||||||
- **Converting a template to the bundle (i18n, v0.247.0)**: `python3 controller/scripts/i18n_extract.py <template>` moves every Hungarian run into `hu.json` and leaves `{{T "key"}}`; then **review what it LEFT** (it matches Hungarian by accented letter plus an ASCII word list — eight ASCII-only strings were missed on the first three pages), add the English to `en.json`, add fixture states for the page to `i18n_parity_test.go` **captured from the unconverted template first**, and run `controller/scripts/i18n_missing_gate.py`. Copy gates judge the page through `controller/scripts/i18n_bundle.py` (`read_template(path, lang)`), never the raw template.
|
- **Converting a template to the bundle (i18n, v0.247.0)**: `python3 controller/scripts/i18n_extract.py <template>` moves every Hungarian run into `hu.json` and leaves `{{T "key"}}`; then **review what it LEFT** (it matches Hungarian by accented letter plus an ASCII word list — eight ASCII-only strings were missed on the first three pages), add the English to `en.json`, add fixture states for the page to `i18n_parity_test.go` **captured from the unconverted template first**, and run `controller/scripts/i18n_missing_gate.py`. Copy gates judge the page through `controller/scripts/i18n_bundle.py` (`read_template(path, lang)`), never the raw template.
|
||||||
- **New settings field**: struct + accessor pair in controller/internal/settings/settings.go following the Lock→mutate→save pattern.
|
- **New settings field**: struct + accessor pair in controller/internal/settings/settings.go following the Lock→mutate→save pattern.
|
||||||
|
- **A value asked AFTER the app starts (v0.315.0)**: add a `DeployField` with `after_start: true` to the catalog template AND an entry to `afterStartRegistry` in `controller/internal/web/after_start.go`, keyed `slug + "/" + ENV_VAR`, with `Needed(stack) bool` and `Apply(s, r, stack, value) error`. **The catalog may never carry the action** — not a command, not a URL, not a container to exec: the household's text is an argument to a function in this repository, which is the whole point of the design (D2 = A). Both halves are required and each is checked: a declared field with no entry renders no card and 404s its POST; an entry whose field the catalog does not declare also 404s (`TestAfterStart_RegistryAloneIsNotAnInvitation` — that second half was green and unpinned until a red-proof showed a POST for an undeclared field reaching Plex). `Apply` returns `*afterStartError{Status, MsgKey}` to show a sentence of its own inline, and **never logs the value** (it is a credential).
|
||||||
|
- **A tab on the app page (v0.315.0)**: a `case` in `appPageHandler`'s switch, a `render<Tab>Tab` that adds only its own keys to `appCommonData`'s map, a template starting with `layout_start` + `app_shell_start`, and the tab's key in `appTabOrder` with a literal `app_page.tab_<key>` locale key resolved in `appTabLinksLang`. **Resolve the label in Go, not with a composed `{{T (printf …)}}`** — a composed key is invisible to `TestI18nParityCoversEveryMarker` and a missing translation would render the key to the household.
|
||||||
|
|
||||||
## 6. Known duplication (observed — NOT fixed)
|
## 6. Known duplication (observed — NOT fixed)
|
||||||
|
|
||||||
| Duplication | Locations |
|
| Duplication | Locations |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Atomic write ×4 (+inline in settings.save) | controller/internal/backup/recovery_unit.go `atomicWrite`; controller/internal/bootstrap/bootstrap.go `writeFileAtomic`; controller/internal/setup/handlers.go `atomicWriteFile`; controller/internal/api/router.go `writeConfig0600` |
|
| Atomic write ×3 (+inline in settings.save) | controller/internal/backup/recovery_unit.go `atomicWrite`; controller/internal/bootstrap/bootstrap.go `writeFileAtomic`; controller/internal/api/router.go `writeConfig0600` (the setup wizard's `atomicWriteFile` went with it, R-554) |
|
||||||
| String truncation ×4 | controller/internal/util/strings.go `TruncateStr` (rune-safe, 1 caller); controller/internal/stacks/manager.go `truncateStr` (byte-based HEAD, widely used) and `tailStr` (rune-safe TAIL, v0.294.0 R-864 — use it for a command's stderr: the error is printed last); controller/internal/backup/offbox.go `truncate` |
|
| String truncation ×4 | controller/internal/util/strings.go `TruncateStr` (rune-safe, 1 caller); controller/internal/stacks/manager.go `truncateStr` (byte-based HEAD, widely used) and `tailStr` (rune-safe TAIL, v0.294.0 R-864 — use it for a command's stderr: the error is printed last); controller/internal/backup/offbox.go `truncate` |
|
||||||
| humanizeBytes ×3 | controller/internal/appbackup/appdata.go `HumanizeBytes` (canonical) + private twin; controller/internal/appexport/estimate.go `humanizeBytes`; controller/internal/backup/appbackup_bridge.go wrapper (deliberate bridge) |
|
| humanizeBytes ×3 | controller/internal/appbackup/appdata.go `HumanizeBytes` (canonical) + private twin; controller/internal/appexport/estimate.go `humanizeBytes`; controller/internal/backup/appbackup_bridge.go wrapper (deliberate bridge) |
|
||||||
| copyFile ×2 | controller/internal/stacks/migrate.go (returns bytes) vs controller/internal/appexport/export.go |
|
| copyFile ×2 | controller/internal/stacks/migrate.go (returns bytes) vs controller/internal/appexport/export.go |
|
||||||
| dir-size ×6 | controller/internal/stacks/delete.go `getDirSizeBytes`/`getDirSizeHuman`; controller/internal/backup/tier2.go `dirSizeBytes` (du -sb); controller/internal/appexport/estimate.go `dirSize`+`duBytes`; controller/internal/appexport/export.go `calcDirSize`; controller/internal/web/handlers.go `dirSizeHuman` |
|
| dir-size ×6 | controller/internal/stacks/delete.go `getDirSizeBytes`/`getDirSizeHuman`; controller/internal/backup/tier2.go `dirSizeBytes` (du -sb); controller/internal/appexport/estimate.go `dirSize`+`duBytes`; controller/internal/appexport/export.go `calcDirSize`; controller/internal/web/handlers.go `dirSizeHuman` |
|
||||||
| timeAgo switch body ×2 | controller/internal/web/funcmap.go `timeAgo` vs `timeAgoStr` (identical formatting logic) |
|
| timeAgo switch body ×2 | controller/internal/web/funcmap.go `timeAgo` vs `timeAgoStr` (identical formatting logic) |
|
||||||
| CSRF ×2 | controller/internal/web/csrf.go (session HMAC) vs controller/internal/setup/csrf.go (cookie double-submit) — intentional (pre-auth wizard) but unlabeled |
|
|
||||||
| Budapest timezone loader ×4 | controller/internal/scheduler/scheduler.go `getBudapestLocation` vs controller/internal/web/funcmap.go `getTimezone` vs controller/internal/quiesce/quiesce.go `budapestLocation` vs controller/internal/api/kept_install.go `budapest` (v0.277.0, the kept choice's dates) (v0.168.0 window gate — Budapest wall-clock, kept local to avoid a scheduler↔quiesce import edge) |
|
| Budapest timezone loader ×4 | controller/internal/scheduler/scheduler.go `getBudapestLocation` vs controller/internal/web/funcmap.go `getTimezone` vs controller/internal/quiesce/quiesce.go `budapestLocation` vs controller/internal/api/kept_install.go `budapest` (v0.277.0, the kept choice's dates) (v0.168.0 window gate — Budapest wall-clock, kept local to avoid a scheduler↔quiesce import edge) |
|
||||||
| JSON writers ×5, 3 envelope shapes | api `writeJSON`; web `writeDiskJSON`, `jsonResponse`/`jsonError`, `writeDebugJSON` |
|
| JSON writers ×5, 3 envelope shapes | api `writeJSON`; web `writeDiskJSON`, `jsonResponse`/`jsonError`, `writeDebugJSON` |
|
||||||
| Safe-name validators ×4 | controller/internal/web/validate.go `validStackName`; controller/internal/api/router.go `validStackParam` (same body — api↔web import cycle); controller/internal/backup/offbox.go `isSafeStackName`; controller/internal/appexport/validate.go `ValidateSegment` (strictest) |
|
| Safe-name validators ×5 | controller/internal/web/validate.go `validStackName`; controller/internal/api/router.go `validStackParam` (same body — api↔web import cycle); controller/internal/backup/offbox.go `isSafeStackName` (exported as `IsValidHoldStack` for the hold commands); controller/internal/report/opactions.go `validHoldStack` (same alphabet as `isSafeStackName` — report cannot import backup; clear_hold's argument check); controller/internal/appexport/validate.go `ValidateSegment` (strictest) |
|
||||||
| DB wait/import ×2 | controller/internal/appbackup/dbdump.go `waitDBReady`/`ImportDump` vs controller/internal/appexport/restore.go `waitForDB`/`importDBDump` |
|
| DB wait/import ×2 | controller/internal/appbackup/dbdump.go `waitDBReady`/`ImportDump` vs controller/internal/appexport/restore.go `waitForDB`/`importDBDump` |
|
||||||
|
| qBittorrent Web API login ×2 | controller/internal/mediawire/mediawire.go `qbLogin` (writes the drive wiring) vs controller/internal/upwatch/explain.go `QBittorrent.login` (reads every minute; keeps its session cookie, which mediawire's per-run login does not need) |
|
||||||
| compose exec ×2 | controller/internal/stacks/manager.go `composeExecCustomEnv` vs controller/internal/appexport/restore.go `composeExecEnv` (the latter has ctx+timeout; the former has the userdata belt) |
|
| compose exec ×2 | controller/internal/stacks/manager.go `composeExecCustomEnv` vs controller/internal/appexport/restore.go `composeExecEnv` (the latter has ctx+timeout; the former has the userdata belt) |
|
||||||
@@ -42,3 +42,7 @@ restic-password
|
|||||||
assets/*.svg
|
assets/*.svg
|
||||||
assets/*.png
|
assets/*.png
|
||||||
assets/*.webp
|
assets/*.webp
|
||||||
|
# build.sh's scratch directory. It is created beside the script, so a build run from a CLONE of
|
||||||
|
# this repo (which is what the clean-tree gate pushes you to when the shared tree is busy) would
|
||||||
|
# otherwise dirty the very tree the gate is checking. Generated output, never committed.
|
||||||
|
workspace/
|
||||||
+62
-31
@@ -5,7 +5,10 @@
|
|||||||
# =============================================================================
|
# =============================================================================
|
||||||
|
|
||||||
# --- Build stage ---
|
# --- Build stage ---
|
||||||
FROM golang:1.24-bookworm AS builder
|
# R-972 (v0.322.0): a supported, patched Go, pinned by version AND digest (no moving tag). Go 1.24 had no security fixes
|
||||||
|
# left (go.dev/doc/devel/release#policy). The builder's Debian does not reach the runtime (a static CGO-free binary).
|
||||||
|
# upstream: osv:Go/stdlib
|
||||||
|
FROM golang:1.27.4-trixie@sha256:b54b2639de8c1bfe538ec5ffc45f29b1932235ac5f6d63c059853646677112d9 AS builder
|
||||||
|
|
||||||
ARG TARGETOS=linux
|
ARG TARGETOS=linux
|
||||||
ARG TARGETARCH
|
ARG TARGETARCH
|
||||||
@@ -38,48 +41,76 @@ RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build \
|
|||||||
-o /build/felhom-controller \
|
-o /build/felhom-controller \
|
||||||
./cmd/controller/
|
./cmd/controller/
|
||||||
|
|
||||||
# --- Runtime stage ---
|
# --- restic: the official release binary, pinned by version AND checksum (R-1105, v0.323.0) ---
|
||||||
FROM debian:bookworm-slim
|
# Never again „whatever the OS ships": Debian 12 → 13 would have swapped restic 0.14.0 → 0.18.0 under the off-site code
|
||||||
|
# without anyone choosing it. The version below is a decision; moving it is a re-proof (07-backup-architecture.md §6.8).
|
||||||
|
# Three checks, each fails the build: restic's SHA256SUMS carries a good signature from restic's release key (vendored
|
||||||
|
# in third_party/restic/, fingerprint CF8F 18F2 8445 7597 3F79 D4E1 91A6 868B D3F7 A907 — no keyserver at build
|
||||||
|
# time); the download matches the published sum; and it matches the sum pinned HERE, so even a re-signed release
|
||||||
|
# cannot swap the binary. Pinned by TestR1105_ResticIsPinnedOutsideTheOS.
|
||||||
|
# upstream: gap:Debian announces package fixes as DSAs on security-tracker.debian.org, which the watch does not read; BEHIND on the point release is the signal
|
||||||
|
FROM debian:13.7-slim@sha256:a29215f6a35e51e22adffa17f89e9d2ef06214e64a2bad10d765c46aea49f11f AS restic
|
||||||
|
ARG TARGETARCH
|
||||||
|
# upstream: github:restic/restic
|
||||||
|
ARG RESTIC_VERSION=0.19.1
|
||||||
|
ARG RESTIC_SHA256_AMD64=f415415624dcc452f2a02b8c33641791a8c6d6d3b65bbb3543fcf9a25151585c
|
||||||
|
ARG RESTIC_SHA256_ARM64=a5f64aaab53d51e311fa3829124c5b703f2d14cf187d8640b6be3b2b49376465
|
||||||
|
COPY third_party/restic/restic-release-key.asc /tmp/restic-release-key.asc
|
||||||
|
RUN set -eu; \
|
||||||
|
apt-get update && apt-get install -y --no-install-recommends ca-certificates curl gnupg gpgv bzip2; \
|
||||||
|
case "${TARGETARCH}" in \
|
||||||
|
amd64) want="${RESTIC_SHA256_AMD64}" ;; \
|
||||||
|
arm64) want="${RESTIC_SHA256_ARM64}" ;; \
|
||||||
|
*) echo "no pinned restic checksum for architecture '${TARGETARCH}'" >&2; exit 1 ;; \
|
||||||
|
esac; \
|
||||||
|
f="restic_${RESTIC_VERSION}_linux_${TARGETARCH}.bz2"; \
|
||||||
|
url="https://github.com/restic/restic/releases/download/v${RESTIC_VERSION}"; \
|
||||||
|
cd /tmp; \
|
||||||
|
curl -fsSL -o "$f" "$url/$f"; curl -fsSL -o SHA256SUMS "$url/SHA256SUMS"; curl -fsSL -o SHA256SUMS.asc "$url/SHA256SUMS.asc"; \
|
||||||
|
gpg --dearmor < /tmp/restic-release-key.asc > /tmp/restic-release-key.gpg; \
|
||||||
|
gpgv --keyring /tmp/restic-release-key.gpg SHA256SUMS.asc SHA256SUMS; \
|
||||||
|
grep " ${f}\$" SHA256SUMS | sha256sum -c -; \
|
||||||
|
echo "${want} ${f}" | sha256sum -c -; \
|
||||||
|
bunzip2 -c "$f" > /usr/local/bin/restic; chmod 0755 /usr/local/bin/restic; \
|
||||||
|
/usr/local/bin/restic version | grep -q "^restic ${RESTIC_VERSION} "
|
||||||
|
|
||||||
# Install runtime dependencies:
|
# --- Runtime stage ---
|
||||||
# - docker-cli: for "docker compose" commands
|
# Debian 13 (R-1105, v0.323.0), pinned by point release AND digest. It waited on Debian 12 until the off-site code's
|
||||||
# - ca-certificates: for HTTPS (healthchecks pings, git)
|
# restic assumptions were re-proven on 0.18 (07-backup-architecture.md §6.8); restic itself no longer comes from here.
|
||||||
# - postgresql-client: for pg_dump
|
# upstream: gap:Debian announces package fixes as DSAs on security-tracker.debian.org, which the watch does not read; BEHIND on the point release is the signal
|
||||||
# - default-mysql-client: for mysqldump
|
FROM debian:13.7-slim@sha256:a29215f6a35e51e22adffa17f89e9d2ef06214e64a2bad10d765c46aea49f11f
|
||||||
# - sqlite3: for SQLite backup
|
|
||||||
# - git: for stack sync from Gitea
|
# Install runtime dependencies — each one is a program the controller binary runs (R-1105 re-checked every exec):
|
||||||
# - curl: for health pings and debugging
|
# - docker-cli + compose plugin: every stack operation (below)
|
||||||
# - util-linux: lsblk, blkid, mount (storage init)
|
# - ca-certificates: for HTTPS (healthchecks pings, git, the hub)
|
||||||
# - fdisk: sfdisk (partition table writing — separate from util-linux on Debian)
|
# - curl: the image's HEALTHCHECK, and the docker repo key below
|
||||||
# - e2fsprogs: mkfs.ext4 (filesystem formatting)
|
# - gnupg: dearmors docker's repo key below
|
||||||
# - rsync: for data migration between storage paths
|
# - git: catalog sync
|
||||||
# - parted: partprobe (partition table re-read after sfdisk)
|
# - util-linux: findmnt (mount reads)
|
||||||
# - restic: encrypted off-box (NAS) backup over SFTP (Part B; version pinned by the Debian release)
|
# - rsync: data migration between storage paths
|
||||||
# - openssh-client: restic's sftp backend shells out to `ssh` (the SFTP transport); also ssh-copy-id/sftp
|
# - openssh-client: restic's sftp/rclone transports shell out to `ssh`; the off-site key probe
|
||||||
# for the SLICE-2 offsite apply-bridge key install
|
# v0.323.0 (R-1105) REMOVED, because the binary never runs them: postgresql-client and default-mysql-client (every
|
||||||
# - sshpass: feeds the one-time storage-box password to ssh-copy-id -s -f (offsite apply-bridge)
|
# dump and import runs INSIDE the app's own database container — `docker exec`, appbackup/dbdump.go), sqlite3,
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
# fdisk, e2fsprogs, parted (disk work moved to the host agent in v0.37.0), sshpass (the ssh-copy-id key install it
|
||||||
|
# fed was replaced by the hub's key registrar in v0.289.0). Fewer packages, fewer known holes.
|
||||||
|
RUN apt-get update && apt-get upgrade -y --no-install-recommends && apt-get install -y --no-install-recommends \
|
||||||
ca-certificates \
|
ca-certificates \
|
||||||
curl \
|
curl \
|
||||||
gnupg \
|
gnupg \
|
||||||
git \
|
git \
|
||||||
postgresql-client \
|
|
||||||
default-mysql-client \
|
|
||||||
sqlite3 \
|
|
||||||
util-linux \
|
util-linux \
|
||||||
fdisk \
|
|
||||||
e2fsprogs \
|
|
||||||
rsync \
|
rsync \
|
||||||
parted \
|
|
||||||
restic \
|
|
||||||
openssh-client \
|
openssh-client \
|
||||||
sshpass \
|
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# Install docker-cli (without daemon)
|
COPY --from=restic /usr/local/bin/restic /usr/local/bin/restic
|
||||||
|
|
||||||
|
# Install docker-cli (without daemon). The repo's codename comes from the image's own /etc/os-release, never a
|
||||||
|
# hard-coded name (a hard-coded `bookworm` would have kept Debian 12's packages on a Debian 13 base).
|
||||||
RUN curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker.gpg \
|
RUN curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker.gpg \
|
||||||
|
&& . /etc/os-release \
|
||||||
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker.gpg] \
|
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker.gpg] \
|
||||||
https://download.docker.com/linux/debian bookworm stable" > /etc/apt/sources.list.d/docker.list \
|
https://download.docker.com/linux/debian ${VERSION_CODENAME} stable" > /etc/apt/sources.list.d/docker.list \
|
||||||
&& apt-get update \
|
&& apt-get update \
|
||||||
&& apt-get install -y --no-install-recommends docker-ce-cli docker-compose-plugin \
|
&& apt-get install -y --no-install-recommends docker-ce-cli docker-compose-plugin \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|||||||
+593
-176
File diff suppressed because it is too large.
Load diff
+119
-13
@@ -12,11 +12,18 @@
|
|||||||
# ./build.sh 0.1.0 # Build with version tag
|
# ./build.sh 0.1.0 # Build with version tag
|
||||||
# ./build.sh 0.1.0 --push # Build + push to Gitea registry
|
# ./build.sh 0.1.0 --push # Build + push to Gitea registry
|
||||||
# ./build.sh 0.1.0 --multiarch # Build amd64+arm64 + push
|
# ./build.sh 0.1.0 --multiarch # Build amd64+arm64 + push
|
||||||
|
# ./build.sh 0.1.0 --print-tags # Print the tags a build would carry, and stop (the R-1143 test)
|
||||||
|
#
|
||||||
|
# :latest is carried ONLY by a release tag (x.y.z). An -rc, dev or any other tag never moves it (R-1143).
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
# --- Configuration (edit these if your paths differ) ---
|
# --- Configuration (edit these if your paths differ) ---
|
||||||
REPO_DIR="/mnt/5_hdd/felhom.eu/git/felhom-controller"
|
# The default is the shared DooPlex clone, and the release runbook names it. It is overridable
|
||||||
|
# because that clone is shared: when another session has work in progress in it, the clean-tree gate
|
||||||
|
# rightly forbids building over them, and the way to ship is a clean clone at the pushed commit —
|
||||||
|
# not stashing somebody else's work. Set FELHOM_REPO_DIR to that clone.
|
||||||
|
REPO_DIR="${FELHOM_REPO_DIR:-/mnt/5_hdd/felhom.eu/git/felhom-controller}"
|
||||||
CONTROLLER_SRC="${REPO_DIR}/controller"
|
CONTROLLER_SRC="${REPO_DIR}/controller"
|
||||||
WEBSITE_ASSETS_DIR="/mnt/5_hdd/felhom.eu/git/felhom.eu/website/assets"
|
WEBSITE_ASSETS_DIR="/mnt/5_hdd/felhom.eu/git/felhom.eu/website/assets"
|
||||||
REGISTRY="gitea.dooplex.hu/admin"
|
REGISTRY="gitea.dooplex.hu/admin"
|
||||||
@@ -37,6 +44,21 @@ warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
|
|||||||
error() { echo -e "${RED}[ERROR]${NC} $*"; }
|
error() { echo -e "${RED}[ERROR]${NC} $*"; }
|
||||||
step() { echo -e "${CYAN}[STEP]${NC} $*"; }
|
step() { echo -e "${CYAN}[STEP]${NC} $*"; }
|
||||||
|
|
||||||
|
# --- The tags this build carries (R-1143, 2026-10-18) ---
|
||||||
|
# Until v0.328.0 every build moved :latest, release candidates included (rc.1–rc.5 each did on 2026-10-17). Nothing
|
||||||
|
# current pulls :latest — the update button takes the highest x.y.z tag — but a legacy-shaped box following it would
|
||||||
|
# have taken an rc. So :latest moves with a RELEASE only. Pinned by scripts/test_build_push_once.sh.
|
||||||
|
TAGS=("${IMAGE}:${VERSION}")
|
||||||
|
if [[ "${VERSION}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||||
|
TAGS+=("${IMAGE}:latest")
|
||||||
|
fi
|
||||||
|
TAG_ARGS=()
|
||||||
|
for t in "${TAGS[@]}"; do TAG_ARGS+=(-t "$t"); done
|
||||||
|
if [[ "${ACTION}" == "--print-tags" ]]; then
|
||||||
|
printf '%s\n' "${TAGS[@]}"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
# --- Pre-flight checks ---
|
# --- Pre-flight checks ---
|
||||||
if [[ ! -d "${CONTROLLER_SRC}" ]]; then
|
if [[ ! -d "${CONTROLLER_SRC}" ]]; then
|
||||||
error "Controller source not found: ${CONTROLLER_SRC}"
|
error "Controller source not found: ${CONTROLLER_SRC}"
|
||||||
@@ -61,11 +83,103 @@ info "║ felhom-controller image builder ║"
|
|||||||
info "╚══════════════════════════════════════╝"
|
info "╚══════════════════════════════════════╝"
|
||||||
info "Version: ${VERSION}"
|
info "Version: ${VERSION}"
|
||||||
info "Commit: ${GIT_COMMIT}"
|
info "Commit: ${GIT_COMMIT}"
|
||||||
|
info "Repo: ${REPO_DIR}"
|
||||||
info "Source: ${CONTROLLER_SRC}"
|
info "Source: ${CONTROLLER_SRC}"
|
||||||
info "Build dir: ${BUILD_DIR}"
|
info "Build dir: ${BUILD_DIR}"
|
||||||
info "Image: ${IMAGE}:${VERSION}"
|
info "Image: ${IMAGE}:${VERSION}"
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
|
# =========================================================================
|
||||||
|
# A VERSION NUMBER IS PUSHED ONCE (v0.316.0)
|
||||||
|
# =========================================================================
|
||||||
|
# 0.315.0 was built and pushed THREE times from three different commits. A box that pulled between
|
||||||
|
# the first and the last runs different code under the same number — and will never fetch the fix,
|
||||||
|
# because to the box, and to the floor, that number is already current (`09-update-architecture.md`:
|
||||||
|
# a box compares VERSIONS, and re-pulls a tag it already has only when the tag changes). Nothing in
|
||||||
|
# the build stopped it. This does.
|
||||||
|
#
|
||||||
|
# The check runs BEFORE the build, so a refusal costs no minutes. A registry that cannot be reached
|
||||||
|
# is a REFUSAL too: the point is to prove the tag is new, and "I could not ask" is not that proof.
|
||||||
|
# Local builds (no --push) are unaffected — reusing a version while iterating is the normal case.
|
||||||
|
#
|
||||||
|
# `docker manifest inspect` is the probe, so a test can put a fake `docker` on PATH
|
||||||
|
# (scripts/test_build_push_once.sh).
|
||||||
|
if [[ "${ACTION}" == "--push" || "${ACTION}" == "--multiarch" ]]; then
|
||||||
|
step "0/4 — Checking the registry: is ${VERSION} already published?"
|
||||||
|
# `set -e` is on, and a failing command substitution would abort the script before the rc is
|
||||||
|
# ever read — which would turn "the registry said no such tag" into a silent exit. The `|| true`
|
||||||
|
# keeps the failure for us to classify; that classification is the whole check.
|
||||||
|
probe_rc=0
|
||||||
|
probe_out=$(docker manifest inspect "${IMAGE}:${VERSION}" 2>&1) || probe_rc=$?
|
||||||
|
if [[ ${probe_rc} -eq 0 ]]; then
|
||||||
|
error "${IMAGE}:${VERSION} already exists in the registry — bump the version."
|
||||||
|
error "A version number is pushed once. Two images under one number mean a box can run"
|
||||||
|
error "either of them and never learn the difference. If this is a fix for something already"
|
||||||
|
error "pushed, release it as the next patch version instead."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
# Absent is the ONLY other acceptable answer. Anything that is not a clean "not found" (the
|
||||||
|
# registry is down, the login expired, DNS failed) leaves the question unanswered, and an
|
||||||
|
# unanswered question is a refusal.
|
||||||
|
if ! grep -qiE 'no such manifest|manifest unknown|not found|does not exist|NAME_UNKNOWN|MANIFEST_UNKNOWN' <<<"${probe_out}"; then
|
||||||
|
error "Could not establish whether ${IMAGE}:${VERSION} exists — refusing to build."
|
||||||
|
error "The registry answered: ${probe_out}"
|
||||||
|
error "Proving the tag is new is the point of this check; 'I could not ask' is not that proof."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
info "${VERSION} is not present in the registry — proceeding."
|
||||||
|
|
||||||
|
# AND THE TREE IT BUILDS FROM MUST BE CLEAN AND PUSHED.
|
||||||
|
#
|
||||||
|
# Until v0.316.3 this was a sentence in a runbook, and a rule without a mechanism is a wish. It
|
||||||
|
# cost a bad push the same evening it was written down: the shared clone had 31 files of another
|
||||||
|
# session's work in progress, and a build from it put their unreleased code into a published
|
||||||
|
# image under my version number. Nobody deployed it; that was luck, not a control.
|
||||||
|
#
|
||||||
|
# Two questions, both of which must be YES:
|
||||||
|
# is every tracked file committed? — otherwise the image holds something git does not
|
||||||
|
# is HEAD what origin/main has? — otherwise the image holds something nobody can fetch
|
||||||
|
# „An unpushed change does not exist" (workspace CLAUDE.md), and an image built from one is a
|
||||||
|
# thing that exists and cannot be reproduced.
|
||||||
|
if [[ -d "${REPO_DIR}/.git" ]]; then
|
||||||
|
dirty=$(cd "${REPO_DIR}" && git status --porcelain 2>/dev/null | wc -l)
|
||||||
|
if [[ "${dirty}" -ne 0 ]]; then
|
||||||
|
error "${REPO_DIR} has ${dirty} uncommitted change(s) — refusing to push a build from it."
|
||||||
|
error "An image built from a dirty tree cannot be reproduced, and on a SHARED clone it"
|
||||||
|
error "may carry work that is not yours. Commit and push, or build from a clean clone"
|
||||||
|
error "with FELHOM_REPO_DIR pointing at it."
|
||||||
|
(cd "${REPO_DIR}" && git status --porcelain | head -10 | sed 's/^/ /')
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
head_sha=$(cd "${REPO_DIR}" && git rev-parse HEAD 2>/dev/null || echo unknown)
|
||||||
|
main_sha=$(cd "${REPO_DIR}" && git rev-parse origin/main 2>/dev/null || echo unknown)
|
||||||
|
# The one other source that can be fetched again: the tag v<VERSION> AS THE SERVER HAS IT, pointing at HEAD. That
|
||||||
|
# is a patch release built off a released version while main holds unreleased work (v0.345.1, R-1300, cloudflared's
|
||||||
|
# security bump, 2026-10-26 — operator's yes in that session). Only the tag that names THIS version counts; a tag
|
||||||
|
# only on this clone, a tag on another commit, or a server that cannot be asked is a refusal. Pinned by
|
||||||
|
# scripts/test_build_push_once.sh („tag" cases).
|
||||||
|
if [[ "${head_sha}" != "${main_sha}" ]]; then
|
||||||
|
tag_sha=$(cd "${REPO_DIR}" && GIT_TERMINAL_PROMPT=0 git ls-remote origin "refs/tags/v${VERSION}" "refs/tags/v${VERSION}^{}" 2>/dev/null \
|
||||||
|
| awk '$2 ~ /\^\{\}$/ {peeled=$1} $2 !~ /\^\{\}$/ {plain=$1} END {print (peeled != "" ? peeled : plain)}') || tag_sha="" # no origin / unreachable: the error below, not set -e
|
||||||
|
if [[ -n "${tag_sha}" && "${tag_sha}" == "${head_sha}" ]]; then
|
||||||
|
info "Source tree is clean and at the pushed tag v${VERSION} (not origin/main)."
|
||||||
|
else
|
||||||
|
error "${REPO_DIR} is not at origin/main, nor at a pushed tag v${VERSION} — refusing to push."
|
||||||
|
error " HEAD ${head_sha}"
|
||||||
|
error " origin/main ${main_sha}"
|
||||||
|
error " v${VERSION} on origin ${tag_sha:-<none>}"
|
||||||
|
error "An unpushed change does not exist; an image built from one cannot be fetched again."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
info "Source tree is clean and at origin/main."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
error "${REPO_DIR} is not a git checkout — refusing to push a build whose source cannot be identified."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
# =========================================================================
|
# =========================================================================
|
||||||
# Step 1: Prepare clean build workspace
|
# Step 1: Prepare clean build workspace
|
||||||
# =========================================================================
|
# =========================================================================
|
||||||
@@ -160,14 +274,10 @@ BUILD_ARGS=(
|
|||||||
case "${ACTION}" in
|
case "${ACTION}" in
|
||||||
--push)
|
--push)
|
||||||
info "Building for current platform + pushing..."
|
info "Building for current platform + pushing..."
|
||||||
docker build "${BUILD_ARGS[@]}" \
|
docker build "${BUILD_ARGS[@]}" "${TAG_ARGS[@]}" .
|
||||||
-t "${IMAGE}:${VERSION}" \
|
|
||||||
-t "${IMAGE}:latest" \
|
|
||||||
.
|
|
||||||
|
|
||||||
info "Pushing..."
|
info "Pushing..."
|
||||||
docker push "${IMAGE}:${VERSION}"
|
for t in "${TAGS[@]}"; do docker push "$t"; done
|
||||||
docker push "${IMAGE}:latest"
|
|
||||||
;;
|
;;
|
||||||
|
|
||||||
--multiarch)
|
--multiarch)
|
||||||
@@ -183,18 +293,14 @@ case "${ACTION}" in
|
|||||||
|
|
||||||
docker buildx build "${BUILD_ARGS[@]}" \
|
docker buildx build "${BUILD_ARGS[@]}" \
|
||||||
--platform linux/amd64,linux/arm64 \
|
--platform linux/amd64,linux/arm64 \
|
||||||
-t "${IMAGE}:${VERSION}" \
|
"${TAG_ARGS[@]}" \
|
||||||
-t "${IMAGE}:latest" \
|
|
||||||
--push \
|
--push \
|
||||||
.
|
.
|
||||||
;;
|
;;
|
||||||
|
|
||||||
*)
|
*)
|
||||||
info "Building for current platform (local only)..."
|
info "Building for current platform (local only)..."
|
||||||
docker build "${BUILD_ARGS[@]}" \
|
docker build "${BUILD_ARGS[@]}" "${TAG_ARGS[@]}" .
|
||||||
-t "${IMAGE}:${VERSION}" \
|
|
||||||
-t "${IMAGE}:latest" \
|
|
||||||
.
|
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
|
|||||||
@@ -135,7 +135,7 @@ func TestMainReportsTheInterruptedOperation(t *testing.T) {
|
|||||||
body := mainBody(t)
|
body := mainBody(t)
|
||||||
names := callsInMain(t, body)
|
names := callsInMain(t, body)
|
||||||
|
|
||||||
if indexOfCall(names, "NotifyBackupFailed") < 0 {
|
if indexOfCall(names, "NotifyInterruptedOperation") < 0 {
|
||||||
t.Fatal("func main() no longer reports an interrupted app-data operation to the operator — the " +
|
t.Fatal("func main() no longer reports an interrupted app-data operation to the operator — the " +
|
||||||
"controller died mid-backup and nobody is told (§2.4)")
|
"controller died mid-backup and nobody is told (§2.4)")
|
||||||
}
|
}
|
||||||
@@ -144,7 +144,7 @@ func TestMainReportsTheInterruptedOperation(t *testing.T) {
|
|||||||
//
|
//
|
||||||
// R-174 STRENGTHENED THIS. `!= nil` alone is no longer sufficient, because Recover now returns a
|
// R-174 STRENGTHENED THIS. `!= nil` alone is no longer sufficient, because Recover now returns a
|
||||||
// non-nil result for a recovery that merely REFUSED starts (an absent data drive) — the drive
|
// non-nil result for a recovery that merely REFUSED starts (an absent data drive) — the drive
|
||||||
// gate working as designed. `NotifyBackupFailed` sends `backup_failed`, which is customer-enabled
|
// gate working as designed. `NotifyInterruptedOperation` (R-585; was `NotifyBackupFailed`) sends `backup_failed`, which is customer-enabled
|
||||||
// by default (settings.DefaultEnabledEvents), so a nil-only guard would email the customer
|
// by default (settings.DefaultEnabledEvents), so a nil-only guard would email the customer
|
||||||
// "A biztonsági mentés sikertelen!" about an app nothing is wrong with. The guard must consult
|
// "A biztonsági mentés sikertelen!" about an app nothing is wrong with. The guard must consult
|
||||||
// Alarming().
|
// Alarming().
|
||||||
@@ -156,7 +156,7 @@ func TestMainReportsTheInterruptedOperation(t *testing.T) {
|
|||||||
}
|
}
|
||||||
carries := false
|
carries := false
|
||||||
for _, name := range callsInMain(t, ifst.Body) {
|
for _, name := range callsInMain(t, ifst.Body) {
|
||||||
if name == "NotifyBackupFailed" {
|
if name == "NotifyInterruptedOperation" {
|
||||||
carries = true
|
carries = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -188,7 +188,7 @@ func TestMainReportsTheInterruptedOperation(t *testing.T) {
|
|||||||
if !guardedByAlarming {
|
if !guardedByAlarming {
|
||||||
t.Fatal("the interrupted-operation alert is not guarded by appStopRecovery.Alarming() — a " +
|
t.Fatal("the interrupted-operation alert is not guarded by appStopRecovery.Alarming() — a " +
|
||||||
"recovery that only REFUSED starts (drive absent) would be reported through " +
|
"recovery that only REFUSED starts (drive absent) would be reported through " +
|
||||||
"NotifyBackupFailed, a customer-enabled event type, telling the customer their backup " +
|
"NotifyInterruptedOperation (backup_failed), a customer-enabled event type, telling the customer their backup " +
|
||||||
"failed when the drive gate was simply doing its job (R-174)")
|
"failed when the drive gate was simply doing its job (R-174)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -493,3 +493,30 @@ func assignedIdentsIn(body *ast.BlockStmt) []string {
|
|||||||
})
|
})
|
||||||
return names
|
return names
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// R-1251: the guard's hold store and drive question are wired BEFORE Recover (a waiting put-back would otherwise be
|
||||||
|
// read as „gone" and nothing would hold the app), and the waiting put-backs are resumed after it. COMPANION
|
||||||
|
// RED-PROOF (2026-10-24): delete SetHolds or SetUndoReachable, or move either below Recover → this fails.
|
||||||
|
func TestR1251_MainWiresThePutBackWait(t *testing.T) {
|
||||||
|
names := callsInMain(t, mainBody(t))
|
||||||
|
rec := indexOfCall(names, "Recover")
|
||||||
|
for _, n := range []string{"SetHolds", "SetUndoReachable"} {
|
||||||
|
if i := indexOfCall(names, n); i < 0 || i > rec {
|
||||||
|
t.Errorf("func main() must call appStopGuard.%s before Recover (at %d, Recover at %d)", n, i, rec)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if i := indexOfCall(names, "ResumeWaitingPutBacks"); i < rec {
|
||||||
|
t.Errorf("func main() must resume the waiting put-backs after Recover (at %d, Recover at %d)", i, rec)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// R-1252: the second-drive copy asks the stack adapter (by an optional interface) whether a block was REJECTED. An
|
||||||
|
// adapter that lost the method would make every rejected block read as absent — quiet, with no alarm. Pinned at
|
||||||
|
// compile time here; the decision is tested in internal/backup.
|
||||||
|
var _ interface{ BackupBlockRejected(string) string } = (*stackAdapter)(nil)
|
||||||
|
|
||||||
|
func TestR1252_MainWiresTheUnreadableSettingsSignal(t *testing.T) {
|
||||||
|
if indexOfCall(callsInMain(t, mainBody(t)), "SetTier2SettingsUnreadableNotify") < 0 {
|
||||||
|
t.Fatal("func main() no longer wires SetTier2SettingsUnreadableNotify — a rejected block would keep the copies silently")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/busymark"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// D65 = A: the agent reads ONE fixed guest path — the controller-data volume + data/ctl/busy
|
||||||
|
// (felhom-agent ControllerBusyMarkerGuestPath, and its sudoers line). The volume is mounted at
|
||||||
|
// /opt/docker/felhom-controller, so the controller must write <default data dir>/ctl/busy.
|
||||||
|
// RED-PROOF: rename holdCtlDir or busymark.FileName → the path moves → FAILS.
|
||||||
|
func TestBusyMarkPathIsTheOneTheAgentReads(t *testing.T) {
|
||||||
|
cfg, err := config.LoadFromBytes([]byte("customer:\n id: t\n domain: t.example\n"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := filepath.Join(cfg.Paths.DataDir, holdCtlDir, busymark.FileName)
|
||||||
|
want := "/opt/docker/felhom-controller/data/ctl/busy" // = the agent's /var/lib/docker/volumes/felhom-controller-data/_data/data/ctl/busy
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("the busy file is %s, the agent reads %s — an operator reboot would never be refused for a backup", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every kind of work has its probe and the writer is started — a seam built and never wired is this project's commonest
|
||||||
|
// defect. RED-PROOF: delete any AddProbe line or the Run → FAILS.
|
||||||
|
func TestBusyMarkIsWiredAtStartup(t *testing.T) {
|
||||||
|
raw, err := os.ReadFile("main.go")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
src := string(raw)
|
||||||
|
for _, want := range []string{
|
||||||
|
`busyMark.AddProbe("an app update is running", stackMgr.AnyUpdating)`,
|
||||||
|
`return backupMgr.IsRunning() || backupMgr.RestoreStatus().Running`,
|
||||||
|
`busyMark.AddProbe("the night backup catch-up is running", catchUp.Running)`,
|
||||||
|
`busyMark.AddProbe("an app export or import is running", appExporter.IsRunning)`,
|
||||||
|
`go busyMark.Run(ctx)`,
|
||||||
|
`go webServer.WatchOperatorReboot(ctx)`, // the household line after an operator reboot
|
||||||
|
} {
|
||||||
|
if !strings.Contains(src, want) {
|
||||||
|
t.Fatalf("main.go does not contain %q", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
//go:build faultinject
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// D63 (test build only): "<skip> <fail>" lets <skip> passes through, fails the next <fail>, then removes the file.
|
||||||
|
func TestD63_TheTestBuildFailsTheArmedPointOnDemand(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
t.Setenv("FELHOM_FAULT_DIR", dir)
|
||||||
|
p := filepath.Join(dir, "stop-radicale")
|
||||||
|
if err := os.WriteFile(p, []byte("1 1\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := faultPoint("stop-radicale"); err != nil {
|
||||||
|
t.Fatalf("the first pass must go through: %v", err)
|
||||||
|
}
|
||||||
|
if err := faultPoint("stop-other"); err != nil {
|
||||||
|
t.Fatalf("another point is not armed: %v", err)
|
||||||
|
}
|
||||||
|
if err := faultPoint("stop-radicale"); err == nil {
|
||||||
|
t.Fatal("the second pass must fail")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(p); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("the spent file must be gone: %v", err)
|
||||||
|
}
|
||||||
|
if err := faultPoint("stop-radicale"); err != nil {
|
||||||
|
t.Fatalf("a spent point fails nothing: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
//go:build !faultinject
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// goBuildTag is a `go build -tags …` flag (build.sh's own `--print-tags` option is not one).
|
||||||
|
var goBuildTag = regexp.MustCompile(`\s-tags[ =]`)
|
||||||
|
|
||||||
|
// D63: the fault switch exists only in a `-tags faultinject` test build. In this (the release) build an armed fault
|
||||||
|
// file injects nothing, and neither build.sh nor the Dockerfile passes a build tag.
|
||||||
|
// RED-PROOF: build the release build with the switch (drop the !faultinject line from faultpoint_off.go and the
|
||||||
|
// faultinject line from faultpoint_on.go) → the armed point fails → FAILS.
|
||||||
|
func TestD63_TheReleaseBuildHasNoFaultSwitch(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
t.Setenv("FELHOM_FAULT_DIR", dir)
|
||||||
|
for _, p := range []string{"defwrite-after-compose", "stop-radicale"} {
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, p), []byte("0 5\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := faultPoint(p); err != nil {
|
||||||
|
t.Fatalf("the release build injected a fault at %s: %v", p, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, f := range []string{"../../build.sh", "../../Dockerfile"} {
|
||||||
|
b, err := os.ReadFile(f)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if goBuildTag.MatchString(string(b)) || strings.Contains(string(b), "faultinject") {
|
||||||
|
t.Fatalf("%s passes a build tag — the release image could carry the fault switch", f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"go/ast"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// v0.317.0 (`16` §4): the agent's same-disk verdict reaches the backup side. A seam built and never wired
|
||||||
|
// has shipped in this repo seven times; this walks main.go for the call AND for the agent call inside it.
|
||||||
|
// COMPANION RED-PROOF: delete the SetDiskJudge block → "not wired"; replace ac.SameDisk with a constant →
|
||||||
|
// "never asks the agent".
|
||||||
|
func TestDiskJudge_IsWiredAtStartup(t *testing.T) {
|
||||||
|
f, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var judge *ast.CallExpr
|
||||||
|
ast.Inspect(f, func(n ast.Node) bool {
|
||||||
|
if c, ok := n.(*ast.CallExpr); ok {
|
||||||
|
if s, ok := c.Fun.(*ast.SelectorExpr); ok && s.Sel.Name == "SetDiskJudge" {
|
||||||
|
judge = c
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if judge == nil {
|
||||||
|
t.Fatal("backupMgr.SetDiskJudge is not wired in main.go — Tier-2 would keep the st_dev rule for ever")
|
||||||
|
}
|
||||||
|
asks := false
|
||||||
|
ast.Inspect(judge, func(n ast.Node) bool {
|
||||||
|
if s, ok := n.(*ast.SelectorExpr); ok && s.Sel.Name == "SameDisk" {
|
||||||
|
asks = true
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if !asks {
|
||||||
|
t.Fatal("SetDiskJudge is wired but never asks the agent (no SameDisk call inside it)")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
//go:build !faultinject
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
// faultPoint is the D63 live-proof fault switch (operator ruling 2026-10-29: prove R-1256 H4 and H5's failed stop live,
|
||||||
|
// with a fault switch in a TEST build only). In every build without the `faultinject` tag — the release image among
|
||||||
|
// them: build.sh and the Dockerfile pass no build tags — it does nothing and reads nothing. Pinned by
|
||||||
|
// TestD63_TheReleaseBuildHasNoFaultSwitch; the switch itself is faultpoint_on.go.
|
||||||
|
func faultPoint(string) error { return nil }
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
//go:build faultinject
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// faultPoint (TEST BUILDS ONLY — `go build -tags faultinject`; never the release image, faultpoint_off.go) fails a named
|
||||||
|
// point on demand, for the D63 live proofs of R-1256 H4 (a definition write that fails after the compose was written)
|
||||||
|
// and H5 (a put-back whose stop fails). Armed by a file <dir>/<point> holding "<skip> <fail>": the next <skip> passes go
|
||||||
|
// through, the <fail> after them fail, and the file is removed when both are spent. <dir> is $FELHOM_FAULT_DIR, else
|
||||||
|
// /opt/docker/felhom-controller/faults (the controller's data volume). A file that does not parse fails nothing.
|
||||||
|
var faultMu sync.Mutex
|
||||||
|
|
||||||
|
func faultPoint(point string) error {
|
||||||
|
faultMu.Lock()
|
||||||
|
defer faultMu.Unlock()
|
||||||
|
dir := os.Getenv("FELHOM_FAULT_DIR")
|
||||||
|
if dir == "" {
|
||||||
|
dir = "/opt/docker/felhom-controller/faults"
|
||||||
|
}
|
||||||
|
p := filepath.Join(dir, point)
|
||||||
|
data, err := os.ReadFile(p)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
f := strings.Fields(string(data))
|
||||||
|
if len(f) != 2 {
|
||||||
|
log.Printf("[WARN] [faultinject] %s: %q does not parse as \"<skip> <fail>\" — nothing injected", p, strings.TrimSpace(string(data)))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
skip, e1 := strconv.Atoi(f[0])
|
||||||
|
fail, e2 := strconv.Atoi(f[1])
|
||||||
|
if e1 != nil || e2 != nil || skip < 0 || fail < 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
write := func() {
|
||||||
|
if skip == 0 && fail == 0 {
|
||||||
|
_ = os.Remove(p)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = os.WriteFile(p, []byte(fmt.Sprintf("%d %d\n", skip, fail)), 0o600)
|
||||||
|
}
|
||||||
|
if skip > 0 {
|
||||||
|
skip--
|
||||||
|
write()
|
||||||
|
log.Printf("[WARN] [faultinject] %s: passed (skip left %d, fail left %d)", point, skip, fail)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if fail > 0 {
|
||||||
|
fail--
|
||||||
|
write()
|
||||||
|
log.Printf("[ERROR] [faultinject] %s: FAULT INJECTED (fail left %d)", point, fail)
|
||||||
|
return fmt.Errorf("FAULT INJECTED at %s (D63 test build)", point)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/report"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ── D64 = B + R-1343: the operator clears a hold in the RUNNING controller ─────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// Two routes reach the same door (clearHoldNow):
|
||||||
|
// - the hub's „Clear hold" → the operator action clear_hold (internal/report/opactions.go), run in this process;
|
||||||
|
// - the box command `felhom-controller --clear-restore-hold <app>` (run with `docker exec` inside the guest) → the
|
||||||
|
// local socket below → the running controller.
|
||||||
|
// The running controller clears the hold in memory AND saves settings.json at once (backup.ClearHoldByOperator), so
|
||||||
|
// no later save — the hold reporter's, a hub report's — can write it back (R-1343). The household's „held" sentence
|
||||||
|
// goes with it: every reader (the page, the start gate, the API, the hold reporter) reads the same settings record.
|
||||||
|
// The ONE held flag kept elsewhere — stacks.Manager's „the last update ended held" — is forgotten here too.
|
||||||
|
|
||||||
|
// holdClearDeps are clearHoldNow's seams (production: holdClearDepsFor).
|
||||||
|
type holdClearDeps struct {
|
||||||
|
clear func(stack string, beforeLift func()) (settings.RestoreHold, error) // backup.AppStopGuard.ClearHoldByOperatorThen
|
||||||
|
forgetUpdateHeld func(stack string) bool // stacks.Manager.ForgetUpdateHeld (nil = none)
|
||||||
|
// keepStopped (R-1350) records that the stop is wanted for an app that is not up — run once the hold is found and
|
||||||
|
// BEFORE it is lifted: stacks.Manager.RecordStopWantedIfDown (nil = none).
|
||||||
|
keepStopped func(stack string) (bool, error)
|
||||||
|
logger *log.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
// clearHoldNow lifts stack's hold and returns the result sentence (English, operator-facing). who names the person
|
||||||
|
// and the route for the box's own log, e.g. „the operator via the hub, action #12". A refusal (bad name, no hold) is
|
||||||
|
// wrapped in report.ErrActionRefused, and nothing was changed.
|
||||||
|
func clearHoldNow(d holdClearDeps, stack, who string) (string, error) {
|
||||||
|
if d.clear == nil {
|
||||||
|
return "", fmt.Errorf("%w: clearing a hold is not available on this box", report.ErrActionRefused)
|
||||||
|
}
|
||||||
|
var before func()
|
||||||
|
if d.keepStopped != nil {
|
||||||
|
before = func() {
|
||||||
|
rec, kerr := d.keepStopped(stack)
|
||||||
|
switch {
|
||||||
|
case kerr != nil && d.logger != nil:
|
||||||
|
d.logger.Printf("[WARN] [hold] %s: the stop could not be recorded as wanted (%v) — the dead-app alarm may follow the clear (R-1350)", stack, kerr)
|
||||||
|
case rec && d.logger != nil:
|
||||||
|
d.logger.Printf("[INFO] [hold] %s: the stop is recorded as wanted (desired state: stopped) — no dead-app alarm; the household's Start ends it (R-1350)", stack)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h, err := d.clear(stack, before)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, backup.ErrHoldBadStack):
|
||||||
|
return "", fmt.Errorf("%w: %q is not a valid app name — nothing was changed", report.ErrActionRefused, stack)
|
||||||
|
case errors.Is(err, backup.ErrNotHeld):
|
||||||
|
return "", fmt.Errorf("%w: %s has no hold — nothing was changed", report.ErrActionRefused, stack)
|
||||||
|
case err != nil:
|
||||||
|
return "", fmt.Errorf("clearing the hold on %s failed: %v", stack, err)
|
||||||
|
}
|
||||||
|
if d.forgetUpdateHeld != nil && d.forgetUpdateHeld(stack) {
|
||||||
|
if d.logger != nil {
|
||||||
|
d.logger.Printf("[INFO] [hold] %s: the update's held state is forgotten with the hold", stack)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if d.logger != nil {
|
||||||
|
d.logger.Printf("[WARN] [hold] %s: hold CLEARED by %s — it was %s (set %s); the app is not started by this", stack, who, h.WireReason(), h.At)
|
||||||
|
}
|
||||||
|
msg := fmt.Sprintf("the hold on %s is cleared (it was: %s). The app is NOT started by this — the household's Start, or a restore, starts it", stack, h.Why())
|
||||||
|
if h.Reason == settings.HoldReasonPutBackPending {
|
||||||
|
dir := h.SafetyDump
|
||||||
|
if dir == "" {
|
||||||
|
dir = "(not named in the hold)"
|
||||||
|
}
|
||||||
|
msg += ". Its waiting put-back is dropped: the pre-restore copy stays on disk at " + dir + " and is never poured back by itself"
|
||||||
|
}
|
||||||
|
return msg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── the local channel (R-1343) ────────────────────────────────────────────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// WHY A UNIX SOCKET IN THE CONTROLLER'S DATA DIR, mode 0600 in a 0700 directory, and nothing on TCP:
|
||||||
|
// - traefik, the LAN and every app reach the controller only over TCP (:8080, :8081). A unix socket has no port,
|
||||||
|
// so none of them can reach it, whatever a proxy header or a forwarded request says;
|
||||||
|
// - the data dir is the controller's own volume: no app container mounts it, and only root in the guest
|
||||||
|
// (`pct exec <vmid> -- docker exec felhom-controller …`, the operator gate this project already uses) can enter
|
||||||
|
// the controller's container to use it;
|
||||||
|
// - the directory is created 0700 BEFORE the socket is bound, so the moment between bind and chmod is not a window;
|
||||||
|
// - the peer's uid must equal this process's (SO_PEERCRED, holdctl_linux.go) — a second lock on the same door.
|
||||||
|
// The customer's HTTP surface is deliberately NOT used: it authenticates as the household, and a household clearing
|
||||||
|
// its own hold is what the hold exists to prevent. Pinned by TestHoldCtl_NotReachableFromOutside.
|
||||||
|
|
||||||
|
const (
|
||||||
|
holdCtlDir = "ctl"
|
||||||
|
holdCtlSock = "hold.sock"
|
||||||
|
// holdCtlOpClear is the one request this channel answers.
|
||||||
|
holdCtlOpClear = "clear_hold"
|
||||||
|
// holdCtlMaxRequest bounds what one request may send.
|
||||||
|
holdCtlMaxRequest = 4096
|
||||||
|
)
|
||||||
|
|
||||||
|
// holdCtlPath is the socket's path under the controller's data dir.
|
||||||
|
func holdCtlPath(dataDir string) string { return filepath.Join(dataDir, holdCtlDir, holdCtlSock) }
|
||||||
|
|
||||||
|
type holdCtlRequest struct {
|
||||||
|
Op string `json:"op"`
|
||||||
|
Stack string `json:"stack"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type holdCtlResponse struct {
|
||||||
|
Outcome string `json:"outcome"` // done | refused | failed (report.Outcome*)
|
||||||
|
Message string `json:"message"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// listenHoldCtl binds the socket and serves it until the listener is closed (closing it removes the socket file).
|
||||||
|
// clear is clearHoldNow bound to the running controller's deps.
|
||||||
|
func listenHoldCtl(path string, clear func(stack, who string) (string, error), logger *log.Logger) (net.Listener, error) {
|
||||||
|
dir := filepath.Dir(path)
|
||||||
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := os.Chmod(dir, 0o700); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// A socket left by a controller that died is replaced; anything else at that path is refused, never removed.
|
||||||
|
if fi, err := os.Lstat(path); err == nil {
|
||||||
|
if fi.Mode()&os.ModeSocket == 0 {
|
||||||
|
return nil, fmt.Errorf("%s exists and is not a socket — refusing to replace it", path)
|
||||||
|
}
|
||||||
|
if err := os.Remove(path); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ln, err := net.Listen("unix", path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := os.Chmod(path, 0o600); err != nil {
|
||||||
|
ln.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
conn, err := ln.Accept()
|
||||||
|
if err != nil {
|
||||||
|
if !errors.Is(err, net.ErrClosed) && logger != nil {
|
||||||
|
logger.Printf("[WARN] [hold] local channel stopped: %v", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go serveHoldCtl(conn, clear, logger)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return ln, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func serveHoldCtl(conn net.Conn, clear func(stack, who string) (string, error), logger *log.Logger) {
|
||||||
|
defer conn.Close()
|
||||||
|
_ = conn.SetDeadline(time.Now().Add(30 * time.Second))
|
||||||
|
answer := func(r holdCtlResponse) { _ = json.NewEncoder(conn).Encode(r) }
|
||||||
|
if ok, why := holdCtlPeerAllowed(conn); !ok {
|
||||||
|
if logger != nil {
|
||||||
|
logger.Printf("[WARN] [hold] local channel: a request was refused — %s", why)
|
||||||
|
}
|
||||||
|
answer(holdCtlResponse{Outcome: report.OutcomeRefused, Message: "refused: " + why})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
line, err := bufio.NewReader(io.LimitReader(conn, holdCtlMaxRequest)).ReadBytes('\n')
|
||||||
|
if err != nil && len(line) == 0 {
|
||||||
|
answer(holdCtlResponse{Outcome: report.OutcomeRefused, Message: "no request was read"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var req holdCtlRequest
|
||||||
|
if err := json.Unmarshal(line, &req); err != nil || req.Op != holdCtlOpClear {
|
||||||
|
answer(holdCtlResponse{Outcome: report.OutcomeRefused, Message: "unknown request — this channel only clears a hold"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
msg, err := clear(req.Stack, "the operator on the box (--clear-restore-hold)")
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
answer(holdCtlResponse{Outcome: report.OutcomeDone, Message: msg})
|
||||||
|
case errors.Is(err, report.ErrActionRefused):
|
||||||
|
answer(holdCtlResponse{Outcome: report.OutcomeRefused, Message: strings.TrimPrefix(err.Error(), report.ErrActionRefused.Error()+": ")})
|
||||||
|
default:
|
||||||
|
answer(holdCtlResponse{Outcome: report.OutcomeFailed, Message: err.Error()})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// askRunningControllerToClear sends one clear request. reached=false: no controller answered at path (no socket, or
|
||||||
|
// a socket nobody listens on) — nothing was asked, so the caller may edit settings.json itself. reached=true with an
|
||||||
|
// error: the request may have been applied; the caller must not edit the file.
|
||||||
|
func askRunningControllerToClear(path, stack string) (resp holdCtlResponse, reached bool, err error) {
|
||||||
|
conn, err := net.DialTimeout("unix", path, 3*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
return holdCtlResponse{}, false, err
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
_ = conn.SetDeadline(time.Now().Add(60 * time.Second))
|
||||||
|
if err := json.NewEncoder(conn).Encode(holdCtlRequest{Op: holdCtlOpClear, Stack: stack}); err != nil {
|
||||||
|
return holdCtlResponse{}, true, err
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(io.LimitReader(conn, 64*1024)).Decode(&resp); err != nil {
|
||||||
|
return holdCtlResponse{}, true, err
|
||||||
|
}
|
||||||
|
return resp, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// clearRestoreHoldCLI is the box command `--clear-restore-hold <app>` (R-379, R-1343). It asks the running
|
||||||
|
// controller first; only when none answers does it edit settings.json itself, and it says which one happened.
|
||||||
|
// Returns the process exit code: 0 cleared, 2 refused (nothing changed), 1 failed or unknown.
|
||||||
|
func clearRestoreHoldCLI(dataDir, stack string, stdout, stderr io.Writer) int {
|
||||||
|
path := holdCtlPath(dataDir)
|
||||||
|
resp, reached, err := askRunningControllerToClear(path, stack)
|
||||||
|
if reached {
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "the running controller was reached, but its answer was lost: %v\n", err)
|
||||||
|
fmt.Fprintf(stderr, " The hold may or may not be cleared. Check with: felhom-controller --restore-holds\n")
|
||||||
|
fmt.Fprintf(stderr, " settings.json was NOT edited by this command.\n")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
switch resp.Outcome {
|
||||||
|
case report.OutcomeDone:
|
||||||
|
fmt.Fprintf(stdout, "%s.\n", resp.Message)
|
||||||
|
fmt.Fprintf(stdout, " Cleared by the RUNNING controller (memory and settings.json together) — no restart is needed.\n")
|
||||||
|
return 0
|
||||||
|
case report.OutcomeRefused:
|
||||||
|
fmt.Fprintf(stderr, "%s\n", resp.Message)
|
||||||
|
return 2
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(stderr, "the running controller could not clear the hold: %s\n", resp.Message)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// No controller answered: it is not running (or is older than this channel). The file is the only copy.
|
||||||
|
fmt.Fprintf(stdout, "No running controller answered on %s (%v).\n", path, err)
|
||||||
|
fmt.Fprintf(stdout, " Editing settings.json directly instead.\n")
|
||||||
|
if !backup.IsValidHoldStack(stack) {
|
||||||
|
fmt.Fprintf(stderr, "%q is not a valid app name — nothing was changed\n", stack)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
lg := log.New(stderr, "", 0)
|
||||||
|
sett, lerr := settings.Load(filepath.Join(dataDir, "settings.json"), lg)
|
||||||
|
if lerr != nil {
|
||||||
|
fmt.Fprintf(stderr, "restore-hold: loading settings: %v\n", lerr)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
// The same door as the running controller's (a waiting put-back is dropped from the app-stop marker too), over
|
||||||
|
// this process's copy — the only copy while no controller runs.
|
||||||
|
g := backup.NewAppStopGuard(filepath.Join(dataDir, "appstop-state.json"), lg)
|
||||||
|
g.SetHolds(sett)
|
||||||
|
h, cerr := g.ClearHoldByOperator(stack)
|
||||||
|
switch {
|
||||||
|
case errors.Is(cerr, backup.ErrNotHeld):
|
||||||
|
// "there was nothing to clear" is not success — a silent 0 here would let an operator believe they had
|
||||||
|
// unblocked an app whose name they mistyped.
|
||||||
|
fmt.Fprintf(stderr, "no restore hold in force for %q — nothing was changed\n", stack)
|
||||||
|
return 2
|
||||||
|
case cerr != nil:
|
||||||
|
fmt.Fprintf(stderr, "restore-hold: clearing %s: %v\n", stack, cerr)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, "restore hold cleared for %s in settings.json (no controller was running to ask; it was: %s).\n", stack, h.Why())
|
||||||
|
if h.Reason == settings.HoldReasonPutBackPending {
|
||||||
|
fmt.Fprintf(stdout, " Its waiting put-back is dropped; the pre-restore copy stays on disk at %s.\n", orNone(h.SafetyDump))
|
||||||
|
}
|
||||||
|
fmt.Fprintf(stdout, " The controller reads it when it starts. If a controller IS running in this guest after all, restart it NOW,\n")
|
||||||
|
fmt.Fprintf(stdout, " INSIDE THE GUEST — from the Proxmox host: pct exec <vmid> -- systemctl restart felhom-controller-bootstrap.service\n")
|
||||||
|
fmt.Fprintf(stdout, " — or its next settings save writes the hold back (R-1343).\n")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// holdClearCommandHint is the exact guest command, for the help text and the operator's mail.
|
||||||
|
const holdClearCommandHint = "pct exec <vmid> -- docker exec felhom-controller felhom-controller --clear-restore-hold <app>"
|
||||||
@@ -0,0 +1,559 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"go/ast"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/holdreport"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/report"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// D64 = B (operator ruling 2026-10-29 12:10) + R-1343: the operator clears a hold — from the hub (clear_hold) or with
|
||||||
|
// the box command — IN THE RUNNING CONTROLLER, so the hold is gone from memory and from settings.json together and no
|
||||||
|
// later save brings it back.
|
||||||
|
//
|
||||||
|
// RED-PROOFS (2026-10-29):
|
||||||
|
// - TestR1343_TheBoxCommandClearsThroughTheRunningController: with clearRestoreHoldCLI's socket call skipped (the
|
||||||
|
// old second-process edit of settings.json), it fails on „the hold came back after a later save of the running
|
||||||
|
// controller" — the R-1343 measurement, in a test;
|
||||||
|
// - TestD64_ClearPutBackPendingDropsTheMarkerEntry: with the dropFromMarker call removed from
|
||||||
|
// ClearHoldByOperator, it fails on „a later controller start poured the old copy back";
|
||||||
|
// - TestD64_ClearHoldViaTheHub: with the forgetUpdateHeld call removed from clearHoldNow, it fails on „the
|
||||||
|
// update's held flag was not forgotten".
|
||||||
|
// - TestD64_ClearHoldViaTheHub + TestD64_ClearHoldStaysGoneAfterALaterSave: with ClearHoldByOperator clearing a
|
||||||
|
// SECOND Settings loaded from disk (the old CLI's shape) instead of the running one, they fail on „the running
|
||||||
|
// controller still holds the app" / „the hold came back after a later save of the running controller".
|
||||||
|
|
||||||
|
// d64Rig is a running controller's hold side: its Settings, the app-stop guard wired to them, and a log.
|
||||||
|
type d64Rig struct {
|
||||||
|
dir string
|
||||||
|
sett *settings.Settings
|
||||||
|
guard *backup.AppStopGuard
|
||||||
|
logBuf *syncBuffer
|
||||||
|
logger *log.Logger
|
||||||
|
forgot []string
|
||||||
|
holdDeps holdClearDeps
|
||||||
|
}
|
||||||
|
|
||||||
|
type syncBuffer struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
b bytes.Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *syncBuffer) Write(p []byte) (int, error) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
return s.b.Write(p)
|
||||||
|
}
|
||||||
|
func (s *syncBuffer) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() }
|
||||||
|
|
||||||
|
func newD64Rig(t *testing.T) *d64Rig {
|
||||||
|
t.Helper()
|
||||||
|
r := &d64Rig{dir: t.TempDir(), logBuf: &syncBuffer{}}
|
||||||
|
r.logger = log.New(r.logBuf, "", 0)
|
||||||
|
sett, err := settings.Load(filepath.Join(r.dir, "settings.json"), r.logger)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r.sett = sett
|
||||||
|
r.guard = backup.NewAppStopGuard(filepath.Join(r.dir, "appstop-state.json"), r.logger)
|
||||||
|
r.guard.SetHolds(sett)
|
||||||
|
r.holdDeps = holdClearDeps{
|
||||||
|
clear: r.guard.ClearHoldByOperatorThen,
|
||||||
|
forgetUpdateHeld: func(s string) bool { r.forgot = append(r.forgot, s); return true },
|
||||||
|
logger: r.logger,
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *d64Rig) hold(t *testing.T, h settings.RestoreHold) {
|
||||||
|
t.Helper()
|
||||||
|
if h.At == "" {
|
||||||
|
h.At = "2026-10-29T08:18:00Z"
|
||||||
|
}
|
||||||
|
if err := r.sett.SetRestoreHold(h); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *d64Rig) onDisk(t *testing.T, stack string) bool {
|
||||||
|
t.Helper()
|
||||||
|
s, err := settings.Load(filepath.Join(r.dir, "settings.json"), log.New(io.Discard, "", 0))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, held := s.GetRestoreHold(stack)
|
||||||
|
return held
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *d64Rig) actions() *report.OperatorActions {
|
||||||
|
return report.NewOperatorActions(context.Background(), operatorActionHandlers(nil, nil, r.holdDeps, nil, r.logger), r.logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
func onlyResult(t *testing.T, o *report.OperatorActions, id int64) report.OperatorActionResult {
|
||||||
|
t.Helper()
|
||||||
|
for _, x := range o.Results() {
|
||||||
|
if x.ID == id {
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("no result for #%d: %+v", id, o.Results())
|
||||||
|
return report.OperatorActionResult{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The hub's clear_hold: the hold is gone (memory and disk), the household's held sentence is gone, the update's
|
||||||
|
// held flag is forgotten, the box logs who did it, and the result names what was cleared.
|
||||||
|
func TestD64_ClearHoldViaTheHub(t *testing.T) {
|
||||||
|
r := newD64Rig(t)
|
||||||
|
r.hold(t, settings.RestoreHold{Stack: "paperless", ReplayError: "ERROR: relation exists", RollbackErr: "psql: refused"})
|
||||||
|
cfg := &config.Config{}
|
||||||
|
cfg.Paths.DataDir = r.dir
|
||||||
|
mgr := backup.NewManager(cfg, r.sett, r.logger)
|
||||||
|
if held, why := mgr.RestoreHoldForLang("paperless", "hu"); !held || why == "" {
|
||||||
|
t.Fatal("fixture: the household must read a held sentence before the clear")
|
||||||
|
}
|
||||||
|
|
||||||
|
o := r.actions()
|
||||||
|
o.Reconcile([]report.OperatorAction{{ID: 12, Action: report.OpClearHold, Arg: "paperless"}})
|
||||||
|
res := onlyResult(t, o, 12)
|
||||||
|
if res.Outcome != report.OutcomeDone {
|
||||||
|
t.Fatalf("result %+v", res)
|
||||||
|
}
|
||||||
|
for _, want := range []string{"the hold on paperless is cleared", "held after a failed restore whose rollback also failed", "NOT started by this"} {
|
||||||
|
if !strings.Contains(res.Message, want) {
|
||||||
|
t.Errorf("result message %q lacks %q", res.Message, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, held := r.sett.GetRestoreHold("paperless"); held {
|
||||||
|
t.Fatal("the running controller still holds the app")
|
||||||
|
}
|
||||||
|
if r.onDisk(t, "paperless") {
|
||||||
|
t.Fatal("settings.json still holds the app")
|
||||||
|
}
|
||||||
|
if held, why := mgr.RestoreHoldForLang("paperless", "hu"); held || why != "" {
|
||||||
|
t.Fatalf("the household still reads a held sentence: %q", why)
|
||||||
|
}
|
||||||
|
if len(r.forgot) != 1 || r.forgot[0] != "paperless" {
|
||||||
|
t.Fatalf("the update's held flag was not forgotten: %v", r.forgot)
|
||||||
|
}
|
||||||
|
if lg := r.logBuf.String(); !strings.Contains(lg, "paperless: hold CLEARED by the operator via the hub, action #12") {
|
||||||
|
t.Fatalf("the box's log must say who cleared it:\n%s", lg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refusals change nothing: an app nobody ever held, a second press on an app already cleared, a bad name.
|
||||||
|
func TestD64_ClearHoldRefusals(t *testing.T) {
|
||||||
|
r := newD64Rig(t)
|
||||||
|
r.hold(t, settings.RestoreHold{Stack: "kimai", Reason: settings.HoldReasonUpdateFailed})
|
||||||
|
o := r.actions()
|
||||||
|
o.Reconcile([]report.OperatorAction{{ID: 1, Action: report.OpClearHold, Arg: "nosuchapp"}})
|
||||||
|
if res := onlyResult(t, o, 1); res.Outcome != report.OutcomeRefused || !strings.Contains(res.Message, "nosuchapp has no hold") {
|
||||||
|
t.Fatalf("unknown app: %+v", res)
|
||||||
|
}
|
||||||
|
if _, held := r.sett.GetRestoreHold("kimai"); !held || !r.onDisk(t, "kimai") {
|
||||||
|
t.Fatal("a refusal changed another app's hold")
|
||||||
|
}
|
||||||
|
if len(r.forgot) != 0 {
|
||||||
|
t.Fatalf("a refusal touched the update state: %v", r.forgot)
|
||||||
|
}
|
||||||
|
o.Reconcile([]report.OperatorAction{{ID: 2, Action: report.OpClearHold, Arg: "kimai"}})
|
||||||
|
o.Reconcile([]report.OperatorAction{{ID: 3, Action: report.OpClearHold, Arg: "kimai"}})
|
||||||
|
if res := onlyResult(t, o, 3); res.Outcome != report.OutcomeRefused || !strings.Contains(res.Message, "kimai has no hold") {
|
||||||
|
t.Fatalf("not held (second press): %+v", res)
|
||||||
|
}
|
||||||
|
if _, err := clearHoldNow(r.holdDeps, "../kimai", "test"); err == nil || !strings.Contains(err.Error(), "not a valid app name") {
|
||||||
|
t.Fatalf("a bad name must be refused by the door itself too: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// R-1343's order: clear, then ANOTHER component saves settings (the hold reporter, a hub report), then the file is
|
||||||
|
// read back — the hold must stay gone, in memory and on disk.
|
||||||
|
func TestD64_ClearHoldStaysGoneAfterALaterSave(t *testing.T) {
|
||||||
|
r := newD64Rig(t)
|
||||||
|
r.hold(t, settings.RestoreHold{Stack: "radicale", Reason: settings.HoldReasonRestoreMixed})
|
||||||
|
o := r.actions()
|
||||||
|
o.Reconcile([]report.OperatorAction{{ID: 5, Action: report.OpClearHold, Arg: "radicale"}})
|
||||||
|
if res := onlyResult(t, o, 5); res.Outcome != report.OutcomeDone {
|
||||||
|
t.Fatalf("result %+v", res)
|
||||||
|
}
|
||||||
|
if err := r.sett.SetReportedHolds(map[string]string{"other": "x|y"}); err != nil { // another component's save
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if r.onDisk(t, "radicale") {
|
||||||
|
t.Fatal("the hold came back after a later save of the running controller")
|
||||||
|
}
|
||||||
|
if _, held := r.sett.GetRestoreHold("radicale"); held {
|
||||||
|
t.Fatal("the running controller holds the app again")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The same order through the BOX COMMAND: it reaches the running controller over the socket; no restart.
|
||||||
|
func TestR1343_TheBoxCommandClearsThroughTheRunningController(t *testing.T) {
|
||||||
|
r := newD64Rig(t)
|
||||||
|
r.hold(t, settings.RestoreHold{Stack: "radicale", Reason: settings.HoldReasonRestoreMixed})
|
||||||
|
ln, err := listenHoldCtl(holdCtlPath(r.dir), func(stack, who string) (string, error) { return clearHoldNow(r.holdDeps, stack, who) }, r.logger)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer ln.Close()
|
||||||
|
|
||||||
|
var out, errb bytes.Buffer
|
||||||
|
if code := clearRestoreHoldCLI(r.dir, "radicale", &out, &errb); code != 0 {
|
||||||
|
t.Fatalf("exit %d, stdout %q, stderr %q", code, out.String(), errb.String())
|
||||||
|
}
|
||||||
|
if err := r.sett.SetReportedHolds(map[string]string{"other": "x|y"}); err != nil { // the running controller's next save
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if r.onDisk(t, "radicale") {
|
||||||
|
t.Fatal("the hold came back after a later save of the running controller")
|
||||||
|
}
|
||||||
|
if !strings.Contains(out.String(), "Cleared by the RUNNING controller") || !strings.Contains(out.String(), "no restart is needed") {
|
||||||
|
t.Fatalf("the command must say it went through the running controller and needs no restart:\n%s", out.String())
|
||||||
|
}
|
||||||
|
if !strings.Contains(r.logBuf.String(), "hold CLEARED by the operator on the box (--clear-restore-hold)") {
|
||||||
|
t.Fatalf("the box's log must say who cleared it:\n%s", r.logBuf.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// A second run: refused through the socket, exit 2, nothing edited.
|
||||||
|
out.Reset()
|
||||||
|
errb.Reset()
|
||||||
|
if code := clearRestoreHoldCLI(r.dir, "radicale", &out, &errb); code != 2 || !strings.Contains(errb.String(), "radicale has no hold") {
|
||||||
|
t.Fatalf("not held: exit %d, stderr %q", code, errb.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// No controller runs (no socket, or a socket nobody listens on): the command edits settings.json and says so plainly,
|
||||||
|
// naming the guest restart for the case a controller runs after all.
|
||||||
|
func TestR1343_TheBoxCommandFallsBackWhenNoControllerRuns(t *testing.T) {
|
||||||
|
for _, stale := range []bool{false, true} {
|
||||||
|
r := newD64Rig(t)
|
||||||
|
r.hold(t, settings.RestoreHold{Stack: "kimai", Reason: settings.HoldReasonUpdateFailed})
|
||||||
|
if stale { // a socket left by a controller that died
|
||||||
|
ln, err := listenHoldCtl(holdCtlPath(r.dir), func(string, string) (string, error) { return "", nil }, r.logger)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ln.(*net.UnixListener).SetUnlinkOnClose(false)
|
||||||
|
ln.Close()
|
||||||
|
}
|
||||||
|
var out, errb bytes.Buffer
|
||||||
|
if code := clearRestoreHoldCLI(r.dir, "kimai", &out, &errb); code != 0 {
|
||||||
|
t.Fatalf("stale=%v: exit %d, stderr %q", stale, code, errb.String())
|
||||||
|
}
|
||||||
|
for _, want := range []string{"No running controller answered", "Editing settings.json directly", "INSIDE THE GUEST", "pct exec <vmid> -- systemctl restart felhom-controller-bootstrap.service"} {
|
||||||
|
if !strings.Contains(out.String(), want) {
|
||||||
|
t.Errorf("stale=%v: output lacks %q:\n%s", stale, want, out.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if r.onDisk(t, "kimai") {
|
||||||
|
t.Fatalf("stale=%v: settings.json still holds the app", stale)
|
||||||
|
}
|
||||||
|
out.Reset()
|
||||||
|
errb.Reset()
|
||||||
|
if code := clearRestoreHoldCLI(r.dir, "kimai", &out, &errb); code != 2 {
|
||||||
|
t.Fatalf("stale=%v: not held must exit 2, got %d", stale, code)
|
||||||
|
}
|
||||||
|
if code := clearRestoreHoldCLI(r.dir, "../x", &out, &errb); code != 2 {
|
||||||
|
t.Fatalf("stale=%v: a bad name must exit 2, got %d", stale, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A put-back WAITING for its drive is also in the app-stop marker: clearing the hold must drop it there too, or the
|
||||||
|
// next controller start with the drive bound would pour the old copy over what the app wrote after the clear. The
|
||||||
|
// copy itself stays on disk (nothing is deleted).
|
||||||
|
func TestD64_ClearPutBackPendingDropsTheMarkerEntry(t *testing.T) {
|
||||||
|
r := newD64Rig(t)
|
||||||
|
undo := filepath.Join(r.dir, "drive", "felhom-data", "backups", "restore-undo", "immich", "20261029T080000Z")
|
||||||
|
if err := os.MkdirAll(undo, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(undo, "undo.json"), []byte(`{"stack":"immich"}`), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.guard.Begin("unit-restore:immich", backup.ReasonUnitRestore, []string{"immich"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.guard.SetUndo("immich", undo); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r.hold(t, settings.RestoreHold{Stack: "immich", Reason: settings.HoldReasonPutBackPending, SafetyDump: undo})
|
||||||
|
|
||||||
|
o := r.actions()
|
||||||
|
o.Reconcile([]report.OperatorAction{{ID: 3, Action: report.OpClearHold, Arg: "immich"}})
|
||||||
|
res := onlyResult(t, o, 3)
|
||||||
|
if res.Outcome != report.OutcomeDone || !strings.Contains(res.Message, "waiting put-back is dropped") || !strings.Contains(res.Message, undo) {
|
||||||
|
t.Fatalf("result %+v", res)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(undo, "undo.json")); err != nil {
|
||||||
|
t.Fatal("the copy must stay on disk")
|
||||||
|
}
|
||||||
|
// The consequence: a later controller start with the drive bound pours nothing back.
|
||||||
|
poured := &recordingPutBacker{}
|
||||||
|
g2 := backup.NewAppStopGuard(filepath.Join(r.dir, "appstop-state.json"), r.logger)
|
||||||
|
g2.SetHolds(r.sett)
|
||||||
|
g2.SetPutBacker(poured)
|
||||||
|
g2.SetStarter(nopStarter{})
|
||||||
|
g2.SetUndoReachable(func(string, string) bool { return true })
|
||||||
|
g2.Recover()
|
||||||
|
if len(poured.stacks) != 0 {
|
||||||
|
t.Fatalf("a later controller start poured the old copy back over the app: %v", poured.stacks)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type recordingPutBacker struct{ stacks []string }
|
||||||
|
|
||||||
|
func (p *recordingPutBacker) PutBackInterruptedRestore(stack, _ string) error {
|
||||||
|
p.stacks = append(p.stacks, stack)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type nopStarter struct{}
|
||||||
|
|
||||||
|
func (nopStarter) StartStack(string) error { return nil }
|
||||||
|
|
||||||
|
// The hold reporter's next tick tells the hub the hold is gone (it reads the same settings record; nothing cached).
|
||||||
|
func TestD64_TheHoldReporterTellsTheHubAfterTheClear(t *testing.T) {
|
||||||
|
r := newD64Rig(t)
|
||||||
|
r.hold(t, settings.RestoreHold{Stack: "kimai", Reason: settings.HoldReasonUpdateFailed})
|
||||||
|
var events []string
|
||||||
|
rep := holdreport.New(r.sett, func(et, _, _ string, _ interface{}) { events = append(events, et) }, r.logger)
|
||||||
|
rep.Tick(timeAt(0))
|
||||||
|
o := r.actions()
|
||||||
|
o.Reconcile([]report.OperatorAction{{ID: 1, Action: report.OpClearHold, Arg: "kimai"}})
|
||||||
|
rep.Tick(timeAt(60))
|
||||||
|
if strings.Join(events, ",") != holdreport.EventHeld+","+holdreport.EventCleared {
|
||||||
|
t.Fatalf("events %v — want app_held then app_hold_cleared", events)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// „Not reachable from outside": the channel is a unix socket (no TCP anywhere in the file), 0600 in a 0700 directory
|
||||||
|
// — even when the directory existed with a looser mode — and main opens it once, under the data dir.
|
||||||
|
func TestHoldCtl_NotReachableFromOutside(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
if err := os.MkdirAll(filepath.Join(dir, holdCtlDir), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ln, err := listenHoldCtl(holdCtlPath(dir), func(string, string) (string, error) { return "", nil }, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer ln.Close()
|
||||||
|
if n := ln.Addr().Network(); n != "unix" {
|
||||||
|
t.Fatalf("the channel listens on %q, want unix", n)
|
||||||
|
}
|
||||||
|
fi, err := os.Lstat(holdCtlPath(dir))
|
||||||
|
if err != nil || fi.Mode()&os.ModeSocket == 0 || fi.Mode().Perm() != 0o600 {
|
||||||
|
t.Fatalf("socket mode %v (err %v), want a socket with 0600", fi.Mode(), err)
|
||||||
|
}
|
||||||
|
di, _ := os.Stat(filepath.Join(dir, holdCtlDir))
|
||||||
|
if di.Mode().Perm() != 0o700 {
|
||||||
|
t.Fatalf("socket dir mode %v, want 0700", di.Mode().Perm())
|
||||||
|
}
|
||||||
|
|
||||||
|
// No TCP and no HTTP in the channel's file: every net.Listen/Dial names "unix".
|
||||||
|
f, err := parser.ParseFile(token.NewFileSet(), "holdclear.go", nil, parser.ImportsOnly)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, im := range f.Imports {
|
||||||
|
if p, _ := strconv.Unquote(im.Path.Value); strings.HasPrefix(p, "net/http") {
|
||||||
|
t.Fatalf("holdclear.go imports %s — the channel must not be HTTP", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
full, err := parser.ParseFile(token.NewFileSet(), "holdclear.go", nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
nets := 0
|
||||||
|
ast.Inspect(full, func(n ast.Node) bool {
|
||||||
|
call, ok := n.(*ast.CallExpr)
|
||||||
|
if !ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||||
|
if !ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if x, ok := sel.X.(*ast.Ident); ok && x.Name == "net" && len(call.Args) > 0 {
|
||||||
|
nets++
|
||||||
|
if lit, ok := call.Args[0].(*ast.BasicLit); !ok || lit.Value != `"unix"` {
|
||||||
|
t.Errorf("net.%s is called with a network other than \"unix\"", sel.Sel.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if nets < 2 {
|
||||||
|
t.Fatalf("expected the listen and the dial in holdclear.go, found %d net calls", nets)
|
||||||
|
}
|
||||||
|
|
||||||
|
// main opens it exactly once, at holdCtlPath(cfg.Paths.DataDir).
|
||||||
|
mf, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
opened := 0
|
||||||
|
ast.Inspect(mf, func(n ast.Node) bool {
|
||||||
|
call, ok := n.(*ast.CallExpr)
|
||||||
|
if !ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if id, ok := call.Fun.(*ast.Ident); ok && id.Name == "listenHoldCtl" {
|
||||||
|
opened++
|
||||||
|
arg, ok := call.Args[0].(*ast.CallExpr)
|
||||||
|
if fn, ok2 := arg.Fun.(*ast.Ident); !ok || !ok2 || fn.Name != "holdCtlPath" {
|
||||||
|
t.Error("main must open the channel at holdCtlPath(<data dir>)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if opened != 1 {
|
||||||
|
t.Fatalf("main.go opens the channel %d time(s), want 1", opened)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The socket answers only its one request; anything else is refused and calls nothing.
|
||||||
|
func TestHoldCtl_UnknownRequestIsRefused(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
called := 0
|
||||||
|
ln, err := listenHoldCtl(holdCtlPath(dir), func(string, string) (string, error) { called++; return "x", nil }, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer ln.Close()
|
||||||
|
conn, err := net.Dial("unix", holdCtlPath(dir))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
if _, err := conn.Write([]byte(`{"op":"set_hold","stack":"x"}` + "\n")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var resp holdCtlResponse
|
||||||
|
if err := json.NewDecoder(conn).Decode(&resp); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if resp.Outcome != report.OutcomeRefused || called != 0 {
|
||||||
|
t.Fatalf("response %+v, calls %d — want refused and nothing called", resp, called)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Something at the socket's path that is NOT a socket is refused, never removed.
|
||||||
|
func TestHoldCtl_ANonSocketFileIsNotReplaced(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
p := holdCtlPath(dir)
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(p, []byte("keep me"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := listenHoldCtl(p, func(string, string) (string, error) { return "", nil }, nil); err == nil {
|
||||||
|
t.Fatal("a regular file at the socket path must be refused")
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(p); string(b) != "keep me" {
|
||||||
|
t.Fatal("the file at the socket path was changed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// main wires every piece once (the seam-built-but-never-wired trap): the clear door into the operator actions, the
|
||||||
|
// R-1340 text into the hold notification, the R-1341 gate into the OOM loop, and the box command.
|
||||||
|
func TestD64_MainWiresTheNewPieces(t *testing.T) {
|
||||||
|
f, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
found := map[string]int{}
|
||||||
|
var opArgs []ast.Expr
|
||||||
|
ast.Inspect(f, func(n ast.Node) bool {
|
||||||
|
call, ok := n.(*ast.CallExpr)
|
||||||
|
if !ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
switch fn := call.Fun.(type) {
|
||||||
|
case *ast.SelectorExpr:
|
||||||
|
if x, ok := fn.X.(*ast.Ident); ok {
|
||||||
|
found[x.Name+"."+fn.Sel.Name]++
|
||||||
|
}
|
||||||
|
case *ast.Ident:
|
||||||
|
found[fn.Name]++
|
||||||
|
if fn.Name == "operatorActionHandlers" {
|
||||||
|
opArgs = call.Args
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
for _, want := range []string{"heldStoppedOperatorText", "heldHoldFromNotify", "oomLog.fresh", "clearRestoreHoldCLI", "listenHoldCtl", "clearHoldNow"} {
|
||||||
|
if found[want] != 1 {
|
||||||
|
t.Errorf("main.go calls %s %d time(s), want exactly 1", want, found[want])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(opArgs) < 3 {
|
||||||
|
t.Fatal("operatorActionHandlers call not found")
|
||||||
|
}
|
||||||
|
if id, ok := opArgs[2].(*ast.Ident); !ok || id.Name != "holdDeps" {
|
||||||
|
t.Error("main must hand holdDeps (the running controller's clear door) to operatorActionHandlers")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func timeAt(sec int) time.Time { return time.Date(2026, 10, 29, 12, 0, sec, 0, time.UTC) }
|
||||||
|
|
||||||
|
// No controller runs: the box command's own clear drops a waiting put-back from the app-stop marker too (the same
|
||||||
|
// door), so the next start with the drive bound pours nothing back.
|
||||||
|
// RED-PROOF (2026-10-29): with the fallback clearing through settings.ClearRestoreHold alone (its first shape in
|
||||||
|
// 5b3b541), this fails on „a later controller start poured the old copy back".
|
||||||
|
func TestR1343_TheFallbackDropsAWaitingPutBackToo(t *testing.T) {
|
||||||
|
r := newD64Rig(t)
|
||||||
|
undo := filepath.Join(r.dir, "drive", "felhom-data", "backups", "restore-undo", "immich", "20261029T080000Z")
|
||||||
|
if err := os.MkdirAll(undo, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.guard.Begin("unit-restore:immich", backup.ReasonUnitRestore, []string{"immich"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.guard.SetUndo("immich", undo); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r.hold(t, settings.RestoreHold{Stack: "immich", Reason: settings.HoldReasonPutBackPending, SafetyDump: undo})
|
||||||
|
var out, errb bytes.Buffer
|
||||||
|
if code := clearRestoreHoldCLI(r.dir, "immich", &out, &errb); code != 0 {
|
||||||
|
t.Fatalf("exit %d, stderr %q", code, errb.String())
|
||||||
|
}
|
||||||
|
if !strings.Contains(out.String(), "waiting put-back is dropped") {
|
||||||
|
t.Errorf("output must say the put-back is dropped:\n%s", out.String())
|
||||||
|
}
|
||||||
|
sett2, err := settings.Load(filepath.Join(r.dir, "settings.json"), log.New(io.Discard, "", 0))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
poured := &recordingPutBacker{}
|
||||||
|
g2 := backup.NewAppStopGuard(filepath.Join(r.dir, "appstop-state.json"), r.logger)
|
||||||
|
g2.SetHolds(sett2)
|
||||||
|
g2.SetPutBacker(poured)
|
||||||
|
g2.SetStarter(nopStarter{})
|
||||||
|
g2.SetUndoReachable(func(string, string) bool { return true })
|
||||||
|
g2.Recover()
|
||||||
|
if len(poured.stacks) != 0 {
|
||||||
|
t.Fatalf("a later controller start poured the old copy back over the app: %v", poured.stacks)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(undo); err != nil {
|
||||||
|
t.Fatal("the copy must stay on disk")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
// holdCtlPeerAllowed (R-1343) admits a peer on the hold socket only when its uid equals this process's (SO_PEERCRED).
|
||||||
|
// The socket's 0600 mode in a 0700 directory already says so; this is the second lock on the same door.
|
||||||
|
func holdCtlPeerAllowed(conn net.Conn) (bool, string) {
|
||||||
|
uc, ok := conn.(*net.UnixConn)
|
||||||
|
if !ok {
|
||||||
|
return false, "not a unix-socket peer"
|
||||||
|
}
|
||||||
|
raw, err := uc.SyscallConn()
|
||||||
|
if err != nil {
|
||||||
|
return false, "the peer's identity could not be read"
|
||||||
|
}
|
||||||
|
var cred *syscall.Ucred
|
||||||
|
var cerr error
|
||||||
|
if err := raw.Control(func(fd uintptr) {
|
||||||
|
cred, cerr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
|
||||||
|
}); err != nil || cerr != nil || cred == nil {
|
||||||
|
return false, "the peer's identity could not be read"
|
||||||
|
}
|
||||||
|
if int(cred.Uid) != os.Geteuid() {
|
||||||
|
return false, fmt.Sprintf("the peer's uid %d is not this controller's", cred.Uid)
|
||||||
|
}
|
||||||
|
return true, ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
//go:build !linux
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import "net"
|
||||||
|
|
||||||
|
// holdCtlPeerAllowed: the peer check needs SO_PEERCRED (Linux, where the controller runs). Elsewhere the socket's
|
||||||
|
// 0600 mode in a 0700 directory is the only lock.
|
||||||
|
func holdCtlPeerAllowed(conn net.Conn) (bool, string) {
|
||||||
|
if _, ok := conn.(*net.UnixConn); !ok {
|
||||||
|
return false, "not a unix-socket peer"
|
||||||
|
}
|
||||||
|
return true, ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ── R-1340: the operator's „HELD STOPPED" mail names the hold's REAL cause ────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// Until 2026-10-29 the restore-hold mail told one story for every restore_mixed hold — R-893 option C's „its off-site
|
||||||
|
// database restore failed. The database was rolled back …, but its files and named volumes are the snapshot's" —
|
||||||
|
// written when option C was the only mixed hold. Measured on Tester 1 (D63's H5 proof): Radicale, which has no
|
||||||
|
// database, whose put-back stopped at „the app could not be stopped" with nothing moved, got exactly that text.
|
||||||
|
// Support read a wrong account of the box.
|
||||||
|
//
|
||||||
|
// The text is now built from the HOLD RECORD the writer persisted just before the mail (its reason and the R-1340
|
||||||
|
// fields: which restore, which branch, which step failed, whether the failure was a database replay, where the copy
|
||||||
|
// is kept). It never says „database" unless the restore's failure WAS a database replay, and never „off-site" for a
|
||||||
|
// restore from the app's own backup. One sentence per reason; pinned by TestR1340_* (holdmail_test.go).
|
||||||
|
|
||||||
|
// heldStoppedOperatorText is the operator mail for a held app: the message, its leg (the hub reads the leg, so the
|
||||||
|
// two existing ones are kept: restore-hold for a restore hold, restore-hold-mixed for a mixed one) and a short reason.
|
||||||
|
func heldStoppedOperatorText(h settings.RestoreHold) (msg, leg, reason string) {
|
||||||
|
stack := h.Stack
|
||||||
|
const tail = " The app will not start from any path until the hold is cleared (the hub's Clear hold button, or on the box: " + holdClearCommandHint + ")."
|
||||||
|
kind := restoreKindPhrase(h.RestoreKind)
|
||||||
|
switch h.Reason {
|
||||||
|
case settings.HoldReasonUnhealthyStop:
|
||||||
|
what := "a crash loop"
|
||||||
|
if h.UnhealthyKind == "oom_storm" {
|
||||||
|
what = "an out-of-memory storm"
|
||||||
|
}
|
||||||
|
trip := ""
|
||||||
|
if h.Trip >= 2 {
|
||||||
|
trip = fmt.Sprintf(" This is stop %d within 24 hours.", h.Trip)
|
||||||
|
}
|
||||||
|
msg = fmt.Sprintf("App %q is HELD STOPPED: the box stopped it for %s at %s.%s No restore or update was involved and no data was touched. "+
|
||||||
|
"The household's Start gives it one more try; clearing the hold lifts it too.", stack, what, h.At, trip)
|
||||||
|
return msg, "unhealthy-stop", "stopped for " + what
|
||||||
|
case settings.HoldReasonUpdateFailed:
|
||||||
|
undo := ""
|
||||||
|
switch h.UndoState {
|
||||||
|
case "untouched":
|
||||||
|
undo = " The automatic undo failed; the data was not touched."
|
||||||
|
case "half":
|
||||||
|
undo = " The automatic undo failed half-way; the data may be partly the new version's."
|
||||||
|
case "not_started":
|
||||||
|
undo = " The automatic undo did not start."
|
||||||
|
}
|
||||||
|
copyLine := " Restoring it from its backup starts it."
|
||||||
|
if h.NoWholeCopy {
|
||||||
|
copyLine = " No copy on this box brings it back whole — it needs support."
|
||||||
|
} else if h.CopyDate != "" {
|
||||||
|
copyLine = fmt.Sprintf(" Restoring it from its backup (tier %d, %s) starts it.", h.CopyTier, h.CopyDate)
|
||||||
|
}
|
||||||
|
msg = fmt.Sprintf("App %q is HELD STOPPED: its update at %s did not come up healthy.%s%s", stack, h.At, undo, copyLine) + tail
|
||||||
|
return msg, "update-hold", "update failed"
|
||||||
|
case settings.HoldReasonPutBackPending:
|
||||||
|
msg = fmt.Sprintf("App %q is HELD STOPPED: a restore was cut after its copy of the live data was taken, and that copy (%s) is on a drive that is not bound. "+
|
||||||
|
"The copy is poured back and the app started when the drive is bound. Clearing the hold DROPS that put-back; the copy stays on disk.", stack, orNone(h.SafetyDump))
|
||||||
|
return msg, "putback-pending", "put-back waits for its drive"
|
||||||
|
case settings.HoldReasonRestoreMixed:
|
||||||
|
return mixedHoldText(h, kind, tail)
|
||||||
|
default: // HoldReasonRestoreFailed: a database replay failed AND its rollback failed (holdAppAfterFailedRollback)
|
||||||
|
what := "its " + kind + " failed"
|
||||||
|
if h.DBReplay || h.RestoreKind == "" { // every restore hold before R-1340 was written by the database branch
|
||||||
|
what = "its " + kind + " failed at the database replay AND the rollback to the pre-restore database copy also failed — the database may be half-written"
|
||||||
|
}
|
||||||
|
msg = fmt.Sprintf("App %q is HELD STOPPED: %s.", stack, what) + tail +
|
||||||
|
fmt.Sprintf(" Replay error: %s. Rollback error: %s", orNone(h.ReplayError), orNone(h.RollbackErr))
|
||||||
|
reason = h.RollbackErr
|
||||||
|
if reason == "" {
|
||||||
|
reason = "rollback failed"
|
||||||
|
}
|
||||||
|
return msg, "restore-hold", reason
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// heldRunKind names the run in the mail's subject. A hold that does not say which restore wrote it is an off-site one, the
|
||||||
|
// pre-R-1340 rule, EXCEPT an interrupted put-back: its record names no kind, and its restore may be either, so „restore" (R-1348,
|
||||||
|
// seen live 2026-11-03: a local restore's mail read „offsite-reconstitute"). Pinned by TestR1348_HeldRunKind.
|
||||||
|
func heldRunKind(h settings.RestoreHold) string {
|
||||||
|
if h.RestoreKind == settings.RestoreKindLocal || h.MixedCause == settings.MixedCauseInterruptedPutBack {
|
||||||
|
return "restore"
|
||||||
|
}
|
||||||
|
return "offsite-reconstitute"
|
||||||
|
}
|
||||||
|
|
||||||
|
func mixedHoldText(h settings.RestoreHold, kind, tail string) (msg, leg, reason string) {
|
||||||
|
stack := h.Stack
|
||||||
|
leg = "restore-hold-mixed"
|
||||||
|
failedAt := ""
|
||||||
|
if h.DBReplay {
|
||||||
|
failedAt = " at the database replay"
|
||||||
|
}
|
||||||
|
copyLine := " There is no copy of the live volumes."
|
||||||
|
if h.SafetyDump != "" {
|
||||||
|
copyLine = " The copy of the live data is kept at " + h.SafetyDump + "."
|
||||||
|
}
|
||||||
|
switch h.MixedCause {
|
||||||
|
case settings.MixedCauseDefinitionWrite:
|
||||||
|
msg = fmt.Sprintf("App %q is HELD STOPPED for support: its %s failed while writing the backup's app definition, before any data was touched, "+
|
||||||
|
"and %s. The app's data is the live data; the definition on disk may be the backup's.", stack, kind, orNone(h.FailedStep)) + tail +
|
||||||
|
" Error: " + orNone(h.ReplayError)
|
||||||
|
return msg, leg, "definition write failed; writing the live definition back failed too"
|
||||||
|
case settings.MixedCausePutBack:
|
||||||
|
msg = fmt.Sprintf("App %q is HELD STOPPED for support: its %s failed%s, and putting the live data back FAILED — %s. "+
|
||||||
|
"The app may be on a mix of the backup's and the live data.%s", stack, kind, failedAt, orNone(h.FailedStep), copyLine) + tail +
|
||||||
|
" Restore error: " + orNone(h.ReplayError)
|
||||||
|
return msg, leg, "put-back failed: " + firstClause(h.FailedStep)
|
||||||
|
case settings.MixedCauseInterruptedPutBack:
|
||||||
|
msg = fmt.Sprintf("App %q is HELD STOPPED for support: a restore cut by a stop could not be put back at the next start — %s. "+
|
||||||
|
"The app may be on a mix of the backup's and the live data.%s", stack, orNone(h.FailedStep), copyLine) + tail
|
||||||
|
return msg, leg, "interrupted restore: put-back failed"
|
||||||
|
}
|
||||||
|
// A mixed hold written before R-1340 carries no cause: name only what the record says, and assume nothing.
|
||||||
|
msg = fmt.Sprintf("App %q is HELD STOPPED for support: a restore stopped half-way (set %s); the app may be on a mix of the backup's and the live data. "+
|
||||||
|
"The hold record says: %s.", stack, h.At, orNone(h.ReplayError)) + tail
|
||||||
|
return msg, leg, "restore stopped half-way"
|
||||||
|
}
|
||||||
|
|
||||||
|
func restoreKindPhrase(k string) string {
|
||||||
|
switch k {
|
||||||
|
case settings.RestoreKindLocal:
|
||||||
|
return "restore from its own backup"
|
||||||
|
case settings.RestoreKindOffsite:
|
||||||
|
return "off-site restore"
|
||||||
|
}
|
||||||
|
return "restore"
|
||||||
|
}
|
||||||
|
|
||||||
|
func orNone(s string) string {
|
||||||
|
if strings.TrimSpace(s) == "" {
|
||||||
|
return "(none recorded)"
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// firstClause is a step's text up to its error (the short reason field).
|
||||||
|
func firstClause(s string) string {
|
||||||
|
if i := strings.Index(s, ":"); i > 0 {
|
||||||
|
return s[:i]
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// heldHoldFromNotify is the hold the notification describes: the record the writer persisted just before it, or —
|
||||||
|
// when that write failed — one rebuilt from the errors handed over (the pre-R-1340 rule: no rollback error = mixed).
|
||||||
|
func heldHoldFromNotify(get func(string) (settings.RestoreHold, bool), stack string, replayErr, rollbackErr error) settings.RestoreHold {
|
||||||
|
if get != nil {
|
||||||
|
if h, ok := get(stack); ok && (h.Reason == settings.HoldReasonRestoreFailed || h.Reason == settings.HoldReasonRestoreMixed) {
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h := settings.RestoreHold{Stack: stack, Reason: settings.HoldReasonRestoreMixed}
|
||||||
|
if rollbackErr != nil {
|
||||||
|
h.Reason, h.RollbackErr = settings.HoldReasonRestoreFailed, rollbackErr.Error()
|
||||||
|
}
|
||||||
|
if replayErr != nil {
|
||||||
|
h.ReplayError = replayErr.Error()
|
||||||
|
}
|
||||||
|
return h
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1340: the operator's „HELD STOPPED" mail names the hold's real cause — one test per reason. Each asserts the words
|
||||||
|
// that MUST be there and the words that must NOT (the option-C database story was the bug).
|
||||||
|
//
|
||||||
|
// RED-PROOF (2026-10-29): with mixedHoldText's body replaced by the pre-R-1340 sentence („its off-site database restore
|
||||||
|
// failed. The database was rolled back to the pre-restore copy and the live definition written back, but its files
|
||||||
|
// and named volumes are the snapshot's"), TestR1340_PutBackWithoutADatabase, _DefinitionWrite, _LocalRestore and
|
||||||
|
// _InterruptedPutBack fail on „database" / „off-site" being present and their own step missing.
|
||||||
|
|
||||||
|
const optionCStory = "files and named volumes are the snapshot's"
|
||||||
|
|
||||||
|
func mustHave(t *testing.T, msg string, want ...string) {
|
||||||
|
t.Helper()
|
||||||
|
for _, w := range want {
|
||||||
|
if !strings.Contains(msg, w) {
|
||||||
|
t.Errorf("the mail must say %q:\n%s", w, msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustNotHave(t *testing.T, msg string, bad ...string) {
|
||||||
|
t.Helper()
|
||||||
|
for _, b := range bad {
|
||||||
|
if strings.Contains(strings.ToLower(msg), strings.ToLower(b)) {
|
||||||
|
t.Errorf("the mail must NOT say %q:\n%s", b, msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestR1340_UnhealthyStop(t *testing.T) {
|
||||||
|
msg, leg, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "romm", At: "2026-10-29T08:00:00Z", Reason: settings.HoldReasonUnhealthyStop, UnhealthyKind: "crash_loop"})
|
||||||
|
mustHave(t, msg, `"romm"`, "crash loop", "no data was touched", "Start gives it one more try")
|
||||||
|
mustNotHave(t, msg, "database", "restore failed", optionCStory)
|
||||||
|
if leg != "unhealthy-stop" {
|
||||||
|
t.Errorf("leg %q", leg)
|
||||||
|
}
|
||||||
|
oom, _, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "romm", Reason: settings.HoldReasonUnhealthyStop, UnhealthyKind: "oom_storm", Trip: 2})
|
||||||
|
mustHave(t, oom, "out-of-memory storm", "stop 2 within 24 hours")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestR1340_UpdateFailed(t *testing.T) {
|
||||||
|
msg, leg, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "kimai", At: "2026-10-29T03:10:00Z", Reason: settings.HoldReasonUpdateFailed,
|
||||||
|
UndoState: "half", CopyTier: 1, CopyDate: "2026-10-29T02:00:00Z"})
|
||||||
|
mustHave(t, msg, "update at 2026-10-29T03:10:00Z did not come up healthy", "undo failed half-way", "tier 1, 2026-10-29T02:00:00Z", "--clear-restore-hold")
|
||||||
|
mustNotHave(t, msg, "database", optionCStory)
|
||||||
|
if leg != "update-hold" {
|
||||||
|
t.Errorf("leg %q", leg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestR1340_RestoreFailedWithADatabase(t *testing.T) {
|
||||||
|
msg, leg, reason := heldStoppedOperatorText(settings.RestoreHold{Stack: "paperless", Reason: settings.HoldReasonRestoreFailed, RestoreKind: settings.RestoreKindOffsite,
|
||||||
|
DBReplay: true, ReplayError: "ERROR: relation exists", RollbackErr: "psql: connection refused"})
|
||||||
|
mustHave(t, msg, "off-site restore failed at the database replay", "rollback to the pre-restore database copy also failed", "ERROR: relation exists", "psql: connection refused")
|
||||||
|
mustNotHave(t, msg, optionCStory)
|
||||||
|
if leg != "restore-hold" || reason != "psql: connection refused" {
|
||||||
|
t.Errorf("leg %q reason %q", leg, reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The measured case: Radicale has no database; the volume could not be removed and the put-back's stop failed.
|
||||||
|
func TestR1340_PutBackWithoutADatabase(t *testing.T) {
|
||||||
|
msg, leg, reason := heldStoppedOperatorText(settings.RestoreHold{Stack: "radicale", Reason: settings.HoldReasonRestoreMixed, RestoreKind: settings.RestoreKindOffsite,
|
||||||
|
MixedCause: settings.MixedCausePutBack, FailedStep: "stopping the app before the put-back failed, so nothing was put back: compose down: timeout",
|
||||||
|
ReplayError: "volume rm -f radicale_data: volume is in use", SafetyDump: "/mnt/hdd/felhom-data/backups/restore-undo/radicale/20261029T081800Z"})
|
||||||
|
mustHave(t, msg, `"radicale"`, "off-site restore failed, and putting the live data back FAILED", "stopping the app before the put-back failed",
|
||||||
|
"compose down: timeout", "kept at /mnt/hdd/felhom-data/backups/restore-undo/radicale/20261029T081800Z", "volume is in use")
|
||||||
|
mustNotHave(t, msg, "database", "rolled back", optionCStory)
|
||||||
|
if leg != "restore-hold-mixed" || reason != "put-back failed: stopping the app before the put-back failed, so nothing was put back" {
|
||||||
|
t.Errorf("leg %q reason %q", leg, reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestR1340_PutBackAfterADatabaseReplay(t *testing.T) {
|
||||||
|
msg, _, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "immich", Reason: settings.HoldReasonRestoreMixed, RestoreKind: settings.RestoreKindOffsite,
|
||||||
|
MixedCause: settings.MixedCausePutBack, DBReplay: true, FailedStep: "putting the live volumes back failed: tar xf failed"})
|
||||||
|
mustHave(t, msg, "failed at the database replay", "putting the live volumes back failed: tar xf failed", "There is no copy of the live volumes")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestR1340_DefinitionWrite(t *testing.T) {
|
||||||
|
msg, _, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "gokapi", Reason: settings.HoldReasonRestoreMixed, RestoreKind: settings.RestoreKindOffsite,
|
||||||
|
MixedCause: settings.MixedCauseDefinitionWrite, FailedStep: "writing the live app definition back failed: app.yaml write failed", ReplayError: "app.yaml write failed"})
|
||||||
|
mustHave(t, msg, "while writing the backup's app definition, before any data was touched", "writing the live app definition back failed", "data is the live data")
|
||||||
|
mustNotHave(t, msg, "database", optionCStory)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestR1340_LocalRestore(t *testing.T) {
|
||||||
|
msg, _, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "app", Reason: settings.HoldReasonRestoreMixed, RestoreKind: settings.RestoreKindLocal,
|
||||||
|
MixedCause: settings.MixedCausePutBack, FailedStep: "putting the live volumes back failed: tar xf failed", SafetyDump: "/srv/undo/app/1"})
|
||||||
|
mustHave(t, msg, "restore from its own backup failed", "putting the live volumes back failed")
|
||||||
|
mustNotHave(t, msg, "off-site", "database", optionCStory)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestR1340_PutBackPending(t *testing.T) {
|
||||||
|
msg, leg, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "immich", Reason: settings.HoldReasonPutBackPending, SafetyDump: "/mnt/hdd/undo/immich/1"})
|
||||||
|
mustHave(t, msg, "copy (/mnt/hdd/undo/immich/1) is on a drive that is not bound", "poured back and the app started when the drive is bound", "DROPS that put-back")
|
||||||
|
mustNotHave(t, msg, "database", optionCStory)
|
||||||
|
if leg != "putback-pending" {
|
||||||
|
t.Errorf("leg %q", leg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestR1340_InterruptedPutBack(t *testing.T) {
|
||||||
|
msg, _, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "immich", Reason: settings.HoldReasonRestoreMixed, MixedCause: settings.MixedCauseInterruptedPutBack,
|
||||||
|
FailedStep: "putting the interrupted restore's copy back failed: compose down: timeout", SafetyDump: "/mnt/hdd/undo/immich/1"})
|
||||||
|
mustHave(t, msg, "cut by a stop could not be put back", "compose down: timeout", "kept at /mnt/hdd/undo/immich/1")
|
||||||
|
mustNotHave(t, msg, "database", "off-site", optionCStory)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A mixed hold written before R-1340 names only what its record says.
|
||||||
|
func TestR1340_LegacyMixedHoldAssumesNothing(t *testing.T) {
|
||||||
|
msg, _, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "x", At: "2026-10-01T00:00:00Z", Reason: settings.HoldReasonRestoreMixed, ReplayError: "boom"})
|
||||||
|
mustHave(t, msg, "stopped half-way", "The hold record says: boom")
|
||||||
|
mustNotHave(t, msg, "database", optionCStory)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The notification reads the hold the writer persisted; when that write failed, it rebuilds one from the errors.
|
||||||
|
func TestR1340_NotifyReadsTheHoldRecord(t *testing.T) {
|
||||||
|
rec := settings.RestoreHold{Stack: "radicale", Reason: settings.HoldReasonRestoreMixed, MixedCause: settings.MixedCausePutBack, FailedStep: "x"}
|
||||||
|
get := func(s string) (settings.RestoreHold, bool) { return rec, s == "radicale" }
|
||||||
|
if h := heldHoldFromNotify(get, "radicale", errors.New("e"), nil); h.MixedCause != settings.MixedCausePutBack {
|
||||||
|
t.Fatalf("the persisted record was not used: %+v", h)
|
||||||
|
}
|
||||||
|
h := heldHoldFromNotify(get, "other", errors.New("replay"), errors.New("rollback"))
|
||||||
|
if h.Reason != settings.HoldReasonRestoreFailed || h.RollbackErr != "rollback" || h.ReplayError != "replay" {
|
||||||
|
t.Fatalf("fallback hold %+v", h)
|
||||||
|
}
|
||||||
|
if h := heldHoldFromNotify(nil, "other", errors.New("replay"), nil); h.Reason != settings.HoldReasonRestoreMixed {
|
||||||
|
t.Fatalf("no rollback error = mixed, got %+v", h)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/agentapi"
|
||||||
|
)
|
||||||
|
|
||||||
|
// hostOOMSource (R-528) is the 30-s dead-app scan's host-side OOM counter: one agent call per scan (5 s cap). An agent
|
||||||
|
// without the route (404) is not asked again for hostOOMRetryAfter, and said once; any other failure is a nil answer
|
||||||
|
// for this scan only (Docker's flag still works). Pinned by TestR528_HostOOMSource*.
|
||||||
|
const hostOOMRetryAfter = 10 * time.Minute
|
||||||
|
|
||||||
|
func hostOOMSource(ask func(context.Context) (agentapi.GuestOOMKillsState, error), logger *log.Logger, now func() time.Time) func() map[string]int64 {
|
||||||
|
var mu sync.Mutex
|
||||||
|
var until time.Time
|
||||||
|
said := false
|
||||||
|
return func() map[string]int64 {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
if now().Before(until) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
st, err := ask(ctx)
|
||||||
|
if err != nil {
|
||||||
|
var se *agentapi.StatusError
|
||||||
|
if errors.As(err, &se) && se.Code == http.StatusNotFound {
|
||||||
|
until = now().Add(hostOOMRetryAfter)
|
||||||
|
if !said {
|
||||||
|
logger.Printf("[INFO] [deadapp] the agent has no OOM counter route (R-528) — Docker's OOM flag only; asked again in %s", hostOOMRetryAfter)
|
||||||
|
said = true
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
logger.Printf("[WARN] [deadapp] the host OOM counter could not be read: %v — Docker's OOM flag only for this scan", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !st.Available {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return st.Containers
|
||||||
|
}
|
||||||
|
}
|
||||||
+683
-278
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,43 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ── R-1341: the OOM line is logged once per NEW kill ──────────────────────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// ScanOOMKilled reports a container for as long as it lives after a kill (Docker's OOMKilled flag is sticky, and the
|
||||||
|
// kernel's kill counter never goes down), so the 30-s dead-app scan logged „[WARN] [deadapp] … was OOM-killed" about
|
||||||
|
// 2 880 times a day per container — measured 2026-10-29 on Tester 1 — while the notifier's cooldown kept the event to
|
||||||
|
// one. The line now goes out when the kill is NEW: the key is (container, its start time, the kill count), and a line
|
||||||
|
// is logged only when a container's key changes — a second scan of the same kill logs nothing, a new kill (the count
|
||||||
|
// went up) or a restarted container (a new start time) logs again. The event call is unchanged (every scan, the
|
||||||
|
// notifier decides). Pinned by TestR1341_*.
|
||||||
|
|
||||||
|
// oomLogGate remembers the last logged key per container. Not safe for concurrent use: the dead-app job runs serially.
|
||||||
|
type oomLogGate struct {
|
||||||
|
last map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
func oomLogKey(o stacks.OOMContainer) string {
|
||||||
|
return o.StartedAt + "|" + strconv.FormatInt(o.Kills, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
// fresh returns the containers whose kill is new since the last scan, and remembers this scan's keys. A container
|
||||||
|
// absent from this scan is forgotten (it was removed or restarted clean), which also bounds the memory.
|
||||||
|
func (g *oomLogGate) fresh(ooms []stacks.OOMContainer) []stacks.OOMContainer {
|
||||||
|
next := make(map[string]string, len(ooms))
|
||||||
|
var out []stacks.OOMContainer
|
||||||
|
for _, o := range ooms {
|
||||||
|
k := oomLogKey(o)
|
||||||
|
next[o.Container] = k
|
||||||
|
if prev, ok := g.last[o.Container]; ok && prev == k {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, o)
|
||||||
|
}
|
||||||
|
g.last = next
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1341: the „[WARN] [deadapp] … was OOM-killed" line goes out once per NEW kill, not every 30-s scan.
|
||||||
|
//
|
||||||
|
// RED-PROOF (2026-10-29): with oomLogGate.fresh returning its input unchanged (the pre-R-1341 loop logged every
|
||||||
|
// container every scan), TestR1341_ASecondScanOfTheSameKillLogsNothing fails on „logged 1 line(s), want 0".
|
||||||
|
|
||||||
|
func oom(container, started string, kills int64) stacks.OOMContainer {
|
||||||
|
return stacks.OOMContainer{Stack: "gokapi", Container: container, StartedAt: started, Kills: kills}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestR1341_ASecondScanOfTheSameKillLogsNothing(t *testing.T) {
|
||||||
|
g := &oomLogGate{}
|
||||||
|
scan := []stacks.OOMContainer{oom("gokapi", "2026-10-29T09:02:00Z", 1)}
|
||||||
|
if got := g.fresh(scan); len(got) != 1 {
|
||||||
|
t.Fatalf("the first sighting must log, logged %d line(s)", len(got))
|
||||||
|
}
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
if got := g.fresh(scan); len(got) != 0 {
|
||||||
|
t.Fatalf("scan %d of the same kill logged %d line(s), want 0", i+2, len(got))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestR1341_ANewKillLogsAgain(t *testing.T) {
|
||||||
|
g := &oomLogGate{}
|
||||||
|
g.fresh([]stacks.OOMContainer{oom("gokapi", "2026-10-29T09:02:00Z", 1)})
|
||||||
|
got := g.fresh([]stacks.OOMContainer{oom("gokapi", "2026-10-29T09:02:00Z", 2)})
|
||||||
|
if len(got) != 1 || got[0].Kills != 2 {
|
||||||
|
t.Fatalf("a new kill (count 1→2) must log once, got %+v", got)
|
||||||
|
}
|
||||||
|
if got := g.fresh([]stacks.OOMContainer{oom("gokapi", "2026-10-29T09:02:00Z", 2)}); len(got) != 0 {
|
||||||
|
t.Fatalf("the same new kill must not log twice, got %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestR1341_ARestartedContainerLogsAgain(t *testing.T) {
|
||||||
|
g := &oomLogGate{}
|
||||||
|
g.fresh([]stacks.OOMContainer{oom("gokapi", "2026-10-29T09:02:00Z", 1)})
|
||||||
|
if got := g.fresh([]stacks.OOMContainer{oom("gokapi", "2026-10-29T09:30:00Z", 1)}); len(got) != 1 {
|
||||||
|
t.Fatalf("a restarted container's kill must log, got %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Two containers are judged apart; one that leaves the scan is forgotten, so its return logs again.
|
||||||
|
func TestR1341_ContainersAreJudgedApart(t *testing.T) {
|
||||||
|
g := &oomLogGate{}
|
||||||
|
a, b := oom("a", "t1", 1), oom("b", "t1", 1)
|
||||||
|
if got := g.fresh([]stacks.OOMContainer{a, b}); len(got) != 2 {
|
||||||
|
t.Fatalf("first scan: %+v", got)
|
||||||
|
}
|
||||||
|
if got := g.fresh([]stacks.OOMContainer{a}); len(got) != 0 {
|
||||||
|
t.Fatalf("a seen again must not log: %+v", got)
|
||||||
|
}
|
||||||
|
if got := g.fresh([]stacks.OOMContainer{a, b}); len(got) != 1 || got[0].Container != "b" {
|
||||||
|
t.Fatalf("b came back after leaving the scan: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/report"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/scheduler"
|
||||||
|
)
|
||||||
|
|
||||||
|
// opActionReportFire holds the out-of-cycle report trigger once main has built it (func()). The
|
||||||
|
// executor is built earlier than the trigger, so it reads it through this holder.
|
||||||
|
var opActionReportFire atomic.Value
|
||||||
|
|
||||||
|
// operatorActionHandlers wires the five operator actions (R-314/R-279/R-177, `09` §3 decision 185)
|
||||||
|
// to the running process. ONE wiring site, called from main and from the wiring test, so the test
|
||||||
|
// exercises the doors production uses (the seam-built-but-never-wired trap).
|
||||||
|
//
|
||||||
|
// offsite_backup_now makes the SAME four checks as the household's „back up now"
|
||||||
|
// (offboxRunHandler) and then runs the same call, so an operator press can never do what the
|
||||||
|
// household's own press cannot.
|
||||||
|
//
|
||||||
|
// clear_hold (D64 = B) goes through clearHoldNow with hold — the same door the box command's socket uses
|
||||||
|
// (holdclear.go), so the hub's button and the box command can never differ. hold.clear nil = not available.
|
||||||
|
func operatorActionHandlers(backupMgr *backup.Manager, sched *scheduler.Scheduler, hold holdClearDeps, resultReady func(), logger *log.Logger) report.OperatorActionHandlers {
|
||||||
|
h := report.OperatorActionHandlers{ResultReady: resultReady}
|
||||||
|
if sched != nil {
|
||||||
|
h.RunJob = sched.RunNow
|
||||||
|
}
|
||||||
|
if hold.clear != nil {
|
||||||
|
h.ClearHold = func(stack string, actionID int64) (string, error) {
|
||||||
|
return clearHoldNow(hold, stack, fmt.Sprintf("the operator via the hub, action #%d", actionID))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if backupMgr == nil {
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
h.OffsiteBackupNow = func() (string, func(ctx context.Context) error) {
|
||||||
|
switch {
|
||||||
|
case !backupMgr.OffboxConfigured():
|
||||||
|
return "no off-site target is set on this box", nil
|
||||||
|
case !backupMgr.OffboxRunnable():
|
||||||
|
return "the off-site key step (escrow) is not done yet — the run is refused until it is", nil
|
||||||
|
case backupMgr.OffboxOrphaned():
|
||||||
|
return "the off-site store is orphaned (written with an older key) — a run cannot write to it", nil
|
||||||
|
case backupMgr.IsRunning():
|
||||||
|
return "a backup run is already in flight", nil
|
||||||
|
}
|
||||||
|
return "", func(ctx context.Context) error {
|
||||||
|
if logger != nil {
|
||||||
|
logger.Printf("[INFO] [opaction] off-site backup started at the operator's request")
|
||||||
|
}
|
||||||
|
err := backupMgr.RunOffboxBackupWithProgress(ctx)
|
||||||
|
if errors.Is(err, backup.ErrOffboxRunInFlight) {
|
||||||
|
return fmt.Errorf("%w: %v", report.ErrActionRefused, err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.AbandonStop = backupMgr.StopAbandon
|
||||||
|
h.AbandonExtend = func(days int) (time.Time, error) { return backupMgr.ExtendAbandon(days) }
|
||||||
|
return h
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"go/ast"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/report"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/scheduler"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// `09` §3 decision 185 (D1), the design's red test (1): a reply carrying abandon_stop during a
|
||||||
|
// countdown stops it IN THE RUNNING MANAGER — and settings.json on disk agrees. This is the reason
|
||||||
|
// the action rides the report reply instead of the CLI lever: the CLI runs a SECOND process, whose
|
||||||
|
// write the running controller can overwrite (the lost update, main.go's R-241 block).
|
||||||
|
func TestD1_AbandonStopActsOnTheRunningManagerAndDisk(t *testing.T) {
|
||||||
|
logger := log.New(io.Discard, "", 0)
|
||||||
|
dir := t.TempDir()
|
||||||
|
settingsPath := filepath.Join(dir, "settings.json")
|
||||||
|
sett, err := settings.Load(settingsPath, logger)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg := &config.Config{}
|
||||||
|
cfg.Paths.DataDir = dir
|
||||||
|
cfg.Paths.SystemDataPath = filepath.Join(dir, "sys")
|
||||||
|
mgr := backup.NewManager(cfg, sett, logger)
|
||||||
|
// No test reaches a real ssh or restic (R-488 / R-650).
|
||||||
|
mgr.SetOffboxSSH(func(context.Context, string, string, int, string, string, string) ([]byte, error) {
|
||||||
|
t.Fatal("abandon_stop must issue no remote command")
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
mgr.SetOffboxRunner(func(context.Context, []string, ...string) ([]byte, error) {
|
||||||
|
t.Fatal("abandon_stop must run no restic")
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
due := time.Now().Add(10 * 24 * time.Hour).UTC()
|
||||||
|
if err := sett.SetOffboxTarget(&settings.OffboxTarget{
|
||||||
|
Enabled: true, Host: "nas.local", Port: 22, User: "felhom", RepoPath: "/srv/repo", Schedule: "daily",
|
||||||
|
EscrowState: "escrowed",
|
||||||
|
AbandonRepoPath: "/srv/repo.orphaned-20261001",
|
||||||
|
AbandonStartedAt: time.Now().Add(-4 * 24 * time.Hour).UTC().Format(time.RFC3339),
|
||||||
|
AbandonAt: due.Format(time.RFC3339),
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !mgr.AbandonStatus().Active {
|
||||||
|
t.Fatal("fixture: a countdown must be running")
|
||||||
|
}
|
||||||
|
|
||||||
|
o := report.NewOperatorActions(context.Background(), operatorActionHandlers(mgr, nil, holdClearDeps{}, nil, logger), logger)
|
||||||
|
o.Reconcile([]report.OperatorAction{{ID: 1, Action: report.OpAbandonStop}})
|
||||||
|
|
||||||
|
if mgr.AbandonStatus().Active {
|
||||||
|
t.Fatal("the running manager still counts down after abandon_stop")
|
||||||
|
}
|
||||||
|
onDisk, err := settings.Load(settingsPath, logger)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if tg := onDisk.GetOffboxTarget(); tg == nil || tg.AbandonAt != "" || tg.AbandonRepoPath == "" {
|
||||||
|
t.Fatalf("settings.json disagrees: %+v (want no due date, the set-aside path kept)", tg)
|
||||||
|
}
|
||||||
|
rs := o.Results()
|
||||||
|
if len(rs) != 1 || rs[0].Outcome != report.OutcomeDone {
|
||||||
|
t.Fatalf("result = %+v", rs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Control: the same countdown, a second press → nothing to stop, reported as such (not „done").
|
||||||
|
o.Reconcile([]report.OperatorAction{{ID: 2, Action: report.OpAbandonStop}})
|
||||||
|
if r := o.Results(); len(r) != 1 || r[0].ID != 2 || r[0].Outcome != report.OutcomeFailed {
|
||||||
|
t.Fatalf("second stop: %+v", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// offsite_backup_now refuses exactly where the household's „back up now" refuses: no target here.
|
||||||
|
func TestD1_OffsiteBackupNowRefusesWithoutATarget(t *testing.T) {
|
||||||
|
logger := log.New(io.Discard, "", 0)
|
||||||
|
dir := t.TempDir()
|
||||||
|
sett, err := settings.Load(filepath.Join(dir, "settings.json"), logger)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg := &config.Config{}
|
||||||
|
cfg.Paths.DataDir = dir
|
||||||
|
mgr := backup.NewManager(cfg, sett, logger)
|
||||||
|
mgr.SetOffboxRunner(func(context.Context, []string, ...string) ([]byte, error) {
|
||||||
|
t.Fatal("no restic may run")
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
o := report.NewOperatorActions(context.Background(), operatorActionHandlers(mgr, nil, holdClearDeps{}, nil, logger), logger)
|
||||||
|
o.Reconcile([]report.OperatorAction{{ID: 9, Action: report.OpOffsiteBackupNow}})
|
||||||
|
if r := o.Results(); len(r) != 1 || r[0].Outcome != report.OutcomeRefused {
|
||||||
|
t.Fatalf("result = %+v", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// run_job reaches the scheduler's RunNow: a registered job runs; a job not registered on this box is
|
||||||
|
// refused.
|
||||||
|
func TestD1_RunJobUsesTheScheduler(t *testing.T) {
|
||||||
|
logger := log.New(io.Discard, "", 0)
|
||||||
|
sched := scheduler.New(logger)
|
||||||
|
ran := make(chan bool, 1)
|
||||||
|
sched.Daily("fill-watch", "03:30", func(ctx context.Context) error { ran <- scheduler.OnDemand(ctx); return nil })
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
sched.Start(ctx)
|
||||||
|
defer sched.Stop()
|
||||||
|
o := report.NewOperatorActions(ctx, operatorActionHandlers(nil, sched, holdClearDeps{}, nil, logger), logger)
|
||||||
|
o.Reconcile([]report.OperatorAction{{ID: 1, Action: report.OpRunJob, Arg: "fill-watch"}, {ID: 2, Action: report.OpRunJob, Arg: "offsite-proof"}})
|
||||||
|
select {
|
||||||
|
case od := <-ran:
|
||||||
|
if !od {
|
||||||
|
t.Fatal("the job did not see itself as on-demand")
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("fill-watch never ran")
|
||||||
|
}
|
||||||
|
deadline := time.Now().Add(5 * time.Second)
|
||||||
|
for len(o.Results()) < 2 && time.Now().Before(deadline) {
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
}
|
||||||
|
got := map[int64]string{}
|
||||||
|
for _, r := range o.Results() {
|
||||||
|
got[r.ID] = r.Outcome
|
||||||
|
}
|
||||||
|
if got[1] != report.OutcomeDone || got[2] != report.OutcomeRefused {
|
||||||
|
t.Fatalf("outcomes = %v, want 1:done 2:refused (offsite-proof not registered here)", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// main.go hands the reply's list to the executor and the trigger to its holder — one call each
|
||||||
|
// (the seam-built-but-never-wired trap: a green executor that main never calls proves nothing).
|
||||||
|
func TestD1_MainWiresTheExecutor(t *testing.T) {
|
||||||
|
f, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
found := map[string]int{}
|
||||||
|
ast.Inspect(f, func(n ast.Node) bool {
|
||||||
|
call, ok := n.(*ast.CallExpr)
|
||||||
|
if !ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
switch fn := call.Fun.(type) {
|
||||||
|
case *ast.SelectorExpr:
|
||||||
|
if x, ok := fn.X.(*ast.Ident); ok {
|
||||||
|
found[x.Name+"."+fn.Sel.Name]++
|
||||||
|
}
|
||||||
|
case *ast.Ident:
|
||||||
|
found[fn.Name]++
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
for _, want := range []string{"opActions.Reconcile", "report.SetOperatorActions", "operatorActionHandlers", "opActionReportFire.Store"} {
|
||||||
|
if found[want] != 1 {
|
||||||
|
t.Errorf("main.go calls %s %d time(s), want exactly 1", want, found[want])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/notify"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1199 (rehearsal 2026-10-20) and R-1199 REOPENED (2026-10-22). A fresh box shows the household its DEFAULT
|
||||||
|
// notification list, but the hub mails only by its OWN stored list. v0.338.0 pushed that default at every start when
|
||||||
|
// nothing was saved on the box — and on a REBUILT box that overwrote the list the household had saved on its old box
|
||||||
|
// (demo-felhom, 07:54:55 UTC 2026-10-22: its own 13 events became the 17 defaults), again at every start, because the
|
||||||
|
// push created no local save. `08` „the household decides".
|
||||||
|
//
|
||||||
|
// Now, at start:
|
||||||
|
// - a list saved on this box: as before (R-922 — re-pushed when it carries an address or a clear), as the household's;
|
||||||
|
// - nothing saved here: READ the hub's list first. One the household saved (on any box) is ADOPTED as this box's
|
||||||
|
// list — nothing is pushed; otherwise the box's default is pushed once, as a default, and saved here, so the next
|
||||||
|
// start sends nothing. A hub that cannot be read (an older hub, no network) gets nothing; the next start asks again.
|
||||||
|
//
|
||||||
|
// The hub refuses a default over a household's list on its own side too (felhom.eu hub household_prefs.go), which also
|
||||||
|
// stops a box still on v0.338.0. Pinned by TestR1199Reopened_* (prefs_sync_wiring_test.go).
|
||||||
|
|
||||||
|
type prefsHub interface {
|
||||||
|
FetchPreferences() (*notify.HubPrefs, error)
|
||||||
|
SyncPreferencesAs(source, email string, enabledEvents []string, cooldownHours int, emailCleared bool) (string, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type prefsStore interface {
|
||||||
|
GetNotificationPrefs() *settings.NotificationPrefs
|
||||||
|
NotificationPrefsSaved() bool
|
||||||
|
SetNotificationPrefs(*settings.NotificationPrefs) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// startupPrefsSync runs the start-up step above and returns what it did (for the log and the tests): "pushed",
|
||||||
|
// "adopted", "default-pushed", "default-kept", "nothing", "no-hub" or "error".
|
||||||
|
func startupPrefsSync(hub prefsHub, st prefsStore, logger *log.Logger) string {
|
||||||
|
logf := func(f string, a ...any) {
|
||||||
|
if logger != nil {
|
||||||
|
logger.Printf(f, a...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
prefs := st.GetNotificationPrefs()
|
||||||
|
if st.NotificationPrefsSaved() {
|
||||||
|
if !prefs.SyncOnStartup() {
|
||||||
|
return "nothing"
|
||||||
|
}
|
||||||
|
if _, err := hub.SyncPreferencesAs(notify.PrefsSourceHousehold, prefs.Email, prefs.EnabledEvents, prefs.CooldownHours, prefs.EmailCleared); err != nil {
|
||||||
|
logf("[WARN] Failed to sync notification preferences on startup: %v", err)
|
||||||
|
return "error"
|
||||||
|
}
|
||||||
|
return "pushed"
|
||||||
|
}
|
||||||
|
hp, err := hub.FetchPreferences()
|
||||||
|
if err != nil {
|
||||||
|
logf("[WARN] notification prefs: no list saved on this box and the hub's could not be read (%v) — nothing pushed; asked again at the next start (R-1199)", err)
|
||||||
|
return "no-hub"
|
||||||
|
}
|
||||||
|
if hp.Exists && hp.HouseholdSaved {
|
||||||
|
adopted := &settings.NotificationPrefs{Email: hp.Email, EnabledEvents: hp.EnabledEvents, CooldownHours: hp.CooldownHours}
|
||||||
|
if adopted.EnabledEvents == nil {
|
||||||
|
adopted.EnabledEvents = []string{}
|
||||||
|
}
|
||||||
|
if err := st.SetNotificationPrefs(adopted); err != nil {
|
||||||
|
logf("[ERROR] notification prefs: adopting the household's list from the hub failed: %v", err)
|
||||||
|
return "error"
|
||||||
|
}
|
||||||
|
logf("[INFO] notification prefs: adopted the household's saved list from the hub (%d events, address set=%t) — nothing pushed (R-1199)", len(adopted.EnabledEvents), adopted.Email != "")
|
||||||
|
return "adopted"
|
||||||
|
}
|
||||||
|
status, err := hub.SyncPreferencesAs(notify.PrefsSourceDefault, "", prefs.EnabledEvents, prefs.CooldownHours, false)
|
||||||
|
if err != nil {
|
||||||
|
logf("[WARN] notification prefs: pushing the default list failed: %v", err)
|
||||||
|
return "error"
|
||||||
|
}
|
||||||
|
if status == "kept" {
|
||||||
|
logf("[INFO] notification prefs: the hub kept the household's own list over this box's default — adopted at the next start (R-1199)")
|
||||||
|
return "default-kept"
|
||||||
|
}
|
||||||
|
local := &settings.NotificationPrefs{EnabledEvents: prefs.EnabledEvents, CooldownHours: prefs.CooldownHours}
|
||||||
|
if err := st.SetNotificationPrefs(local); err != nil {
|
||||||
|
logf("[ERROR] notification prefs: saving the pushed default on this box failed: %v", err)
|
||||||
|
return "error"
|
||||||
|
}
|
||||||
|
logf("[INFO] notification prefs: no household list anywhere — pushed this box's default once and saved it here (R-1199)")
|
||||||
|
return "default-pushed"
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/notify"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1199 REOPENED (2026-10-22) — the brief's four cases, against the real settings file and a hub that behaves like
|
||||||
|
// hub ≥ 0.165.0 (it keeps a household's list over a default push).
|
||||||
|
// RED-PROOF: with v0.338.0's rule restored (no hub read: a box with nothing saved pushes its default at every start)
|
||||||
|
// case A fails (the default reaches the hub) and case D fails (a second push) — seen failing 2026-10-22.
|
||||||
|
|
||||||
|
type fakeHub struct {
|
||||||
|
stored *notify.HubPrefs
|
||||||
|
readErr error
|
||||||
|
pushes []string // the source of every push
|
||||||
|
lastEvents []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeHub) FetchPreferences() (*notify.HubPrefs, error) {
|
||||||
|
if f.readErr != nil {
|
||||||
|
return nil, f.readErr
|
||||||
|
}
|
||||||
|
if f.stored == nil {
|
||||||
|
return ¬ify.HubPrefs{Exists: false}, nil
|
||||||
|
}
|
||||||
|
cp := *f.stored
|
||||||
|
return &cp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeHub) SyncPreferencesAs(source, email string, ev []string, cd int, cleared bool) (string, error) {
|
||||||
|
f.pushes = append(f.pushes, source)
|
||||||
|
if source != notify.PrefsSourceHousehold && f.stored != nil && f.stored.HouseholdSaved {
|
||||||
|
return "kept", nil
|
||||||
|
}
|
||||||
|
if f.stored == nil {
|
||||||
|
f.stored = ¬ify.HubPrefs{Exists: true}
|
||||||
|
}
|
||||||
|
f.stored.EnabledEvents, f.lastEvents = ev, ev
|
||||||
|
if email != "" {
|
||||||
|
f.stored.Email = email
|
||||||
|
}
|
||||||
|
if source == notify.PrefsSourceHousehold {
|
||||||
|
f.stored.HouseholdSaved = true
|
||||||
|
}
|
||||||
|
return "ok", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSettings(t *testing.T) *settings.Settings {
|
||||||
|
t.Helper()
|
||||||
|
s, err := settings.Load(filepath.Join(t.TempDir(), "settings.json"), log.New(io.Discard, "", 0))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
var familyList = []string{"backup_failed", "disk_warning", "node_down"}
|
||||||
|
|
||||||
|
// A: the household saved on an earlier box; this box has no local save → nothing reaches the hub, the box adopts the
|
||||||
|
// list and its page (GetNotificationPrefs) shows it.
|
||||||
|
func TestR1199Reopened_A_ARebuiltBoxAdoptsTheHouseholdsList(t *testing.T) {
|
||||||
|
hub := &fakeHub{stored: ¬ify.HubPrefs{Exists: true, HouseholdSaved: true, Email: "family@example.hu", EnabledEvents: familyList, CooldownHours: 12}}
|
||||||
|
st := newSettings(t)
|
||||||
|
if got := startupPrefsSync(hub, st, nil); got != "adopted" {
|
||||||
|
t.Fatalf("startup = %q, want adopted", got)
|
||||||
|
}
|
||||||
|
if len(hub.pushes) != 0 {
|
||||||
|
t.Fatalf("a box with no list of its own pushed %v over the household's list", hub.pushes)
|
||||||
|
}
|
||||||
|
p := st.GetNotificationPrefs()
|
||||||
|
if !st.NotificationPrefsSaved() || len(p.EnabledEvents) != 3 || p.Email != "family@example.hu" || p.CooldownHours != 12 {
|
||||||
|
t.Fatalf("the page must show the household's list: %+v", p)
|
||||||
|
}
|
||||||
|
// D after A: the next start re-pushes the adopted list as the household's (it carries an address, R-922) — the
|
||||||
|
// same list, never the default.
|
||||||
|
startupPrefsSync(hub, st, nil)
|
||||||
|
if len(hub.pushes) != 1 || hub.pushes[0] != notify.PrefsSourceHousehold || len(hub.lastEvents) != 3 {
|
||||||
|
t.Fatalf("after adoption: pushes %v events %v", hub.pushes, hub.lastEvents)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// B: no household ever saved (a seeded row, or none) → the default goes once, is saved here, and the hub mails by it.
|
||||||
|
func TestR1199Reopened_B_NoHouseholdListAnywhereTakesTheDefaultOnce(t *testing.T) {
|
||||||
|
for _, stored := range []*notify.HubPrefs{nil, {Exists: true, Email: "seed@example.hu", EnabledEvents: []string{"node_down"}}} {
|
||||||
|
hub := &fakeHub{stored: stored}
|
||||||
|
st := newSettings(t)
|
||||||
|
if got := startupPrefsSync(hub, st, nil); got != "default-pushed" {
|
||||||
|
t.Fatalf("startup = %q, want default-pushed", got)
|
||||||
|
}
|
||||||
|
if len(hub.pushes) != 1 || hub.pushes[0] != notify.PrefsSourceDefault || len(hub.stored.EnabledEvents) != len(settings.DefaultEnabledEvents) {
|
||||||
|
t.Fatalf("the default must reach the hub once, as a default: %v %v", hub.pushes, hub.stored.EnabledEvents)
|
||||||
|
}
|
||||||
|
if !st.NotificationPrefsSaved() {
|
||||||
|
t.Fatal("the pushed default must be saved on the box")
|
||||||
|
}
|
||||||
|
// D: a restart sends nothing (a local save exists, with no address).
|
||||||
|
if got := startupPrefsSync(hub, st, nil); got != "nothing" || len(hub.pushes) != 1 {
|
||||||
|
t.Fatalf("restart after B: %q, pushes %v — want nothing", got, hub.pushes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// C: the household saves on the box → the page save pushes as the household's (web handler, unchanged path); at start
|
||||||
|
// a saved list with an address is re-pushed as the household's (R-922).
|
||||||
|
func TestR1199Reopened_C_ASavedListIsTheHouseholds(t *testing.T) {
|
||||||
|
hub := &fakeHub{stored: ¬ify.HubPrefs{Exists: true, HouseholdSaved: true, EnabledEvents: familyList}}
|
||||||
|
st := newSettings(t)
|
||||||
|
st.SetNotificationPrefs(&settings.NotificationPrefs{Email: "new@example.hu", EnabledEvents: []string{"node_down"}})
|
||||||
|
if got := startupPrefsSync(hub, st, nil); got != "pushed" || hub.pushes[0] != notify.PrefsSourceHousehold {
|
||||||
|
t.Fatalf("a saved list: %q %v", got, hub.pushes)
|
||||||
|
}
|
||||||
|
if len(hub.stored.EnabledEvents) != 1 {
|
||||||
|
t.Fatalf("the household's new choice must reach the hub: %v", hub.stored.EnabledEvents)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A hub that cannot be read gets nothing (never a blind default); a hub that keeps its list over a race is not
|
||||||
|
// overwritten and the box saves nothing (it adopts at the next start).
|
||||||
|
func TestR1199Reopened_AnUnreadableHubGetsNothing(t *testing.T) {
|
||||||
|
hub := &fakeHub{readErr: errors.New("hub answered HTTP 404")}
|
||||||
|
st := newSettings(t)
|
||||||
|
if got := startupPrefsSync(hub, st, nil); got != "no-hub" || len(hub.pushes) != 0 || st.NotificationPrefsSaved() {
|
||||||
|
t.Fatalf("unreadable hub: %q pushes %v saved %t", got, hub.pushes, st.NotificationPrefsSaved())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The default list the page shows carries the three events the rehearsal household did not get (kept from R-1199).
|
||||||
|
func TestR1199_TheDefaultListHoldsTheAlarmsTheHouseholdMissed(t *testing.T) {
|
||||||
|
want := map[string]bool{"disk_warning": false, "storage_disconnected": false, "crossdrive_failed": false}
|
||||||
|
for _, e := range settings.DefaultEnabledEvents {
|
||||||
|
if _, ok := want[e]; ok {
|
||||||
|
want[e] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for e, ok := range want {
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("%s is not in the default list", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1105: restic is pinned OUTSIDE the OS. Until v0.323.0 it came from the runtime's apt list, so the
|
||||||
|
// version was „whatever Debian ships" — a Debian 12 → 13 base move would have swapped restic 0.14.0 for
|
||||||
|
// 0.18.0 under the off-site code with nobody choosing it. The consequences pinned here:
|
||||||
|
// - the version is one explicit ARG, and each architecture's checksum is pinned beside it;
|
||||||
|
// - the fetch checks restic's signature (vendored key, no keyserver) AND both checksums;
|
||||||
|
// - the runtime takes restic ONLY from that stage — no apt package can bring a second one;
|
||||||
|
// - every base image is pinned by digest, and the Docker repo's codename is read from the image.
|
||||||
|
func TestR1105_ResticIsPinnedOutsideTheOS(t *testing.T) {
|
||||||
|
raw, err := os.ReadFile("../../Dockerfile")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
src := string(raw)
|
||||||
|
// Stages, split on FROM, with `\`-continued lines joined so an apt list reads as one command.
|
||||||
|
joined := strings.ReplaceAll(src, "\\\n", " ")
|
||||||
|
var stages []string
|
||||||
|
for _, part := range regexp.MustCompile(`(?m)^FROM `).Split(joined, -1)[1:] {
|
||||||
|
stages = append(stages, "FROM "+part)
|
||||||
|
}
|
||||||
|
if len(stages) < 3 {
|
||||||
|
t.Fatalf("expected a builder, a restic and a runtime stage, found %d stages", len(stages))
|
||||||
|
}
|
||||||
|
var fetch string
|
||||||
|
for _, s := range stages {
|
||||||
|
if regexp.MustCompile(`^FROM \S+ AS restic\b`).MatchString(s) {
|
||||||
|
fetch = s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fetch == "" {
|
||||||
|
t.Fatal("no `AS restic` stage: restic is no longer fetched as a pinned release binary")
|
||||||
|
}
|
||||||
|
runtime := stages[len(stages)-1]
|
||||||
|
|
||||||
|
if m := regexp.MustCompile(`ARG RESTIC_VERSION=(\d+\.\d+\.\d+)\s`).FindStringSubmatch(fetch); m == nil {
|
||||||
|
t.Error("ARG RESTIC_VERSION=X.Y.Z is missing — the version must be an explicit decision")
|
||||||
|
}
|
||||||
|
for _, arch := range []string{"AMD64", "ARM64"} {
|
||||||
|
if !regexp.MustCompile(`ARG RESTIC_SHA256_` + arch + `=[0-9a-f]{64}\s`).MatchString(fetch) {
|
||||||
|
t.Errorf("no pinned sha256 for %s", arch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, want := range []string{
|
||||||
|
"COPY third_party/restic/restic-release-key.asc",
|
||||||
|
"gpgv --keyring", // SHA256SUMS is restic's, signed
|
||||||
|
`SHA256SUMS | sha256sum -c -`, // the download matches the published sum
|
||||||
|
`echo "${want} ${f}" | sha256sum -c -`, // ...and the sum pinned in this file
|
||||||
|
} {
|
||||||
|
if !strings.Contains(fetch, want) {
|
||||||
|
t.Errorf("the restic stage no longer does %q", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := os.Stat("../../third_party/restic/restic-release-key.asc"); err != nil {
|
||||||
|
t.Errorf("the vendored release key is missing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(runtime, "COPY --from=restic /usr/local/bin/restic /usr/local/bin/restic") {
|
||||||
|
t.Error("the runtime does not take restic from the pinned stage")
|
||||||
|
}
|
||||||
|
aptRe := regexp.MustCompile(`apt-get install[^&]*`)
|
||||||
|
for _, inst := range aptRe.FindAllString(runtime, -1) {
|
||||||
|
if regexp.MustCompile(`\srestic(\s|$)`).MatchString(inst) {
|
||||||
|
t.Errorf("the runtime's apt list installs restic — a second, OS-chosen restic: %q", strings.Join(strings.Fields(inst), " "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, from := range regexp.MustCompile(`(?m)^FROM (\S+)`).FindAllStringSubmatch(src, -1) {
|
||||||
|
if !strings.Contains(from[1], "@sha256:") {
|
||||||
|
t.Errorf("base image %s is not pinned by digest", from[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if regexp.MustCompile(`download\.docker\.com/linux/debian (bookworm|trixie|forky)`).MatchString(src) {
|
||||||
|
t.Error("the Docker apt repo codename is hard-coded — it must come from /etc/os-release (VERSION_CODENAME)")
|
||||||
|
}
|
||||||
|
if !strings.Contains(runtime, "${VERSION_CODENAME}") {
|
||||||
|
t.Error("the Docker apt repo line does not read VERSION_CODENAME")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"go/ast"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1176 (2026-10-21): the off-site apply-bridge waits only until the FLOOR is known (offsiteapply.AwaitSettle), and
|
||||||
|
// then may mint a repository password unless the box has recorded that the hub holds the household's sealed package
|
||||||
|
// (R-241's mint guard reads that record). Both facts arrive in the same report ACK, so inside OnPushResponse the
|
||||||
|
// escrow must be recorded BEFORE updater.SetFloor makes the floor known — otherwise a bridge poll landing between the
|
||||||
|
// two mints a fresh key on a rebuilt box and the household's history is set aside on its first night.
|
||||||
|
// Walks main.go's AST with comments dropped, so a commented-out call cannot satisfy it.
|
||||||
|
// COMPANION RED-PROOF: move escrowConfirmer.Reconcile below updater.SetFloor → this fails.
|
||||||
|
func TestR1176_EscrowIsRecordedBeforeTheFloorIsKnown(t *testing.T) {
|
||||||
|
fset := token.NewFileSet()
|
||||||
|
f, err := parser.ParseFile(fset, "main.go", nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var escrowPos, floorPos token.Pos
|
||||||
|
ast.Inspect(f, func(n ast.Node) bool {
|
||||||
|
as, ok := n.(*ast.AssignStmt)
|
||||||
|
if !ok || len(as.Lhs) != 1 || len(as.Rhs) != 1 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
sel, ok := as.Lhs[0].(*ast.SelectorExpr)
|
||||||
|
if !ok || sel.Sel.Name != "OnPushResponse" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
ast.Inspect(as.Rhs[0], func(m ast.Node) bool {
|
||||||
|
call, ok := m.(*ast.CallExpr)
|
||||||
|
if !ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if s, ok := call.Fun.(*ast.SelectorExpr); ok {
|
||||||
|
if x, ok := s.X.(*ast.Ident); ok {
|
||||||
|
switch {
|
||||||
|
case x.Name == "escrowConfirmer" && s.Sel.Name == "Reconcile" && escrowPos == 0:
|
||||||
|
escrowPos = call.Pos()
|
||||||
|
case x.Name == "updater" && s.Sel.Name == "SetFloor" && floorPos == 0:
|
||||||
|
floorPos = call.Pos()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if escrowPos == 0 || floorPos == 0 {
|
||||||
|
t.Fatalf("OnPushResponse no longer calls both escrowConfirmer.Reconcile (%v) and updater.SetFloor (%v) — the order is unasserted", escrowPos, floorPos)
|
||||||
|
}
|
||||||
|
if escrowPos > floorPos {
|
||||||
|
t.Fatalf("escrowConfirmer.Reconcile (%s) runs AFTER updater.SetFloor (%s): a rebuilt box can mint a fresh key before it learns the hub holds the household's package",
|
||||||
|
fset.Position(escrowPos), fset.Position(floorPos))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1189 (d): the catch-up in main.go carries the After hook that runs the off-site proof and the due-gated integrity
|
||||||
|
// check (internal/nightchain TestR1189d_* pins that After runs; this pins that production wires it).
|
||||||
|
// RED-PROOF: the After block removed from main.go → this fails.
|
||||||
|
func TestR1189d_TheCatchUpIsWiredToTheChecks(t *testing.T) {
|
||||||
|
src, err := os.ReadFile("main.go")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s := string(src)
|
||||||
|
i := strings.Index(s, "catchUp := &nightchain.CatchUp{")
|
||||||
|
if i < 0 {
|
||||||
|
t.Fatal("the catch-up literal is gone from main.go")
|
||||||
|
}
|
||||||
|
lit := s[i:]
|
||||||
|
lit = lit[:strings.Index(lit, "\n\t\t\t}\n")]
|
||||||
|
a := strings.Index(lit, "After: func(ctx context.Context) {")
|
||||||
|
if a < 0 || !strings.Contains(lit[a:], "runOffsiteProof(") || !strings.Contains(lit[a:], "runOffsiteIntegrityCheck(ctx, backupMgr, notifier, logger, false)") {
|
||||||
|
t.Fatal("the catch-up must run the off-site proof and the due-gated (force=false) integrity check after its legs")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1253 (review round 2, HUNT-1 H3): an export with „stop the app first" during another app's restore replaced the
|
||||||
|
// ONE app-stop marker — the restore's crash record and its Undo were lost, and a power cut then left the restored app
|
||||||
|
// on mixed data with no put-back. The test is the review's mechanism with two Begins on one guard, through the
|
||||||
|
// exporter's real adapter. RED-PROOF (2026-10-24): with exportStopGuard.Begin calling Begin instead of BeginExclusive,
|
||||||
|
// this fails on „the restore's Undo is gone from the marker".
|
||||||
|
func TestR1253_AnExportNeverReplacesARestoresMarker(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
marker := filepath.Join(dir, "appstop-state.json")
|
||||||
|
g := backup.NewAppStopGuard(marker, log.New(io.Discard, "", 0))
|
||||||
|
if err := g.Begin("unit-restore:bookstack", backup.ReasonUnitRestore, []string{"bookstack"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
undo := filepath.Join(dir, "backups", "restore-undo", "bookstack", "20261024T200000Z")
|
||||||
|
if err := g.SetUndo("bookstack", undo); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ex := exportStopGuard{g: g}
|
||||||
|
if busy := ex.BusyWith(); busy != "unit-restore:bookstack" {
|
||||||
|
t.Fatalf("the export must see the restore holding the marker, got %q", busy)
|
||||||
|
}
|
||||||
|
err := ex.Begin("app-export:immich", []string{"immich"})
|
||||||
|
if !errors.Is(err, backup.ErrAppStopBusy) {
|
||||||
|
t.Fatalf("the export's Begin must be refused while the restore holds the marker, got %v", err)
|
||||||
|
}
|
||||||
|
b, _ := os.ReadFile(marker)
|
||||||
|
if !strings.Contains(string(b), undo) || strings.Contains(string(b), "immich") {
|
||||||
|
t.Fatalf("the restore's Undo is gone from the marker (or the export replaced it): %s", b)
|
||||||
|
}
|
||||||
|
// the restore ends → the export may run
|
||||||
|
g.End()
|
||||||
|
if err := ex.Begin("app-export:immich", []string{"immich"}); err != nil {
|
||||||
|
t.Fatalf("after the restore ended the export must start: %v", err)
|
||||||
|
}
|
||||||
|
ex.End()
|
||||||
|
// a marker a CRASH left (a new process over the same file) does not block: nothing in this process will End it
|
||||||
|
if err := g.Begin("volume-dump:paperless", backup.ReasonVolumeDump, []string{"paperless"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
fresh := exportStopGuard{g: backup.NewAppStopGuard(marker, log.New(io.Discard, "", 0))}
|
||||||
|
if busy := fresh.BusyWith(); busy != "" {
|
||||||
|
t.Fatalf("a crash-left marker is not a live operation, got %q", busy)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
// TestR1256_H8_TheSweepIsWiredAtStartup — R-1256 H8: an unused restore copy goes only through
|
||||||
|
// SweepUnusedRestoreCopies, so main.go must CALL it (the seam-built-but-never-wired class).
|
||||||
|
// RED-PROOF: delete the `restore-copy-sweep` job — this fails.
|
||||||
|
func TestR1256_H8_TheSweepIsWiredAtStartup(t *testing.T) {
|
||||||
|
lines, _, _ := slice4CallLines(t)
|
||||||
|
if len(lines["SweepUnusedRestoreCopies"]) == 0 {
|
||||||
|
t.Fatal("SweepUnusedRestoreCopies is never called — an unused restore copy would stay on the drive for ever")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1261 — a hold of an app removed while held is dropped only if main gives the watch the installed check; without
|
||||||
|
// it TorrentInstalled is nil, which means „assume installed", and the record waits for an app that never runs again.
|
||||||
|
func TestR1261_MainWiresTheInstalledCheck(t *testing.T) {
|
||||||
|
b, err := os.ReadFile("upwatch_wiring.go")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(b), "TorrentInstalled: func(stack string) bool") {
|
||||||
|
t.Fatal("upwatch_wiring.go must wire TorrentInstalled (R-1261)")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1279 — the `.fab` import downloads first only if main.go passes the restores' helper in; an unwired exporter keeps
|
||||||
|
// the old order (volumes removed before the pull). Seam-built-but-never-wired is a recorded class (REUSE.md).
|
||||||
|
func TestR1279_MainWiresTheImportsDownloadFirst(t *testing.T) {
|
||||||
|
b, err := os.ReadFile("main.go")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(b), "appExporter.SetImagePreparer(backupMgr.PrepareRestoreImages)") {
|
||||||
|
t.Fatal("main.go must wire the import's download-first helper (SetImagePreparer)")
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(b), "backupMgr.SetUnitSetAsideNotify(") {
|
||||||
|
t.Fatal("main.go must wire the D47 set-aside operator line")
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(b), "func (a *stackAdapter) ContainerSamples(") {
|
||||||
|
t.Fatal("main.go's stack adapter must read container samples for the stable-start rule (fix A)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fix A: the sampler reads a container with NO healthcheck (no State.Health) — measured on 9202: a -f template stopped
|
||||||
|
// at „map has no entry for key Health", so every such app read „not started".
|
||||||
|
func TestFixA_ParseContainerSamples(t *testing.T) {
|
||||||
|
out := []byte(`[{"Id":"a1","RestartCount":0,"State":{"Status":"running"}},
|
||||||
|
{"Id":"b2","RestartCount":3,"State":{"Status":"running","Health":{"Status":"healthy"}}},
|
||||||
|
{"Id":"c3","RestartCount":1,"State":{"Status":"restarting"}}]`)
|
||||||
|
got, err := parseContainerSamples(out)
|
||||||
|
if err != nil || len(got) != 3 {
|
||||||
|
t.Fatalf("parse: %v %+v", err, got)
|
||||||
|
}
|
||||||
|
if !got[0].Running || got[0].Health != "" || got[1].Health != "healthy" || got[1].RestartCount != 3 || got[2].Running {
|
||||||
|
t.Fatalf("wrong samples: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1286: demo-hp's Kimai was held by the crash-loop guard (reason unhealthy_stop, 2026-10-14) and the boot sweep, the
|
||||||
|
// start gate and `--restore-holds` all said „held after a failed restore whose rollback also failed" for 11 days.
|
||||||
|
// Each reason now says what it is and what lifts it.
|
||||||
|
// RED-PROOF: holdWhy back to the old two-way branch → the unhealthy_stop, restore_mixed and putback_pending cases fail.
|
||||||
|
func TestR1286_EveryHoldReasonSaysWhatItIs(t *testing.T) {
|
||||||
|
sett := holdTestSettings(t)
|
||||||
|
g := driveStartGate{sett: sett}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
hold settings.RestoreHold
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{settings.RestoreHold{Stack: "kimai", At: "2026-10-14T09:06:31Z", Reason: settings.HoldReasonUnhealthyStop, UnhealthyKind: "crash_loop"}, "stopped by the box for a crash loop"},
|
||||||
|
{settings.RestoreHold{Stack: "a", At: "t", Reason: settings.HoldReasonUpdateFailed}, "failed update"},
|
||||||
|
// R-1340 (2026-10-29): a record with no cause fields no longer claims „off-site … database replay" — that was the
|
||||||
|
// false story (a local restore of an app with no database read the same); it says what is known.
|
||||||
|
{settings.RestoreHold{Stack: "b", At: "t", Reason: settings.HoldReasonRestoreMixed}, "restore stopped half-way"},
|
||||||
|
{settings.RestoreHold{Stack: "c", At: "t", Reason: settings.HoldReasonPutBackPending}, "pre-restore copy is poured back"},
|
||||||
|
{settings.RestoreHold{Stack: "d", At: "t"}, "failed restore whose rollback also failed"},
|
||||||
|
} {
|
||||||
|
if err := sett.SetRestoreHold(tc.hold); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ok, why := g.MayStart(tc.hold.Stack)
|
||||||
|
if ok || !strings.Contains(why, tc.want) {
|
||||||
|
t.Fatalf("%s (reason %q): the gate says %q, want it to contain %q", tc.hold.Stack, tc.hold.Reason, why, tc.want)
|
||||||
|
}
|
||||||
|
if tc.hold.Reason != "" && strings.Contains(why, "failed restore whose rollback also failed") {
|
||||||
|
t.Fatalf("%s: a %q hold must not read as a failed restore: %q", tc.hold.Stack, tc.hold.Reason, why)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1347 and R-1348: each seam is CALLED from main.go (an AST walk) — a seam built and never wired is the project's
|
||||||
|
// oldest shape.
|
||||||
|
func TestR1347_UpdateHeldForgetterIsWiredAtStartup(t *testing.T) {
|
||||||
|
lines, _, _ := slice4CallLines(t)
|
||||||
|
if len(lines["SetUpdateHeldForgetter"]) == 0 {
|
||||||
|
t.Fatal("main.go never calls SetUpdateHeldForgetter — a restored app would stay unwatched until the controller restarts")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestR1348_HeldNotifyIsWiredAtStartup(t *testing.T) {
|
||||||
|
lines, _, _ := slice4CallLines(t)
|
||||||
|
if len(lines["SetHeldNotify"]) == 0 {
|
||||||
|
t.Fatal("main.go never calls SetHeldNotify — a failed put-back at start-up would mail nobody")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The mail's run name for an interrupted put-back. RED (2026-11-03, live on 9202): the sink showed run_kind offsite-reconstitute for a
|
||||||
|
// local restore.
|
||||||
|
func TestR1348_HeldRunKind(t *testing.T) {
|
||||||
|
for _, c := range []struct {
|
||||||
|
h settings.RestoreHold
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{settings.RestoreHold{Reason: settings.HoldReasonRestoreMixed, MixedCause: settings.MixedCauseInterruptedPutBack}, "restore"},
|
||||||
|
{settings.RestoreHold{RestoreKind: settings.RestoreKindLocal}, "restore"},
|
||||||
|
{settings.RestoreHold{RestoreKind: settings.RestoreKindOffsite}, "offsite-reconstitute"},
|
||||||
|
{settings.RestoreHold{Reason: settings.HoldReasonRestoreMixed}, "offsite-reconstitute"},
|
||||||
|
} {
|
||||||
|
if got := heldRunKind(c.h); got != c.want {
|
||||||
|
t.Errorf("%+v: run kind %q, want %q", c.h, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/report"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1350 (measured 2026-10-29 14:57 on Tester 1): the operator cleared gokapi's crash-loop hold from the hub, the app
|
||||||
|
// stayed stopped (the clear starts nothing), and 30 s later the dead-app scan sent „Telepített alkalmazás nem fut:
|
||||||
|
// Gokapi" — the hold had kept the app out of the scan, and the household's recorded wish was still „running".
|
||||||
|
// The fix: the clear records that the stop is WANTED (desired state „stopped") for an app that is not up, BEFORE the
|
||||||
|
// hold is lifted; a later Start records „running" and ends it.
|
||||||
|
|
||||||
|
// The consequence, through the scan's own derivation: a stopped app whose wish is „running" is DOWN (the alarm); the
|
||||||
|
// same app with the wish „stopped" is not.
|
||||||
|
func TestR1350_AStopWantedIsNotDown(t *testing.T) {
|
||||||
|
st := func(desired string) []stacks.Stack {
|
||||||
|
return []stacks.Stack{{Name: "gokapi", Deployed: true, State: stacks.StateStopped, AppConfig: &stacks.AppConfig{DesiredState: desired}}}
|
||||||
|
}
|
||||||
|
if _, states := classifyRunStates(st(stacks.DesiredStateRunning), nil, nil, time.Now()); len(states) != 1 || !states[0].Down {
|
||||||
|
t.Fatalf("fixture: a stopped app wished running must be down: %+v", states)
|
||||||
|
}
|
||||||
|
if _, states := classifyRunStates(st(stacks.DesiredStateStopped), nil, nil, time.Now()); len(states) != 1 || states[0].Down {
|
||||||
|
t.Fatalf("a stopped app wished stopped is down — the alarm fires: %+v", states)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The clear records the wish BEFORE the hold is lifted (a dead-app scan between the two would read „no hold, wished
|
||||||
|
// running" and mail), and only for an app that IS held. RED-PROOF: drop the keepStopped call from the clear → FAILS
|
||||||
|
// („not recorded"); call it after the lift → FAILS („after the hold was lifted").
|
||||||
|
func TestR1350_TheClearRecordsTheStopIsWanted(t *testing.T) {
|
||||||
|
r := newD64Rig(t)
|
||||||
|
r.hold(t, settings.RestoreHold{Stack: "gokapi", Reason: settings.HoldReasonUnhealthyStop, UnhealthyKind: "crash_loop", Trip: 1})
|
||||||
|
var recorded []string
|
||||||
|
var heldWhenRecorded bool
|
||||||
|
r.holdDeps.keepStopped = func(stack string) (bool, error) {
|
||||||
|
recorded = append(recorded, stack)
|
||||||
|
_, heldWhenRecorded = r.sett.GetRestoreHold(stack)
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
o := r.actions()
|
||||||
|
o.Reconcile([]report.OperatorAction{{ID: 21, Action: report.OpClearHold, Arg: "gokapi"}})
|
||||||
|
if res := onlyResult(t, o, 21); res.Outcome != report.OutcomeDone {
|
||||||
|
t.Fatalf("result %+v", res)
|
||||||
|
}
|
||||||
|
if len(recorded) != 1 || recorded[0] != "gokapi" {
|
||||||
|
t.Fatalf("the stop was not recorded as wanted: %v", recorded)
|
||||||
|
}
|
||||||
|
if !heldWhenRecorded {
|
||||||
|
t.Fatal("the wish was recorded after the hold was lifted — a scan in between mails app_start_failed")
|
||||||
|
}
|
||||||
|
if lg := r.logBuf.String(); !strings.Contains(lg, "gokapi: the stop is recorded as wanted") {
|
||||||
|
t.Fatalf("the box's log must say it:\n%s", lg)
|
||||||
|
}
|
||||||
|
// a refusal (no hold) records nothing — a down app with no hold is a real fault the alarm must keep
|
||||||
|
o.Reconcile([]report.OperatorAction{{ID: 22, Action: report.OpClearHold, Arg: "kimai"}})
|
||||||
|
if res := onlyResult(t, o, 22); res.Outcome != report.OutcomeRefused {
|
||||||
|
t.Fatalf("result %+v", res)
|
||||||
|
}
|
||||||
|
if len(recorded) != 1 {
|
||||||
|
t.Fatalf("a refused clear recorded a wish: %v", recorded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The running controller's clear is wired with the record. RED-PROOF: drop keepStopped from main.go's holdDeps → FAILS.
|
||||||
|
func TestR1350_MainWiresTheRecord(t *testing.T) {
|
||||||
|
raw, err := os.ReadFile("main.go")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(raw), "keepStopped: stackMgr.RecordStopWantedIfDown") || !strings.Contains(string(raw), "clear: appStopGuard.ClearHoldByOperatorThen") {
|
||||||
|
t.Fatal("main.go's hold clear does not record the wanted stop (R-1350)")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/fillwatch"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/system"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1371 — one warning per filesystem.
|
||||||
|
//
|
||||||
|
// The box as measured 2026-11-10 (demo-hp, the N100, Tester 1): "/" and `/mnt/sys_drive` are ONE filesystem, seen
|
||||||
|
// through two paths. The filesystem identity here is the one system.FilesystemKey gives on those boxes (its own rule
|
||||||
|
// is pinned by TestFilesystemKey_AnOverlayRootIsTheDockerDataRoot): equal for the two paths, another for a drive.
|
||||||
|
//
|
||||||
|
// RED-PROOF (observed 2026-11-10, then restored): with the filesystem check removed from fillTargetsBy this test fails
|
||||||
|
// with "one filling filesystem sent 2 warnings".
|
||||||
|
func boxKeys(extra map[string]uint64) func(string) (uint64, bool) {
|
||||||
|
keys := map[string]uint64{system.DockerVolumePath: 64519, "/mnt/sys_drive": 64519}
|
||||||
|
for p, k := range extra {
|
||||||
|
keys[p] = k
|
||||||
|
}
|
||||||
|
return func(p string) (uint64, bool) { k, ok := keys[p]; return k, ok }
|
||||||
|
}
|
||||||
|
|
||||||
|
func settingsWithDrives(t *testing.T, paths ...settings.StoragePath) *settings.Settings {
|
||||||
|
t.Helper()
|
||||||
|
sett, err := settings.Load(filepath.Join(t.TempDir(), "settings.json"), log.New(io.Discard, "", 0))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, sp := range paths {
|
||||||
|
if err := sett.AddStoragePath(sp); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sett
|
||||||
|
}
|
||||||
|
|
||||||
|
// The consequence: the one filesystem fills, and the household gets ONE warning, then ONE critical — through the real
|
||||||
|
// watcher and the real push closure.
|
||||||
|
func TestR1371_OneFillSendsOneWarning(t *testing.T) {
|
||||||
|
cfg := &config.Config{}
|
||||||
|
cfg.Paths.SystemDataPath = "/mnt/sys_drive"
|
||||||
|
sett := settingsWithDrives(t, settings.StoragePath{Path: "/mnt/felhom-drives/usb", Label: "Családi lemez", Schedulable: true})
|
||||||
|
key := boxKeys(map[string]uint64{"/mnt/felhom-drives/usb": 2049})
|
||||||
|
|
||||||
|
pct := 50.0
|
||||||
|
usage := func(p string) *fillwatch.Usage {
|
||||||
|
if p == "/mnt/felhom-drives/usb" {
|
||||||
|
return &fillwatch.Usage{UsedPercent: 20, AvailGB: 700, UsedGB: 200, TotalGB: 900}
|
||||||
|
}
|
||||||
|
// "/" and /mnt/sys_drive: the same filesystem, so the same numbers.
|
||||||
|
return &fillwatch.Usage{UsedPercent: pct, AvailGB: 68.7 * (100 - pct) / 100, UsedGB: 68.7 * pct / 100, TotalGB: 68.7}
|
||||||
|
}
|
||||||
|
w := fillwatch.New(filepath.Join(t.TempDir(), "fill.json"), log.New(io.Discard, "", 0),
|
||||||
|
func() []fillwatch.Target { return fillTargetsBy(cfg, sett, key) }, usage)
|
||||||
|
rec := &fakeFillPusher{}
|
||||||
|
w.SetNotify(fillEventPush(rec))
|
||||||
|
|
||||||
|
check := func() {
|
||||||
|
t.Helper()
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
if err := w.Check(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
check()
|
||||||
|
if len(rec.got) != 0 {
|
||||||
|
t.Fatalf("a half-full filesystem sent %d events", len(rec.got))
|
||||||
|
}
|
||||||
|
pct = 90
|
||||||
|
check()
|
||||||
|
if len(rec.got) != 1 {
|
||||||
|
t.Fatalf("one filling filesystem sent %d warnings (%+v), want exactly 1", len(rec.got), rec.got)
|
||||||
|
}
|
||||||
|
if rec.got[0].eventType != "disk_warning" {
|
||||||
|
t.Fatalf("event = %s, want disk_warning", rec.got[0].eventType)
|
||||||
|
}
|
||||||
|
if d, _ := rec.got[0].details.(map[string]any); d == nil || d["path"] != system.DockerVolumePath {
|
||||||
|
t.Fatalf("the warning is for %v, want the first target of the filesystem (%q)", rec.got[0].details, system.DockerVolumePath)
|
||||||
|
}
|
||||||
|
pct = 97
|
||||||
|
check()
|
||||||
|
if len(rec.got) != 2 || rec.got[1].eventType != "disk_critical" {
|
||||||
|
t.Fatalf("after 97%% the events are %+v, want one warning then one critical", rec.got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// What stays and what goes, target by target.
|
||||||
|
func TestR1371_TargetsByFilesystem(t *testing.T) {
|
||||||
|
cfg := &config.Config{}
|
||||||
|
cfg.Paths.SystemDataPath = "/mnt/sys_drive"
|
||||||
|
paths := func(ts []fillwatch.Target) []string {
|
||||||
|
var out []string
|
||||||
|
for _, tg := range ts {
|
||||||
|
out = append(out, tg.Path)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
eq := func(got, want []string) bool {
|
||||||
|
if len(got) != len(want) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i := range got {
|
||||||
|
if got[i] != want[i] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// One volume, no drive: one target, and it is the app area (the first one added).
|
||||||
|
got := fillTargetsBy(cfg, nil, boxKeys(nil))
|
||||||
|
if len(got) != 1 || got[0].Path != system.DockerVolumePath || got[0].LabelKey != "event.fill.label_apps" {
|
||||||
|
t.Fatalf("one-volume box: targets = %+v, want only the app area", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The OLD layout (two volumes): both areas stay.
|
||||||
|
two := func(p string) (uint64, bool) {
|
||||||
|
return map[string]uint64{system.DockerVolumePath: 1, "/mnt/sys_drive": 2}[p], p == system.DockerVolumePath || p == "/mnt/sys_drive"
|
||||||
|
}
|
||||||
|
if got := paths(fillTargetsBy(cfg, nil, two)); !eq(got, []string{"/", "/mnt/sys_drive"}) {
|
||||||
|
t.Fatalf("two-volume box: targets = %v, want both areas", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
sett := settingsWithDrives(t,
|
||||||
|
settings.StoragePath{Path: "/mnt/felhom-drives/a", Label: "A", Schedulable: true},
|
||||||
|
settings.StoragePath{Path: "/mnt/felhom-drives/b", Label: "B", Schedulable: true}, // a second folder of drive A's filesystem
|
||||||
|
settings.StoragePath{Path: "/mnt/felhom-drives/gone", Label: "Gone", Schedulable: true}, // unplugged: no identity
|
||||||
|
settings.StoragePath{Path: "/mnt/felhom-drives/gone2", Label: "Gone2", Schedulable: true}, // unplugged too
|
||||||
|
settings.StoragePath{Path: "/mnt/sys_drive/internal", Label: "Belső", Schedulable: true}, // a "drive" that is the system volume
|
||||||
|
)
|
||||||
|
key := boxKeys(map[string]uint64{"/mnt/felhom-drives/a": 2049, "/mnt/felhom-drives/b": 2049, "/mnt/sys_drive/internal": 64519})
|
||||||
|
want := []string{"/", "/mnt/felhom-drives/a", "/mnt/felhom-drives/gone", "/mnt/felhom-drives/gone2"}
|
||||||
|
if got := paths(fillTargetsBy(cfg, sett, key)); !eq(got, want) {
|
||||||
|
t.Fatalf("targets = %v, want %v — one per filesystem, and every path with no identity kept", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
// No identity at all (not Linux, or nothing readable): the list is the old one, by path.
|
||||||
|
none := func(string) (uint64, bool) { return 0, false }
|
||||||
|
if got := paths(fillTargetsBy(cfg, nil, none)); !eq(got, []string{"/", "/mnt/sys_drive"}) {
|
||||||
|
t.Fatalf("no identity: targets = %v, want both paths (one warning too many, never one too few)", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The wiring: the production list uses the real identity. On this machine "/mnt/sys_drive" does not exist, so it has
|
||||||
|
// no identity and stays; a folder and its sub-folder are one filesystem and collapse.
|
||||||
|
func TestR1371_ProductionListUsesTheRealIdentity(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
if _, ok := system.FilesystemKey(dir); !ok {
|
||||||
|
t.Skip("no filesystem identity on this machine (not Linux)")
|
||||||
|
}
|
||||||
|
cfg := &config.Config{}
|
||||||
|
cfg.Paths.SystemDataPath = dir
|
||||||
|
sett := settingsWithDrives(t, settings.StoragePath{Path: filepath.Join(dir, "sub"), Label: "Sub", Schedulable: true})
|
||||||
|
if err := os.MkdirAll(filepath.Join(dir, "sub"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := fillTargets(cfg, sett)
|
||||||
|
for _, tg := range got {
|
||||||
|
if tg.Path == filepath.Join(dir, "sub") {
|
||||||
|
t.Fatalf("fillTargets kept %q, a sub-folder of the system area's filesystem: targets = %+v", tg.Path, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// "/" and dir are one filesystem or two; the list must hold exactly that many targets.
|
||||||
|
rootKey, okRoot := system.FilesystemKey(system.DockerVolumePath)
|
||||||
|
dirKey, _ := system.FilesystemKey(dir)
|
||||||
|
want := 2
|
||||||
|
if okRoot && rootKey == dirKey {
|
||||||
|
want = 1
|
||||||
|
}
|
||||||
|
if len(got) != want {
|
||||||
|
t.Fatalf("fillTargets = %+v, want %d target(s): one per filesystem among / and %s", got, want, dir)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import (
|
|||||||
"go/parser"
|
"go/parser"
|
||||||
"go/token"
|
"go/token"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/i18n"
|
||||||
)
|
)
|
||||||
|
|
||||||
// R-359 — the scheduled job must be PROVEN WIRED.
|
// R-359 — the scheduled job must be PROVEN WIRED.
|
||||||
@@ -87,16 +89,33 @@ func TestR359_DebugCallbackIsWired(t *testing.T) {
|
|||||||
|
|
||||||
func TestR359_OutcomeMessagesCarryNoMachineDetail(t *testing.T) {
|
func TestR359_OutcomeMessagesCarryNoMachineDetail(t *testing.T) {
|
||||||
// The customer gets a sentence; restic's words go to the log. R-379: 615 bytes of raw database
|
// The customer gets a sentence; restic's words go to the log. R-379: 615 bytes of raw database
|
||||||
// text reached a customer once.
|
// text reached a customer once. R-585: the sentence is a bundle key now, so BOTH languages are
|
||||||
|
// held to it — an English household must be told what not to do just as plainly.
|
||||||
|
b, err := i18n.Shared()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
lang string
|
||||||
|
wants []string
|
||||||
|
}{
|
||||||
|
{"hu", []string{"Ne törölj semmit", "vedd fel velünk a kapcsolatot"}},
|
||||||
|
{"en", []string{"Do not delete anything", "contact us"}},
|
||||||
|
} {
|
||||||
|
msg, fellBack, ok := b.Text(tc.lang, "event.backup_integrity_failed")
|
||||||
|
if !ok || fellBack {
|
||||||
|
t.Fatalf("%s: event.backup_integrity_failed is missing (ok=%v fellBack=%v)", tc.lang, ok, fellBack)
|
||||||
|
}
|
||||||
for _, bad := range []string{"sftp:", "restic", "exit status", "@", "/srv/"} {
|
for _, bad := range []string{"sftp:", "restic", "exit status", "@", "/srv/"} {
|
||||||
if contains(integrityFailedMsg, bad) {
|
if contains(msg, bad) {
|
||||||
t.Errorf("the failure sentence carries machine detail %q: %q", bad, integrityFailedMsg)
|
t.Errorf("%s: the failure sentence carries machine detail %q: %q", tc.lang, bad, msg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// It must still tell them what to do — and what NOT to do.
|
// It must still tell them what to do — and what NOT to do.
|
||||||
for _, want := range []string{"Ne törölj semmit", "vedd fel velünk a kapcsolatot"} {
|
for _, want := range tc.wants {
|
||||||
if !contains(integrityFailedMsg, want) {
|
if !contains(msg, want) {
|
||||||
t.Errorf("the failure sentence is a dead end; missing %q", want)
|
t.Errorf("%s: the failure sentence is a dead end; missing %q", tc.lang, want)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/fillwatch"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/system"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fillPushRecord struct {
|
||||||
|
eventType, severity, message, household string
|
||||||
|
details interface{}
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeFillPusher struct{ got []fillPushRecord }
|
||||||
|
|
||||||
|
func (f *fakeFillPusher) PushEventHousehold(eventType, severity, message, household string, details interface{}) {
|
||||||
|
f.got = append(f.got, fillPushRecord{eventType, severity, message, household, details})
|
||||||
|
}
|
||||||
|
|
||||||
|
// R-521 F7 (BIGNIGHT 2026-09-14): the guest's own system disk at 95 % produced only `health_degraded`,
|
||||||
|
// whose mail a cooldown swallowed — no disk-specific event reached the hub. The consequence pinned here,
|
||||||
|
// through the REAL target list (fillTargets), the REAL watcher and the REAL push closure (fillEventPush):
|
||||||
|
// the guest's root filesystem at F7's numbers sends the hub's existing `disk_critical` event (severity
|
||||||
|
// critical, a type the hub already allowlists), ONCE (edge-triggered), carrying the Hungarian sentence
|
||||||
|
// AND the household's own (English here).
|
||||||
|
func TestR521F7_RootFilesystemSendsTheDiskEventInBothLanguages(t *testing.T) {
|
||||||
|
cfg := &config.Config{}
|
||||||
|
cfg.Paths.SystemDataPath = "/mnt/sys_drive"
|
||||||
|
usage := func(p string) *fillwatch.Usage {
|
||||||
|
if p == system.DockerVolumePath { // the guest's root filesystem as the controller sees it
|
||||||
|
return &fillwatch.Usage{UsedPercent: 95, AvailGB: 3.5, UsedGB: 61.8, TotalGB: 68.7}
|
||||||
|
}
|
||||||
|
return &fillwatch.Usage{UsedPercent: 30, AvailGB: 50, UsedGB: 20, TotalGB: 70}
|
||||||
|
}
|
||||||
|
w := fillwatch.New(filepath.Join(t.TempDir(), "fill.json"), log.New(io.Discard, "", 0),
|
||||||
|
func() []fillwatch.Target { return fillTargets(cfg, nil) }, usage)
|
||||||
|
rec := &fakeFillPusher{}
|
||||||
|
w.SetNotify(fillEventPush(rec))
|
||||||
|
w.SetLang(func() string { return "en" })
|
||||||
|
|
||||||
|
for i := 0; i < 2; i++ { // the second check sees the same band: nothing new (edge-triggered)
|
||||||
|
if err := w.Check(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(rec.got) != 1 {
|
||||||
|
t.Fatalf("pushes = %d (%+v), want exactly 1 disk event for the root filesystem", len(rec.got), rec.got)
|
||||||
|
}
|
||||||
|
p := rec.got[0]
|
||||||
|
if p.eventType != "disk_critical" || p.severity != "critical" {
|
||||||
|
t.Errorf("pushed %s/%s, want disk_critical/critical", p.eventType, p.severity)
|
||||||
|
}
|
||||||
|
if d, _ := p.details.(map[string]any); d == nil || d["path"] != system.DockerVolumePath {
|
||||||
|
t.Errorf("details = %v, want path %q", p.details, system.DockerVolumePath)
|
||||||
|
}
|
||||||
|
if !strings.Contains(p.message, "Alkalmaz") || !strings.Contains(p.message, "kritikusan") {
|
||||||
|
t.Errorf("Hungarian message = %q", p.message)
|
||||||
|
}
|
||||||
|
if !strings.Contains(p.household, "App area") || !strings.Contains(p.household, "critically full") {
|
||||||
|
t.Errorf("household (English) message = %q", p.household)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/agentapi"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-528: the scan's host counter source. An old agent (404) is asked again only after hostOOMRetryAfter; a transient
|
||||||
|
// failure is retried at the next scan; the counters pass through.
|
||||||
|
// RED-PROOF: drop the 404 back-off → an old agent is asked at every 30-s scan (calls 3, not 1) → FAILS.
|
||||||
|
func TestR528_HostOOMSourceBacksOffAnOldAgent(t *testing.T) {
|
||||||
|
clock := time.Date(2026, 10, 28, 23, 0, 0, 0, time.UTC)
|
||||||
|
calls := 0
|
||||||
|
var answer error = &agentapi.StatusError{Path: "/guest/oom-kills", Code: http.StatusNotFound}
|
||||||
|
src := hostOOMSource(func(context.Context) (agentapi.GuestOOMKillsState, error) {
|
||||||
|
calls++
|
||||||
|
if answer != nil {
|
||||||
|
return agentapi.GuestOOMKillsState{}, answer
|
||||||
|
}
|
||||||
|
return agentapi.GuestOOMKillsState{Available: true, Containers: map[string]int64{"id": 2}}, nil
|
||||||
|
}, log.New(io.Discard, "", 0), func() time.Time { return clock })
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
if got := src(); got != nil {
|
||||||
|
t.Fatalf("an old agent: %v", got)
|
||||||
|
}
|
||||||
|
clock = clock.Add(30 * time.Second)
|
||||||
|
}
|
||||||
|
if calls != 1 {
|
||||||
|
t.Fatalf("an old agent was asked %d times in 90 s, want 1", calls)
|
||||||
|
}
|
||||||
|
clock = clock.Add(hostOOMRetryAfter)
|
||||||
|
answer = nil
|
||||||
|
if got := src(); got["id"] != 2 || calls != 2 {
|
||||||
|
t.Fatalf("after the back-off, an upgraded agent: %v (calls %d)", got, calls)
|
||||||
|
}
|
||||||
|
answer = errors.New("timeout")
|
||||||
|
if got := src(); got != nil || calls != 3 {
|
||||||
|
t.Fatalf("a transient failure: %v", got)
|
||||||
|
}
|
||||||
|
answer = nil
|
||||||
|
if got := src(); got["id"] != 2 || calls != 4 {
|
||||||
|
t.Fatalf("the next scan after a transient failure must ask again: %v (calls %d)", got, calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The source is wired into the stack manager at startup (the seam-built-but-never-wired class).
|
||||||
|
// RED-PROOF: delete the SetHostOOMKills line in main.go → FAILS.
|
||||||
|
func TestR528_HostOOMSourceIsWiredAtStartup(t *testing.T) {
|
||||||
|
lines, _, _ := slice4CallLines(t)
|
||||||
|
if len(lines["SetHostOOMKills"]) == 0 || len(lines["hostOOMSource"]) == 0 {
|
||||||
|
t.Fatal("the host OOM counter is never wired — the 30-s scan would read Docker's flag only (R-528)")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"go/ast"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/crashboot"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-856 (`09` §3 decision 143): the dead-app check — the source of app_start_failed and
|
||||||
|
// app_stopped_unhealthy — waits on the crash-aware boot grace, not on the fixed 90 s constant.
|
||||||
|
//
|
||||||
|
// Red-proof: put `time.Since(startTime) < deadAppBootGrace` back as the check's gate — this test fails.
|
||||||
|
func TestR856_DeadAppCheckWaitsOnTheCrashAwareGrace(t *testing.T) {
|
||||||
|
f, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var body *ast.BlockStmt
|
||||||
|
ast.Inspect(f, func(n ast.Node) bool {
|
||||||
|
call, ok := n.(*ast.CallExpr)
|
||||||
|
if !ok || len(call.Args) < 3 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if sel, ok := call.Fun.(*ast.SelectorExpr); !ok || sel.Sel.Name != "Every" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if lit, ok := call.Args[0].(*ast.BasicLit); ok && lit.Value == `"deadapp-check"` {
|
||||||
|
if fl, ok := call.Args[2].(*ast.FuncLit); ok {
|
||||||
|
body = fl.Body
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if body == nil {
|
||||||
|
t.Fatal("the deadapp-check schedule is gone from main.go")
|
||||||
|
}
|
||||||
|
within, constant := false, false
|
||||||
|
ast.Inspect(body, func(n ast.Node) bool {
|
||||||
|
switch x := n.(type) {
|
||||||
|
case *ast.SelectorExpr:
|
||||||
|
if id, ok := x.X.(*ast.Ident); ok && id.Name == "bootGrace" && x.Sel.Name == "Within" {
|
||||||
|
within = true
|
||||||
|
}
|
||||||
|
case *ast.Ident:
|
||||||
|
if x.Name == "deadAppBootGrace" {
|
||||||
|
constant = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if !within || constant {
|
||||||
|
t.Errorf("the dead-app check must gate on bootGrace.Within (found=%v) and not on deadAppBootGrace (found=%v)", within, constant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The normal grace is today's 90 s: a normal boot must keep it exactly (decision 143's other half).
|
||||||
|
func TestR856_NormalGraceIsTheDeadAppBootGrace(t *testing.T) {
|
||||||
|
if crashboot.NormalGrace != deadAppBootGrace {
|
||||||
|
t.Errorf("crashboot.NormalGrace = %s, deadAppBootGrace = %s — a normal boot must keep today's grace", crashboot.NormalGrace, deadAppBootGrace)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// R-1112: main opens the family store at start (webServer.OpenFamilyStore), so an old family.json is converted on every
|
||||||
|
// box — not only on one where someone passes a family gate. Red-proof: remove the call from main.go → this fails.
|
||||||
|
func TestR1112_MainOpensTheFamilyStore(t *testing.T) {
|
||||||
|
f, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
ast.Inspect(f, func(n ast.Node) bool {
|
||||||
|
if call, ok := n.(*ast.CallExpr); ok {
|
||||||
|
if sel, ok := call.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "OpenFamilyStore" {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if !found {
|
||||||
|
t.Fatal("main.go does not call OpenFamilyStore — an old family.json keeps its session values until a family request")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/api"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/web"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-970 (v0.322.0) — the box's own hub API key opens NO route on the box.
|
||||||
|
//
|
||||||
|
// Until v0.322.0 a Bearer equal to the hub key reached /api/config/ (read the whole controller.yaml with every secret,
|
||||||
|
// and REPLACE it), /api/selfupdate/ and /api/geo/ from the internet, unsigned — against `01` §4 („no inbound control
|
||||||
|
// endpoint") and §10. The test drives the REAL route table (buildMux) with real web.Server and api.Router: a password
|
||||||
|
// is set (so auth is on), the request carries the key and no session, and the planted controller.yaml must be neither
|
||||||
|
// served nor changed.
|
||||||
|
//
|
||||||
|
// RED-PROOF (2026-10-16, REPORT): with an /api/geo/ route mounted without the session check, this failed at
|
||||||
|
// „GET /api/geo/countries with the hub key answered 200".
|
||||||
|
func TestR970_HubKeyOpensNoDoor(t *testing.T) {
|
||||||
|
const hubKey = "TESTONLY-hub-key-5d1b"
|
||||||
|
const secret = "TESTONLY-tunnel-token-q9"
|
||||||
|
dir := t.TempDir()
|
||||||
|
lg := log.New(io.Discard, "", 0)
|
||||||
|
cfgPath := filepath.Join(dir, "controller.yaml")
|
||||||
|
planted := "customer:\n id: t\n domain: example.hu\ninfrastructure:\n cf_tunnel_token: " + secret + "\n"
|
||||||
|
if err := os.WriteFile(cfgPath, []byte(planted), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg := config.Default()
|
||||||
|
cfg.Customer.Domain = "example.hu"
|
||||||
|
cfg.Hub.APIKey = hubKey
|
||||||
|
cfg.Paths.DataDir = filepath.Join(dir, "data")
|
||||||
|
sett, err := settings.Load(filepath.Join(dir, "settings.json"), lg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := sett.SetPasswordHash("$2a$10$abcdefghijklmnopqrstuuJ1A9pDq6s9F2x1H3bQb0v8Y3wq6z2Om"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ws := web.NewServer(cfg, nil, nil, nil, nil, sett, nil, nil, nil, lg, "test")
|
||||||
|
ar := api.NewRouter(cfg, cfgPath, sett, nil, nil, nil, nil, nil, nil, nil, lg)
|
||||||
|
mux := buildMux(ar, ws)
|
||||||
|
|
||||||
|
// Control: auth is on — a request with no key and no session is refused, so a refusal below means something.
|
||||||
|
ctl := httptest.NewRequest(http.MethodGet, "/api/stacks", nil)
|
||||||
|
ctl.Host = "felhom.example.hu"
|
||||||
|
cw := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(cw, ctl)
|
||||||
|
if cw.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("control: an anonymous /api/stacks answered %d, want 401 — auth is not on in this harness", cw.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
paths := []string{"/api/config", "/api/config/", "/api/config/apply", "/api/config/hash",
|
||||||
|
"/api/selfupdate/check", "/api/selfupdate/update", "/api/geo/settings", "/api/geo/countries", "/api/geo/sync"}
|
||||||
|
methods := []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch}
|
||||||
|
for _, p := range paths {
|
||||||
|
for _, m := range methods {
|
||||||
|
req := httptest.NewRequest(m, p, strings.NewReader("customer:\n id: evil\n domain: evil.example\n"))
|
||||||
|
req.Host = "felhom.example.hu"
|
||||||
|
req.Header.Set("Authorization", "Bearer "+hubKey)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(w, req)
|
||||||
|
if w.Code/100 == 2 {
|
||||||
|
t.Errorf("%s %s with the hub key answered %d — the key opens a door", m, p, w.Code)
|
||||||
|
}
|
||||||
|
if strings.Contains(w.Body.String(), secret) {
|
||||||
|
t.Fatalf("%s %s with the hub key served the settings file", m, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got, _ := os.ReadFile(cfgPath); string(got) != planted {
|
||||||
|
t.Fatal("controller.yaml was replaced through a hub-key request")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,13 +24,15 @@ type restoreEventPusher interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// loadRestoreRecordAtStartup wires persistence and returns the restore the last stop interrupted.
|
// loadRestoreRecordAtStartup wires persistence and returns the restore the last stop interrupted.
|
||||||
func loadRestoreRecordAtStartup(mgr *backup.Manager, dataDir string, logger *log.Logger) *backup.RestoreOpResult {
|
// putBack names the apps the crash recovery put back (AppStopRecovery.PutBack, D22 / R-1195); waiting those whose
|
||||||
|
// put-back waits for their drive (AppStopRecovery.Waiting, R-1251).
|
||||||
|
func loadRestoreRecordAtStartup(mgr *backup.Manager, dataDir string, logger *log.Logger, putBack, waiting []string) *backup.RestoreOpResult {
|
||||||
if mgr == nil {
|
if mgr == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
path := filepath.Join(dataDir, restoreRecordFileName)
|
path := filepath.Join(dataDir, restoreRecordFileName)
|
||||||
mgr.SetRestoreRecordPath(path)
|
mgr.SetRestoreRecordPath(path)
|
||||||
res := mgr.LoadRestoreRecord()
|
res := mgr.LoadRestoreRecordAfterRecovery(putBack, waiting)
|
||||||
if logger != nil {
|
if logger != nil {
|
||||||
logger.Printf("[INFO] [backup] restore record wired: %s (interrupted at startup: %t)", path, res != nil)
|
logger.Printf("[INFO] [backup] restore record wired: %s (interrupted at startup: %t)", path, res != nil)
|
||||||
}
|
}
|
||||||
@@ -42,6 +44,13 @@ func reportInterruptedRestore(p restoreEventPusher, res *backup.RestoreOpResult)
|
|||||||
if p == nil || res == nil {
|
if p == nil || res == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if res.PutBack || res.PutBackWaiting {
|
||||||
|
// D22 / R-1195: the data is back as before the restore — the record's own sentence, in the box's language.
|
||||||
|
// R-1251: or it is put back when the drive is there; „start it again" would restore the backup over it.
|
||||||
|
p.PushEvent("restore_interrupted", "warning", res.Stack+": "+res.Message,
|
||||||
|
map[string]any{"stack": res.Stack, "op": res.Op, "put_back": res.PutBack, "put_back_waiting": res.PutBackWaiting})
|
||||||
|
return
|
||||||
|
}
|
||||||
p.PushEvent("restore_interrupted", "warning",
|
p.PushEvent("restore_interrupted", "warning",
|
||||||
fmt.Sprintf("A(z) %s visszaállítása megszakadt, mert a doboz újraindult — indítsd el újra.", res.Stack),
|
fmt.Sprintf("A(z) %s visszaállítása megszakadt, mert a doboz újraindult — indítsd el újra.", res.Stack),
|
||||||
map[string]any{"stack": res.Stack, "op": res.Op})
|
map[string]any{"stack": res.Stack, "op": res.Op})
|
||||||
|
|||||||
@@ -33,13 +33,13 @@ func TestRestoreRecordAtStartup_RaisesInterruptedOnce(t *testing.T) {
|
|||||||
before.BeginRestoreOp("restore", "gokapi") // the box stops here
|
before.BeginRestoreOp("restore", "gokapi") // the box stops here
|
||||||
|
|
||||||
rec := &pushRecorder{}
|
rec := &pushRecorder{}
|
||||||
reportInterruptedRestore(rec, loadRestoreRecordAtStartup(new(backup.Manager), dir, lg))
|
reportInterruptedRestore(rec, loadRestoreRecordAtStartup(new(backup.Manager), dir, lg, nil, nil))
|
||||||
if len(rec.got) != 1 || rec.got[0].eventType != "restore_interrupted" || rec.got[0].severity != "warning" {
|
if len(rec.got) != 1 || rec.got[0].eventType != "restore_interrupted" || rec.got[0].severity != "warning" {
|
||||||
t.Fatalf("an interrupted restore raised no restore_interrupted (warning): %+v", rec.got)
|
t.Fatalf("an interrupted restore raised no restore_interrupted (warning): %+v", rec.got)
|
||||||
}
|
}
|
||||||
|
|
||||||
again := &pushRecorder{}
|
again := &pushRecorder{}
|
||||||
reportInterruptedRestore(again, loadRestoreRecordAtStartup(new(backup.Manager), dir, lg))
|
reportInterruptedRestore(again, loadRestoreRecordAtStartup(new(backup.Manager), dir, lg, nil, nil))
|
||||||
if len(again.got) != 0 {
|
if len(again.got) != 0 {
|
||||||
t.Fatalf("the same interruption was raised again on the next start: %+v", again.got)
|
t.Fatalf("the same interruption was raised again on the next start: %+v", again.got)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -111,3 +111,12 @@ func TestSlice4_UpdatingCheckIsWiredAtStartup(t *testing.T) {
|
|||||||
t.Fatal("backupMgr.SetUpdatingCheck is never called — the nightly legs cannot see an update in progress")
|
t.Fatal("backupMgr.SetUpdatingCheck is never called — the nightly legs cannot see an update in progress")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// R-645 (09 §3 decision 142): the backup manager must be told which apps are not running their pinned
|
||||||
|
// version, or the night backup writes a just-failed definition over the good unit after a hand-lifted hold.
|
||||||
|
func TestR645_VersionCheckIsWiredAtStartup(t *testing.T) {
|
||||||
|
lines, _, _ := slice4CallLines(t)
|
||||||
|
if len(lines["SetVersionCheck"]) == 0 {
|
||||||
|
t.Fatal("backupMgr.SetVersionCheck is never called — the night backup cannot see an app off its pin")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The stray-copy fix: main.go removes every leftover second-drive copy container BEFORE the scheduler and the web
|
||||||
|
// server start (either could begin a backup or a restore beside a lost copy). RED-PROOF (2026-10-22 night): the call
|
||||||
|
// removed, or moved below sched.Start, → this fails.
|
||||||
|
func TestStrayCopy_ClearIsWiredBeforeTheScheduler(t *testing.T) {
|
||||||
|
src, err := os.ReadFile("main.go")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s := string(src)
|
||||||
|
c := strings.Index(s, "backup.ClearLeftoverTier2Copies(ctx)")
|
||||||
|
st := strings.Index(s, "sched.Start(ctx)")
|
||||||
|
ws := strings.Index(s, "web.NewServer(")
|
||||||
|
if c < 0 || st < 0 || ws < 0 {
|
||||||
|
t.Fatalf("missing: clear=%d sched.Start=%d web.NewServer=%d", c, st, ws)
|
||||||
|
}
|
||||||
|
if c > st || c > ws {
|
||||||
|
t.Fatal("the leftover-copy removal must run before the scheduler and the web server start")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/agentapi"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/mediawire"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/metrics"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/notify"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/upwatch"
|
||||||
|
)
|
||||||
|
|
||||||
|
// qbLimitShare is qBittorrent's default share of the measured upload line — CC's pick, open for the operator (decide
|
||||||
|
// row in felhom.eu STATUS): 50 %.
|
||||||
|
const qbLimitShare = 0.5
|
||||||
|
|
||||||
|
// baselineMinMinutes: an app the box cannot ask is judged only once its history holds ~20 hours of minutes.
|
||||||
|
const baselineMinMinutes = 1200
|
||||||
|
|
||||||
|
// newUpwatch builds the upload and CPU watch (internal/upwatch; felhom.eu `08` §9). It does not start it.
|
||||||
|
func newUpwatch(sett *settings.Settings, stackMgr *stacks.Manager, backupMgr *backup.Manager, metricsStore *metrics.MetricsStore,
|
||||||
|
notifier *notify.Notifier, line agentLine, logger *log.Logger) *upwatch.Service {
|
||||||
|
box := mediawire.DockerBox{}
|
||||||
|
qb := &upwatch.QBittorrent{Box: box}
|
||||||
|
tr := &upwatch.Transmission{Box: box}
|
||||||
|
svc := &upwatch.Service{Store: sett, QB: qb, QBRunning: func() bool { return box.Running("qbittorrent") }, QBShare: qbLimitShare,
|
||||||
|
Measured: line.Measured, Log: logger,
|
||||||
|
// R-1250: a box that seeds all day is line-tested by holding its torrent app low for one test on request.
|
||||||
|
Torrents: []upwatch.Holdable{qb, tr}, TorrentRunning: box.Running, LineWaiting: line.Waiting, LineRun: line.Run,
|
||||||
|
// R-1261: a hold of an app removed while held is dropped (else the 50 % rule never runs again).
|
||||||
|
TorrentInstalled: func(stack string) bool {
|
||||||
|
st, ok := stackMgr.GetStack(stack)
|
||||||
|
return ok && st != nil && st.Deployed
|
||||||
|
}}
|
||||||
|
w := &upwatch.Watcher{
|
||||||
|
Source: &upwatch.DockerAPI{},
|
||||||
|
Explainers: map[string]upwatch.Explainer{
|
||||||
|
"qbittorrent": qb,
|
||||||
|
"transmission": tr,
|
||||||
|
"plex": &upwatch.Plex{Token: func() string { return mediawire.PlexToken(box) }, URL: mediawire.PlexURL},
|
||||||
|
},
|
||||||
|
Rules: upwatch.DefaultRules(),
|
||||||
|
Line: svc.Line,
|
||||||
|
Busy: func(stack string) bool {
|
||||||
|
if backupMgr != nil && backupMgr.IsRunning() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if st, ok := stackMgr.GetStack(stack); ok && st != nil && (st.Updating || st.Deploying) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
},
|
||||||
|
Emit: notifier.NotifyUnexplained,
|
||||||
|
Log: logger,
|
||||||
|
}
|
||||||
|
if metricsStore != nil {
|
||||||
|
w.Baseline = dailyBaseline(metricsStore)
|
||||||
|
}
|
||||||
|
svc.Watcher = w
|
||||||
|
return svc
|
||||||
|
}
|
||||||
|
|
||||||
|
// agentLine is the host's line test as the watch uses it; every field nil without a local API.
|
||||||
|
type agentLine struct {
|
||||||
|
Measured func(context.Context) (float64, time.Time, bool)
|
||||||
|
Waiting func(context.Context) bool // waiting_for_quiet (agent ≥ 0.165.0, R-1250)
|
||||||
|
Run func(context.Context) (upwatch.LineRunResult, error) // POST /host/line-test/run
|
||||||
|
}
|
||||||
|
|
||||||
|
// agentLineTest reads the host's weekly line test through the agent's local API (agent ≥ 0.164.0; an older agent
|
||||||
|
// answers 404 → not measured, and never waiting). Empty without a local API.
|
||||||
|
func agentLineTest(endpoint, token, fingerprint string, logger *log.Logger) agentLine {
|
||||||
|
if endpoint == "" || token == "" {
|
||||||
|
return agentLine{}
|
||||||
|
}
|
||||||
|
ac, err := agentapi.New(endpoint, token, fingerprint)
|
||||||
|
if err != nil {
|
||||||
|
logger.Printf("[WARN] [upwatch] agent client init failed (%v) — no line test; qBittorrent gets no limit", err)
|
||||||
|
return agentLine{}
|
||||||
|
}
|
||||||
|
read := func(ctx context.Context) (agentapi.LineTestState, error) {
|
||||||
|
cctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
return ac.LineTest(cctx)
|
||||||
|
}
|
||||||
|
return agentLine{
|
||||||
|
Measured: func(ctx context.Context) (float64, time.Time, bool) {
|
||||||
|
st, err := read(ctx)
|
||||||
|
if err != nil {
|
||||||
|
logger.Printf("[DEBUG] [upwatch] line test read: %v", err)
|
||||||
|
return 0, time.Time{}, false
|
||||||
|
}
|
||||||
|
return st.Mbps, st.MeasuredAtTime(), st.Present
|
||||||
|
},
|
||||||
|
Waiting: func(ctx context.Context) bool {
|
||||||
|
st, err := read(ctx)
|
||||||
|
return err == nil && st.WaitingForQuiet
|
||||||
|
},
|
||||||
|
Run: func(ctx context.Context) (upwatch.LineRunResult, error) {
|
||||||
|
r, err := ac.LineTestRun(ctx)
|
||||||
|
return upwatch.LineRunResult{OK: r.OK, Mbps: r.Mbps, Refused: r.Refused, Error: r.Error}, err
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// dailyBaseline caches each app's p95 for a day (a 7-day query is a few hundred thousand rows).
|
||||||
|
func dailyBaseline(ms *metrics.MetricsStore) func(string, []string) (float64, bool) {
|
||||||
|
type entry struct {
|
||||||
|
at time.Time
|
||||||
|
p95 float64
|
||||||
|
ok bool
|
||||||
|
}
|
||||||
|
var mu sync.Mutex
|
||||||
|
cache := map[string]entry{}
|
||||||
|
return func(stack string, containers []string) (float64, bool) {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
if e, ok := cache[stack]; ok && time.Since(e.at) < 24*time.Hour {
|
||||||
|
return e.p95, e.ok
|
||||||
|
}
|
||||||
|
p95, minutes, err := ms.StackTxP95Mbps(containers, time.Now().Add(-7*24*time.Hour))
|
||||||
|
e := entry{at: time.Now(), p95: p95, ok: err == nil && minutes >= baselineMinMinutes}
|
||||||
|
cache[stack] = e
|
||||||
|
return e.p95, e.ok
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// startUpwatch runs the minute watcher and the 15-minute qBittorrent limit rule until ctx ends. A torrent limit a
|
||||||
|
// stopped controller left at the line-test value is put back first (R-1250), before any rule reads it.
|
||||||
|
func startUpwatch(ctx context.Context, svc *upwatch.Service, logger *log.Logger) {
|
||||||
|
svc.RecoverHold(ctx)
|
||||||
|
svc.RefreshMeasured(ctx)
|
||||||
|
go svc.Watcher.Run(ctx, time.Minute)
|
||||||
|
go func() {
|
||||||
|
t := time.NewTicker(15 * time.Minute)
|
||||||
|
defer t.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-t.C:
|
||||||
|
svc.SeedLineTestNow(ctx) // R-1250: holds the torrent app only while the agent waits for quiet
|
||||||
|
svc.QBLimitNow(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
l, ok := svc.Line()
|
||||||
|
logger.Printf("[INFO] [upwatch] upload and CPU watch started (line %s, qBittorrent share %.0f %%)", lineText(l, ok), qbLimitShare*100)
|
||||||
|
}
|
||||||
|
|
||||||
|
func lineText(l float64, ok bool) string {
|
||||||
|
if !ok {
|
||||||
|
return "unknown — no weekly line test yet and no counting off-site push"
|
||||||
|
}
|
||||||
|
return upwatch.MbpsText(int64(l*1e6/8)) + " Mbit/s"
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/notify"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/upwatch"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The upload watch is built, started, handed to the off-site push BEFORE the scheduler can start one, and its view
|
||||||
|
// handed to the pages — a seam built and never wired is this project's commonest defect.
|
||||||
|
// RED-PROOF: delete the SetOffboxPushObserver line → fails; move it below the scheduler's start → fails; pass nil
|
||||||
|
// instead of agentLineTest(...) → the qBittorrent limit never gets a tested line → fails.
|
||||||
|
func TestUpwatchIsWiredAtStartup(t *testing.T) {
|
||||||
|
lines, _, _ := slice4CallLines(t)
|
||||||
|
for _, fn := range []string{"newUpwatch", "agentLineTest", "SetOffboxPushObserver", "startUpwatch", "SetUpwatchView"} {
|
||||||
|
if len(lines[fn]) == 0 {
|
||||||
|
t.Fatalf("main.go never calls %s", fn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if lines["SetOffboxPushObserver"][0] > lines["Daily"][0] {
|
||||||
|
t.Fatalf("SetOffboxPushObserver (line %d) comes after the first scheduled job (line %d)", lines["SetOffboxPushObserver"][0], lines["Daily"][0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// newUpwatch asks the three apps the spike proved, reports through the notifier, and reads exact counters.
|
||||||
|
// RED-PROOF: drop the transmission entry → fails.
|
||||||
|
func TestNewUpwatch_ExplainersAndEmit(t *testing.T) {
|
||||||
|
lg := log.New(io.Discard, "", 0)
|
||||||
|
sett, err := settings.Load(filepath.Join(t.TempDir(), "settings.json"), lg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
svc := newUpwatch(sett, nil, nil, nil, notify.New("", "", "", sett, lg, false), agentLine{}, lg)
|
||||||
|
for _, a := range []string{"qbittorrent", "transmission", "plex"} {
|
||||||
|
if _, ok := svc.Watcher.Explainers[a]; !ok {
|
||||||
|
t.Errorf("no explainer for %s", a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if svc.Watcher.Emit == nil || svc.Watcher.Line == nil || svc.QB == nil || svc.QBShare != 0.5 {
|
||||||
|
t.Fatalf("service not wired: %+v", svc)
|
||||||
|
}
|
||||||
|
if _, ok := svc.Watcher.Source.(*upwatch.DockerAPI); !ok {
|
||||||
|
t.Fatal("the watch must read the Engine API's exact counters, not docker stats' text")
|
||||||
|
}
|
||||||
|
// R-1250: both torrent apps can be held, qBittorrent first; without a local API there is no hold at all.
|
||||||
|
if len(svc.Torrents) != 2 || svc.Torrents[0].Stack() != "qbittorrent" || svc.Torrents[1].Stack() != "transmission" ||
|
||||||
|
svc.TorrentRunning == nil || svc.LineWaiting != nil || svc.LineRun != nil {
|
||||||
|
t.Fatalf("line-test hold not wired: %d torrents, waiting=%v run=%v", len(svc.Torrents), svc.LineWaiting != nil, svc.LineRun != nil)
|
||||||
|
}
|
||||||
|
if svc.Watcher.Baseline != nil {
|
||||||
|
t.Fatal("no metrics store, yet a baseline: an app with no explainer would be judged without history")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// R-1250: the start-up check puts a held limit back BEFORE the first rule reads it, and every tick runs the hold
|
||||||
|
// before the 50 % rule. Asserted on startUpwatch's source order.
|
||||||
|
// RED-PROOF: move svc.RecoverHold below the ticker, or drop SeedLineTestNow → fails.
|
||||||
|
func TestStartUpwatchRecoversTheHoldFirst(t *testing.T) {
|
||||||
|
src, err := os.ReadFile("upwatch_wiring.go")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body := string(src)
|
||||||
|
i := strings.Index(body, "func startUpwatch(")
|
||||||
|
if i < 0 {
|
||||||
|
t.Fatal("no startUpwatch")
|
||||||
|
}
|
||||||
|
body = body[i:]
|
||||||
|
rec, ticker := strings.Index(body, "svc.RecoverHold(ctx)"), strings.Index(body, "time.NewTicker(")
|
||||||
|
seed, rule := strings.Index(body, "svc.SeedLineTestNow(ctx)"), strings.Index(body, "svc.QBLimitNow(ctx)")
|
||||||
|
if rec < 0 || rec > ticker {
|
||||||
|
t.Fatalf("RecoverHold at %d, the ticker at %d: a held limit must go back before anything else runs", rec, ticker)
|
||||||
|
}
|
||||||
|
if seed < 0 || seed > rule {
|
||||||
|
t.Fatalf("SeedLineTestNow at %d, QBLimitNow at %d: the hold must run before the 50 %% rule", seed, rule)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// With a local API, agentLineTest yields all three halves, and newUpwatch hands the hold both agent calls.
|
||||||
|
// RED-PROOF: drop LineRun from newUpwatch's Service, or Run from agentLineTest → fails.
|
||||||
|
func TestUpwatchHoldGetsBothAgentCalls(t *testing.T) {
|
||||||
|
lg := log.New(io.Discard, "", 0)
|
||||||
|
line := agentLineTest("127.0.0.1:1", "token-canary", strings.Repeat("ab", 32), lg)
|
||||||
|
if line.Measured == nil || line.Waiting == nil || line.Run == nil {
|
||||||
|
t.Fatalf("agentLineTest with a local API: measured=%v waiting=%v run=%v", line.Measured != nil, line.Waiting != nil, line.Run != nil)
|
||||||
|
}
|
||||||
|
sett, err := settings.Load(filepath.Join(t.TempDir(), "settings.json"), lg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
svc := newUpwatch(sett, nil, nil, nil, notify.New("", "", "", sett, lg, false), line, lg)
|
||||||
|
if svc.Measured == nil || svc.LineWaiting == nil || svc.LineRun == nil {
|
||||||
|
t.Fatalf("newUpwatch dropped an agent call: measured=%v waiting=%v run=%v", svc.Measured != nil, svc.LineWaiting != nil, svc.LineRun != nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-3
@@ -1,12 +1,12 @@
|
|||||||
module gitea.dooplex.hu/admin/felhom-controller
|
module gitea.dooplex.hu/admin/felhom-controller
|
||||||
|
|
||||||
go 1.24.0
|
go 1.27.4
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6
|
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6
|
||||||
github.com/emersion/go-smtp v0.24.0
|
github.com/emersion/go-smtp v0.24.0
|
||||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||||
golang.org/x/crypto v0.31.0
|
golang.org/x/crypto v0.58.0
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
modernc.org/sqlite v1.45.0
|
modernc.org/sqlite v1.45.0
|
||||||
)
|
)
|
||||||
@@ -18,7 +18,7 @@ require (
|
|||||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
|
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
|
||||||
golang.org/x/sys v0.37.0 // indirect
|
golang.org/x/sys v0.49.0 // indirect
|
||||||
modernc.org/libc v1.67.6 // indirect
|
modernc.org/libc v1.67.6 // indirect
|
||||||
modernc.org/mathutil v1.7.1 // indirect
|
modernc.org/mathutil v1.7.1 // indirect
|
||||||
modernc.org/memory v1.11.0 // indirect
|
modernc.org/memory v1.11.0 // indirect
|
||||||
|
|||||||
+6
-6
@@ -18,8 +18,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
|
|||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
|
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
|
||||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
|
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
|
||||||
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
|
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
|
||||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
|
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
|
||||||
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
|
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
|
||||||
@@ -27,10 +27,10 @@ golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
|
|||||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
|
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||||
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||||
golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
|
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
|
||||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
|
||||||
golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
|
golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
|
||||||
golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
|
golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
|
|||||||
@@ -22,7 +22,10 @@
|
|||||||
# is a Finder Settings -> Sidebar toggle). Treat sidebar discovery as an OPEN
|
# is a Finder Settings -> Sidebar toggle). Treat sidebar discovery as an OPEN
|
||||||
# question, not a shipped feature.
|
# question, not a shipped feature.
|
||||||
# Evidence: felhom.eu/documentation/audits/DIAG-sharing-2026-07-20.md.
|
# Evidence: felhom.eu/documentation/audits/DIAG-sharing-2026-07-20.md.
|
||||||
FROM alpine:3.21@sha256:48b0309ca019d89d40f670aa1bc06e426dc0931948452e8491e3d65087abc07d
|
# 1.2.0 (R-972): Alpine 3.24.2, pinned by digest — the same base as the hub. 3.21 carried 48 fixable high findings
|
||||||
|
# (audits/security-review-2026-10-12/scanners/). Same packages; scanner before → after in the controller's v0.323.0 CHANGELOG.
|
||||||
|
# upstream: gap:Alpine's package fixes (Samba among them) are in its secdb, which the watch does not read; BEHIND on the point release is the signal
|
||||||
|
FROM alpine:3.24.2@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6
|
||||||
|
|
||||||
# samba = smbd + nmbd + smbpasswd/testparm (meta-package proven installable in the spike);
|
# samba = smbd + nmbd + smbpasswd/testparm (meta-package proven installable in the spike);
|
||||||
# wsdd = WS-Discovery daemon; tini = a proper PID1 to reap nmbd/wsdd/avahi and forward signals;
|
# wsdd = WS-Discovery daemon; tini = a proper PID1 to reap nmbd/wsdd/avahi and forward signals;
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
// Package aftercrash runs the apps' after_unclean_boot blocks ONCE per controller start that followed an unclean
|
||||||
|
// host boot (R-1007, `09` §3 decision 236).
|
||||||
|
//
|
||||||
|
// The fact is crashboot's (the host crash guard, read through the agent): the same verdict that holds the app mails
|
||||||
|
// for CrashGrace. Unknown is a normal boot — a repair never runs on a guess. A normal boot never runs it. After a crash
|
||||||
|
// boot it waits CrashGrace from the controller's start (the apps come up slowly after a crash), then runs each app's
|
||||||
|
// block one after the other and reports each app's counts. It never stops an app; a failed run is reported, not
|
||||||
|
// retried. Pinned by aftercrash_test.go.
|
||||||
|
package aftercrash
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/crashboot"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Verdict is crashboot.Grace's Decided (a seam for tests).
|
||||||
|
type Verdict func(now time.Time) (resolved, crash bool, bootAt time.Time)
|
||||||
|
|
||||||
|
// Runner does the one run. Every func field is required; Logger may be nil.
|
||||||
|
type Runner struct {
|
||||||
|
Start time.Time
|
||||||
|
Verdict Verdict
|
||||||
|
Apps func() []string
|
||||||
|
Run func(name string, bootAt time.Time) stacks.AfterUncleanBootResult
|
||||||
|
Report func(name string, bootAt time.Time, res stacks.AfterUncleanBootResult)
|
||||||
|
Logger *log.Logger
|
||||||
|
// Wait is how long after Start a crash-boot run waits (default crashboot.CrashGrace).
|
||||||
|
Wait time.Duration
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
done bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// New builds the runner on the controller's crash-boot grace.
|
||||||
|
func New(g *crashboot.Grace, apps func() []string,
|
||||||
|
run func(string, time.Time) stacks.AfterUncleanBootResult,
|
||||||
|
report func(string, time.Time, stacks.AfterUncleanBootResult), logger *log.Logger) *Runner {
|
||||||
|
return &Runner{Start: g.Start(), Verdict: g.Decided, Apps: apps, Run: run, Report: report, Logger: logger}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Done reports whether this start's decision has been taken (ran, or decided not to).
|
||||||
|
func (r *Runner) Done() bool {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
return r.done
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tick is called periodically (the scheduler). It returns true once the run has happened or been ruled out.
|
||||||
|
func (r *Runner) Tick(now time.Time) bool {
|
||||||
|
r.mu.Lock()
|
||||||
|
if r.done {
|
||||||
|
r.mu.Unlock()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
resolved, crash, bootAt := r.Verdict(now)
|
||||||
|
if !resolved {
|
||||||
|
r.mu.Unlock()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !crash {
|
||||||
|
r.done = true
|
||||||
|
r.mu.Unlock()
|
||||||
|
r.logf("[INFO] [aftercrash] a normal (or unknown) boot — no app repair after an unclean boot (R-1007)")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
wait := r.Wait
|
||||||
|
if wait <= 0 {
|
||||||
|
wait = crashboot.CrashGrace
|
||||||
|
}
|
||||||
|
if now.Sub(r.Start) < wait {
|
||||||
|
r.mu.Unlock()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
r.done = true // set BEFORE the run: a slow or failing run is never started twice
|
||||||
|
r.mu.Unlock()
|
||||||
|
|
||||||
|
apps := r.Apps()
|
||||||
|
r.logf("[INFO] [aftercrash] the host's boot at %s followed an unclean stop — %d app(s) with an after_unclean_boot block (R-1007)",
|
||||||
|
bootAt.UTC().Format(time.RFC3339), len(apps))
|
||||||
|
for _, name := range apps {
|
||||||
|
res := r.Run(name, bootAt)
|
||||||
|
if res.Skipped != "" {
|
||||||
|
r.logf("[WARN] [aftercrash] %s: skipped — %s", name, res.Skipped)
|
||||||
|
} else {
|
||||||
|
r.logf("[INFO] [aftercrash] %s: found %d empty file(s), repaired %d, still broken %d, lost %d (checked=%t) in %s%s",
|
||||||
|
name, res.Found, res.Repaired, res.StillBroken, res.Lost, res.LostChecked, res.Duration.Round(time.Millisecond), problem(res.Problem))
|
||||||
|
}
|
||||||
|
r.Report(name, bootAt, res)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func problem(p string) string {
|
||||||
|
if p == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return " — problem: " + p
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) logf(format string, args ...any) {
|
||||||
|
if r.Logger != nil {
|
||||||
|
r.Logger.Printf(format, args...)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package aftercrash
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/crashboot"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1007 (decision 236): the repair runs ONLY after an unclean host boot that THIS start followed, only after the
|
||||||
|
// crash grace, and only once. A normal boot and an unknown fact never run it. The verdict is crashboot's own (the
|
||||||
|
// real Grace with a fake probe), so these tests assert the consequence: was the app's block run?
|
||||||
|
|
||||||
|
var start = time.Date(2026, 10, 14, 12, 8, 0, 0, time.UTC)
|
||||||
|
|
||||||
|
func probe(f crashboot.Fact, err error) crashboot.Probe {
|
||||||
|
return func(context.Context) (crashboot.Fact, error) { return f, err }
|
||||||
|
}
|
||||||
|
|
||||||
|
func runner(p crashboot.Probe) (*Runner, *[]string) {
|
||||||
|
var ran []string
|
||||||
|
g := crashboot.New(start, p, nil)
|
||||||
|
r := New(g, func() []string { return []string{"immich"} },
|
||||||
|
func(name string, _ time.Time) stacks.AfterUncleanBootResult {
|
||||||
|
ran = append(ran, name)
|
||||||
|
return stacks.AfterUncleanBootResult{}
|
||||||
|
},
|
||||||
|
func(string, time.Time, stacks.AfterUncleanBootResult) {}, nil)
|
||||||
|
return r, &ran
|
||||||
|
}
|
||||||
|
|
||||||
|
// RED-PROOF: drop the `now.Sub(r.Start) < wait` check → the run happens at +1 min → fails.
|
||||||
|
// RED-PROOF: drop `r.done = true` before the run → a second tick runs it again → fails.
|
||||||
|
func TestAfterCrash_RunsOnceAfterTheGraceOnAnUncleanBootThisStartFollowed(t *testing.T) {
|
||||||
|
r, ran := runner(probe(crashboot.Fact{Known: true, Unclean: true, BootAt: start.Add(-40 * time.Second)}, nil))
|
||||||
|
for _, at := range []time.Duration{0, time.Minute, 14 * time.Minute} {
|
||||||
|
r.Tick(start.Add(at))
|
||||||
|
}
|
||||||
|
if len(*ran) != 0 {
|
||||||
|
t.Fatalf("ran inside the crash grace: %v", *ran)
|
||||||
|
}
|
||||||
|
r.Tick(start.Add(crashboot.CrashGrace + time.Second))
|
||||||
|
r.Tick(start.Add(crashboot.CrashGrace + time.Minute))
|
||||||
|
if len(*ran) != 1 {
|
||||||
|
t.Fatalf("ran %d time(s), want exactly once after the grace", len(*ran))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RED-PROOF: in Tick, treat `!crash` like a crash (drop the early return) → a normal boot runs the repair → fails.
|
||||||
|
func TestAfterCrash_NeverOnANormalAnUnknownOrAnOldUncleanBoot(t *testing.T) {
|
||||||
|
cases := map[string]crashboot.Probe{
|
||||||
|
"normal boot": probe(crashboot.Fact{Known: true, Unclean: false, BootAt: start.Add(-time.Minute)}, nil),
|
||||||
|
"unknown (no crash guard)": probe(crashboot.Fact{}, nil),
|
||||||
|
"unknown (agent unreachable)": probe(crashboot.Fact{}, context.DeadlineExceeded),
|
||||||
|
"no agent at all": nil,
|
||||||
|
"an unclean boot days ago": probe(crashboot.Fact{Known: true, Unclean: true, BootAt: start.Add(-72 * time.Hour)}, nil),
|
||||||
|
"an unclean boot with no time": probe(crashboot.Fact{Known: true, Unclean: true}, nil),
|
||||||
|
}
|
||||||
|
for name, p := range cases {
|
||||||
|
r, ran := runner(p)
|
||||||
|
for at := time.Duration(0); at <= 2*crashboot.CrashGrace; at += 30 * time.Second {
|
||||||
|
r.Tick(start.Add(at))
|
||||||
|
}
|
||||||
|
if len(*ran) != 0 {
|
||||||
|
t.Errorf("%s: the repair ran", name)
|
||||||
|
}
|
||||||
|
if !r.Done() {
|
||||||
|
t.Errorf("%s: the decision was never taken", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -64,6 +64,21 @@ func targetQuery(target string) string {
|
|||||||
return "?target=" + url.QueryEscape(target)
|
return "?target=" + url.QueryEscape(target)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// backupStartQuery is targetQuery plus `trigger=manual` for a household press (R-899).
|
||||||
|
func backupStartQuery(target string, manual bool) string {
|
||||||
|
q := url.Values{}
|
||||||
|
if target != "" {
|
||||||
|
q.Set("target", target)
|
||||||
|
}
|
||||||
|
if manual {
|
||||||
|
q.Set("trigger", "manual")
|
||||||
|
}
|
||||||
|
if len(q) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return "?" + q.Encode()
|
||||||
|
}
|
||||||
|
|
||||||
// BackupDueFor reports whether THIS TIER is due. A fresh backup on another tier must not satisfy it
|
// BackupDueFor reports whether THIS TIER is due. A fresh backup on another tier must not satisfy it
|
||||||
// — that filtering happens agent-side (latestSuccessfulBackupForTarget); this just asks per tier.
|
// — that filtering happens agent-side (latestSuccessfulBackupForTarget); this just asks per tier.
|
||||||
func (c *Client) BackupDueFor(ctx context.Context, target string) (DueResponse, error) {
|
func (c *Client) BackupDueFor(ctx context.Context, target string) (DueResponse, error) {
|
||||||
@@ -80,8 +95,15 @@ func (c *Client) BackupDueFor(ctx context.Context, target string) (DueResponse,
|
|||||||
|
|
||||||
// StartBackupFor enqueues a backup of this guest ON THE GIVEN TIER.
|
// StartBackupFor enqueues a backup of this guest ON THE GIVEN TIER.
|
||||||
func (c *Client) StartBackupFor(ctx context.Context, target string) (BackupResponse, error) {
|
func (c *Client) StartBackupFor(ctx context.Context, target string) (BackupResponse, error) {
|
||||||
|
return c.StartBackupForTrigger(ctx, target, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartBackupForTrigger is StartBackupFor that also says whether this is a household press (R-899): a press
|
||||||
|
// carries `trigger=manual`, and an agent that knows it does not start the night's OS leg after it. An older
|
||||||
|
// agent ignores the parameter (it reads only `target`), so the request is safe against any agent.
|
||||||
|
func (c *Client) StartBackupForTrigger(ctx context.Context, target string, manual bool) (BackupResponse, error) {
|
||||||
var out BackupResponse
|
var out BackupResponse
|
||||||
body, err := c.post(ctx, "/backup"+targetQuery(target), struct{}{})
|
body, err := c.post(ctx, "/backup"+backupStartQuery(target, manual), struct{}{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return out, err
|
return out, err
|
||||||
}
|
}
|
||||||
@@ -105,6 +127,48 @@ func (c *Client) BackupStatusFor(ctx context.Context, target string) (StatusResp
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BackupJobsInFlight (R-921) lists the tiers whose backup job the agent holds in flight right now — phase
|
||||||
|
// running or snapshotted, the agent's own definition (localapi backupInFlight). A job in flight on another
|
||||||
|
// tier is the agent's first reason to refuse POST /backup (HTTP 409), so the controller asks this BEFORE it
|
||||||
|
// stops any app. It reads only GET /backup/tiers and GET /backup/status?target= (both agent >= v0.97.0); a
|
||||||
|
// pre-R-82 agent (no /backup/tiers) answers nil, nil. Any other error is returned — the caller fails toward
|
||||||
|
// backing up. It does NOT see the agent's host-wide heavy-operation gate; HostBusy does (newer agents).
|
||||||
|
func (c *Client) BackupJobsInFlight(ctx context.Context) ([]string, error) {
|
||||||
|
tiers, err := c.BackupTiers(ctx)
|
||||||
|
if errors.Is(err, ErrTiersUnsupported) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
for _, t := range tiers.Tiers {
|
||||||
|
st, err := c.BackupStatusFor(ctx, t.Target)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if st.Phase == PhaseRunning || st.Phase == PhaseSnapshotted {
|
||||||
|
out = append(out, t.Target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HostBusy (R-921) reads GET /backup/status's host_busy: whether the agent's host-wide heavy-operation gate is held
|
||||||
|
// right now (another guest's backup, the restore test, a night OS step …) — the agent's second reason to refuse
|
||||||
|
// POST /backup. known=false: the agent does not serve the field (older than the agent release that adds it) — no
|
||||||
|
// information, never „free". An error is returned; the caller fails toward backing up.
|
||||||
|
func (c *Client) HostBusy(ctx context.Context) (busy bool, what string, known bool, err error) {
|
||||||
|
st, err := c.BackupStatusFor(ctx, "")
|
||||||
|
if err != nil {
|
||||||
|
return false, "", false, err
|
||||||
|
}
|
||||||
|
if st.HostBusy == nil {
|
||||||
|
return false, "", false, nil
|
||||||
|
}
|
||||||
|
return st.HostBusy.Busy, st.HostBusy.What, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
// SetBackupTargetResponse mirrors POST /backup/target (agent >= v0.113.0).
|
// SetBackupTargetResponse mirrors POST /backup/target (agent >= v0.113.0).
|
||||||
type SetBackupTargetResponse struct {
|
type SetBackupTargetResponse struct {
|
||||||
Target string `json:"target"`
|
Target string `json:"target"`
|
||||||
|
|||||||
@@ -202,6 +202,15 @@ type StatusResponse struct {
|
|||||||
// Tiers (agent >= v0.131.0, R-517) — per tier: newest success, last attempt, storage presence.
|
// Tiers (agent >= v0.131.0, R-517) — per tier: newest success, last attempt, storage presence.
|
||||||
// Absent on an older agent; the page then falls back to the single latest record.
|
// Absent on an older agent; the page then falls back to the single latest record.
|
||||||
Tiers []TierBackupState `json:"tiers,omitempty"`
|
Tiers []TierBackupState `json:"tiers,omitempty"`
|
||||||
|
// HostBusy (R-921, agent Unreleased 2026-10-19) — whether the agent's host-wide heavy-operation gate is held
|
||||||
|
// right now (then POST /backup answers 409). nil = an older agent that does not serve it.
|
||||||
|
HostBusy *HostBusyState `json:"host_busy,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// HostBusyState mirrors the agent's localapi.HostBusyState.
|
||||||
|
type HostBusyState struct {
|
||||||
|
Busy bool `json:"busy"`
|
||||||
|
What string `json:"what,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// TierBackupState mirrors the agent's localapi.TierBackupState.
|
// TierBackupState mirrors the agent's localapi.TierBackupState.
|
||||||
@@ -255,6 +264,9 @@ const (
|
|||||||
PhaseRunning = "running"
|
PhaseRunning = "running"
|
||||||
PhaseDone = "done"
|
PhaseDone = "done"
|
||||||
PhaseFailed = "failed"
|
PhaseFailed = "failed"
|
||||||
|
// PhaseSnapshotted (8B.2): the storage snapshot is taken, the upload still runs and still holds the
|
||||||
|
// guest — the agent counts it as IN FLIGHT (felhom-agent localapi backupInFlight).
|
||||||
|
PhaseSnapshotted = "snapshotted"
|
||||||
)
|
)
|
||||||
|
|
||||||
// BackupDue reports whether a policy-scheduled backup is due for this guest (the quiesce trigger).
|
// BackupDue reports whether a policy-scheduled backup is due for this guest (the quiesce trigger).
|
||||||
@@ -272,15 +284,7 @@ func (c *Client) BackupDue(ctx context.Context) (DueResponse, error) {
|
|||||||
|
|
||||||
// StartBackup enqueues a backup of this guest (the agent vzdump) and returns the job to poll.
|
// StartBackup enqueues a backup of this guest (the agent vzdump) and returns the job to poll.
|
||||||
func (c *Client) StartBackup(ctx context.Context) (BackupResponse, error) {
|
func (c *Client) StartBackup(ctx context.Context) (BackupResponse, error) {
|
||||||
var out BackupResponse
|
return c.StartBackupForTrigger(ctx, "", false)
|
||||||
body, err := c.post(ctx, "/backup", struct{}{})
|
|
||||||
if err != nil {
|
|
||||||
return out, err
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(body, &out); err != nil {
|
|
||||||
return out, fmt.Errorf("agentapi: decode POST /backup: %w", err)
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// BackupStatus reports the current/last backup job phase for this guest.
|
// BackupStatus reports the current/last backup job phase for this guest.
|
||||||
@@ -360,8 +364,18 @@ type DiskInfo struct {
|
|||||||
// agent predates the field — the disk-health card + 6h degradation check feature-detect on this and
|
// agent predates the field — the disk-health card + 6h degradation check feature-detect on this and
|
||||||
// render "Nincs adat" (never alarm) when nil. See DiskVerdictFor.
|
// render "Nincs adat" (never alarm) when nil. See DiskVerdictFor.
|
||||||
Smart *SmartSummary `json:"smart,omitempty"`
|
Smart *SmartSummary `json:"smart,omitempty"`
|
||||||
|
// Physical-disk identity (agent v0.157.0, `16` §3): kind, the keys of the physical disks under the place,
|
||||||
|
// proven|unknown + reason. Empty from an older agent or for an absent drive.
|
||||||
|
Kind string `json:"kind,omitempty"` // system | internal | disk | partition | network (felhom.eu `16` §3)
|
||||||
|
PhysicalDisks []string `json:"physical_disks,omitempty"`
|
||||||
|
Identity string `json:"identity,omitempty"`
|
||||||
|
IdentityReason string `json:"identity_reason,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PlaceKindInternal is the agent's kind for the one-disk box's internal data place („Belső tárhely", agent ≥ 0.158.0,
|
||||||
|
// felhom.eu architecture/16 §5): a host mount on the system disk, bound at /mnt/felhom-drives/belso.
|
||||||
|
const PlaceKindInternal = "internal"
|
||||||
|
|
||||||
// FSUUID returns the raw filesystem UUID from a "uuid:<…>" DurableID, or "" if this disk's identity
|
// FSUUID returns the raw filesystem UUID from a "uuid:<…>" DurableID, or "" if this disk's identity
|
||||||
// is not a filesystem UUID (network/lvm targets — not assignable as a host mount).
|
// is not a filesystem UUID (network/lvm targets — not assignable as a host mount).
|
||||||
func (d DiskInfo) FSUUID() string {
|
func (d DiskInfo) FSUUID() string {
|
||||||
@@ -378,6 +392,10 @@ type DisksResponse struct {
|
|||||||
// GuestBootID changes on every guest boot (host or guest reboot) but is stable across a
|
// GuestBootID changes on every guest boot (host or guest reboot) but is stable across a
|
||||||
// controller-only restart — the deterministic signal the controller recreates drive-backed apps on.
|
// controller-only restart — the deterministic signal the controller recreates drive-backed apps on.
|
||||||
GuestBootID string `json:"guest_boot_id,omitempty"`
|
GuestBootID string `json:"guest_boot_id,omitempty"`
|
||||||
|
// GuestBootKey (R-1395; an agent after 0.174.0) is the same signal built from the kernel's boot_id instead of
|
||||||
|
// the boot TIME: a step of the host's clock moves the boot time (and so GuestBootID) and does not move this.
|
||||||
|
// "" from an older agent — the controller then reads GuestBootID as before. See web.guestBootVerdict.
|
||||||
|
GuestBootKey string `json:"guest_boot_key,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// FormatResult mirrors POST /disks/format (the success/refusal payload).
|
// FormatResult mirrors POST /disks/format (the success/refusal payload).
|
||||||
@@ -424,6 +442,36 @@ var ErrFormatRefused = fmt.Errorf("agentapi: format refused — system/backup de
|
|||||||
// The UI surfaces the type-to-confirm flow, then re-submits with confirmed=true + that durable id.
|
// The UI surfaces the type-to-confirm flow, then re-submits with confirmed=true + that durable id.
|
||||||
var ErrNeedsConfirmation = fmt.Errorf("agentapi: format needs customer confirmation — user-data device")
|
var ErrNeedsConfirmation = fmt.Errorf("agentapi: format needs customer confirmation — user-data device")
|
||||||
|
|
||||||
|
// ErrNoDurableID is the agent's anti-retarget refusal of a blank format (R-1069): the device has no durable id to
|
||||||
|
// bind the format to — a virtual disk passed on a virtio bus without a serial has no /dev/disk/by-id link. The agent's
|
||||||
|
// rule is a safety rule and stays; this only lets the dashboard say it in plain words. Matched on the agent's own
|
||||||
|
// refusal text (felhom-agent internal/localapi/disks.go „format refused: device has no durable id"); if that text
|
||||||
|
// ever changes, the refusal degrades to the raw message it was before. Pinned by TestFormatDisk_NoDurableIDIsTyped.
|
||||||
|
var ErrNoDurableID = fmt.Errorf("agentapi: format refused — the device has no durable id (path-only formats are not permitted)")
|
||||||
|
|
||||||
|
// SameDiskResult is the agent's answer to POST /disks/same-disk (v0.157.0). Act on Proven first:
|
||||||
|
// Proven+Different = a counted second copy; Proven+!Different = the same disk; !Proven = unknown
|
||||||
|
// (Reason vm|network|usb_bridge|weak_wwn|no_serial|unmapped).
|
||||||
|
type SameDiskResult struct {
|
||||||
|
Different bool `json:"different"`
|
||||||
|
Proven bool `json:"proven"`
|
||||||
|
Reason string `json:"reason,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SameDisk asks the agent whether two guest paths sit on the same physical disk. Gate it with
|
||||||
|
// Supports(FeatureSameDisk) — an older agent answers 404.
|
||||||
|
func (c *Client) SameDisk(ctx context.Context, a, b string) (SameDiskResult, error) {
|
||||||
|
var out SameDiskResult
|
||||||
|
raw, err := c.post(ctx, "/disks/same-disk", map[string]string{"a": a, "b": b})
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &out); err != nil {
|
||||||
|
return out, fmt.Errorf("agentapi: decode /disks/same-disk: %w", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Disks lists the host drives the agent manages, with a data-bearing flag per drive.
|
// Disks lists the host drives the agent manages, with a data-bearing flag per drive.
|
||||||
func (c *Client) Disks(ctx context.Context) (DisksResponse, error) {
|
func (c *Client) Disks(ctx context.Context) (DisksResponse, error) {
|
||||||
var out DisksResponse
|
var out DisksResponse
|
||||||
@@ -453,8 +501,37 @@ type DiskCandidate struct {
|
|||||||
// mountpoint — sending it down the device-attach path would try to mount an in-guest path as if
|
// mountpoint — sending it down the device-attach path would try to mount an in-guest path as if
|
||||||
// it were a raw device. See web/attach_sources.go for why the agent's scan cannot supply these.
|
// it were a raw device. See web/attach_sources.go for why the agent's scan cannot supply these.
|
||||||
AlreadyMounted bool `json:"already_mounted,omitempty"`
|
AlreadyMounted bool `json:"already_mounted,omitempty"`
|
||||||
|
// Partitions (agent ≥ 0.158.0, felhom.eu architecture/16 §6): each partition of this disk as its own place —
|
||||||
|
// state empty („format this part"), filesystem („use this part" when mountable; format through the confirmed
|
||||||
|
// path), in_use (already a Felhom drive: shown, never offered). Absent from an older agent.
|
||||||
|
Partitions []CandidatePartition `json:"partitions,omitempty"`
|
||||||
|
// WholeDiskInUse is set by the CONTROLLER (never the agent) when a partition of this disk is a registered drive
|
||||||
|
// (R-542): the disk stays listed for its FREE parts only, and no whole-disk action is offered.
|
||||||
|
WholeDiskInUse bool `json:"whole_disk_in_use,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CandidatePartition mirrors the agent's partition entry (felhom-agent internal/storage/partitions.go).
|
||||||
|
type CandidatePartition struct {
|
||||||
|
Device string `json:"device"`
|
||||||
|
Number int `json:"number,omitempty"`
|
||||||
|
SizeBytes int64 `json:"size_bytes"`
|
||||||
|
FSType string `json:"fstype,omitempty"`
|
||||||
|
State string `json:"state"` // empty | filesystem | in_use
|
||||||
|
Mountable bool `json:"mountable"`
|
||||||
|
DurableID string `json:"durable_id,omitempty"` // uuid:<fs-uuid> — the attach key
|
||||||
|
MountedAt string `json:"mounted_at,omitempty"`
|
||||||
|
// Formattable (agent ≥ 0.158.1): false for every part of a disk with a mounted node — the root mkfs wrapper refuses
|
||||||
|
// those and trusts no „it is Felhom's own" claim. Only formattable parts are offered for formatting.
|
||||||
|
Formattable bool `json:"formattable"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Partition states (agent ≥ 0.158.0).
|
||||||
|
const (
|
||||||
|
PartEmpty = "empty"
|
||||||
|
PartFilesystem = "filesystem"
|
||||||
|
PartInUse = "in_use"
|
||||||
|
)
|
||||||
|
|
||||||
// CandidatesResult mirrors GET /disks/candidates: disks free to enroll, split into initialize (all
|
// CandidatesResult mirrors GET /disks/candidates: disks free to enroll, split into initialize (all
|
||||||
// unclaimed) and attach (the mountable-FS subset).
|
// unclaimed) and attach (the mountable-FS subset).
|
||||||
type CandidatesResult struct {
|
type CandidatesResult struct {
|
||||||
@@ -514,6 +591,10 @@ type GuestMemoryInfo struct {
|
|||||||
MaxMB int64 `json:"max_mb"`
|
MaxMB int64 `json:"max_mb"`
|
||||||
FloorMB int64 `json:"floor_mb"`
|
FloorMB int64 `json:"floor_mb"`
|
||||||
Running bool `json:"running"`
|
Running bool `json:"running"`
|
||||||
|
// HostSwapMB / GuestSwapMB (agent ≥ the R-1192 swap release): the host's swap and this guest's swap allowance.
|
||||||
|
// nil = an older agent (not judged).
|
||||||
|
HostSwapMB *int64 `json:"host_swap_mb,omitempty"`
|
||||||
|
GuestSwapMB *int64 `json:"guest_swap_mb,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// MemoryResizeResult mirrors the agent's POST /guest/memory success body.
|
// MemoryResizeResult mirrors the agent's POST /guest/memory success body.
|
||||||
@@ -722,6 +803,11 @@ func (c *Client) Decommission(ctx context.Context, where string) (DecommissionRe
|
|||||||
return out, err
|
return out, err
|
||||||
}
|
}
|
||||||
if err := refusalError("/disks/decommission", status, env); err != nil {
|
if err := refusalError("/disks/decommission", status, env); err != nil {
|
||||||
|
if status == http.StatusForbidden || status == http.StatusConflict {
|
||||||
|
// R-1063: the agent's two policy refusals (403 a protected role, 409 the whole-guest backup target) are
|
||||||
|
// typed, so the dashboard can say which in plain words. The text is refusalError's, unchanged.
|
||||||
|
return out, &DecommissionRefusedError{Status: status, Reason: refusalReason(env)}
|
||||||
|
}
|
||||||
return out, err
|
return out, err
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(env.Data, &out); err != nil {
|
if err := json.Unmarshal(env.Data, &out); err != nil {
|
||||||
@@ -730,6 +816,17 @@ func (c *Client) Decommission(ctx context.Context, where string) (DecommissionRe
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DecommissionRefusedError is the agent saying no to a decommission: Status 403 (the mount is system/backup by its
|
||||||
|
// role) or 409 (the mount holds the whole-guest backup target). Nothing was done on the host.
|
||||||
|
type DecommissionRefusedError struct {
|
||||||
|
Status int
|
||||||
|
Reason string // the agent's own words, truncated (never a secret: the agent's refusal text)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *DecommissionRefusedError) Error() string {
|
||||||
|
return fmt.Sprintf("agentapi: POST /disks/decommission: HTTP %d: %s", e.Status, e.Reason)
|
||||||
|
}
|
||||||
|
|
||||||
// refusalError converts a non-2xx status or an ok:false envelope into an error that CARRIES the
|
// refusalError converts a non-2xx status or an ok:false envelope into an error that CARRIES the
|
||||||
// agent's reason (truncated; never request bodies or secrets). nil on an accepted 200/202+ok=true.
|
// agent's reason (truncated; never request bodies or secrets). nil on an accepted 200/202+ok=true.
|
||||||
func refusalError(path string, status int, env apiResponse) error {
|
func refusalError(path string, status int, env apiResponse) error {
|
||||||
@@ -737,16 +834,21 @@ func refusalError(path string, status int, env apiResponse) error {
|
|||||||
if accepted && env.OK {
|
if accepted && env.OK {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
reason := truncateErr(env.Error, 300)
|
reason := refusalReason(env)
|
||||||
if reason == "" {
|
|
||||||
reason = "(no reason in agent response)"
|
|
||||||
}
|
|
||||||
if accepted { // 2xx but ok:false — business refusal without an HTTP error code
|
if accepted { // 2xx but ok:false — business refusal without an HTTP error code
|
||||||
return fmt.Errorf("agentapi: POST %s: %s", path, reason)
|
return fmt.Errorf("agentapi: POST %s: %s", path, reason)
|
||||||
}
|
}
|
||||||
return fmt.Errorf("agentapi: POST %s: HTTP %d: %s", path, status, reason)
|
return fmt.Errorf("agentapi: POST %s: HTTP %d: %s", path, status, reason)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// refusalReason is the agent's refusal text as refusalError carries it.
|
||||||
|
func refusalReason(env apiResponse) string {
|
||||||
|
if r := truncateErr(env.Error, 300); r != "" {
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
return "(no reason in agent response)"
|
||||||
|
}
|
||||||
|
|
||||||
// truncateErr mirrors stacks.truncateStr for agent refusal reasons.
|
// truncateErr mirrors stacks.truncateStr for agent refusal reasons.
|
||||||
func truncateErr(s string, maxLen int) string {
|
func truncateErr(s string, maxLen int) string {
|
||||||
if len(s) <= maxLen {
|
if len(s) <= maxLen {
|
||||||
@@ -793,6 +895,9 @@ func (c *Client) FormatDisk(ctx context.Context, device, fstype string, confirme
|
|||||||
// real failure (e.g. the agent's 502 on a mkfs error: "device is mounted"). Returning the zero-value
|
// real failure (e.g. the agent's 502 on a mkfs error: "device is mounted"). Returning the zero-value
|
||||||
// result with a nil error here made a failed destructive format read as a silent SUCCESS in the web
|
// result with a nil error here made a failed destructive format read as a silent SUCCESS in the web
|
||||||
// layer. Surface it as an error so the caller (and the dashboard) report the failure.
|
// layer. Surface it as an error so the caller (and the dashboard) report the failure.
|
||||||
|
if status == http.StatusConflict && strings.Contains(env.Error, "has no durable id") {
|
||||||
|
return out, ErrNoDurableID
|
||||||
|
}
|
||||||
if status < 200 || status >= 300 || !env.OK {
|
if status < 200 || status >= 300 || !env.OK {
|
||||||
msg := strings.TrimSpace(env.Error)
|
msg := strings.TrimSpace(env.Error)
|
||||||
if msg == "" {
|
if msg == "" {
|
||||||
@@ -970,6 +1075,18 @@ func (c *Client) RemoveNetStorage(ctx context.Context, name string) error {
|
|||||||
// status, even on a non-2xx (so callers like FormatDisk can read a 403 refusal body). A transport or
|
// status, even on a non-2xx (so callers like FormatDisk can read a 403 refusal body). A transport or
|
||||||
// envelope-parse failure is still an error; an `ok:false` business refusal is NOT (the data carries it).
|
// envelope-parse failure is still an error; an `ok:false` business refusal is NOT (the data carries it).
|
||||||
func (c *Client) postWithStatus(ctx context.Context, path string, body any) (apiResponse, int, error) {
|
func (c *Client) postWithStatus(ctx context.Context, path string, body any) (apiResponse, int, error) {
|
||||||
|
return c.postWithStatusOn(c.hc, ctx, path, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// postWithStatusTimeout is postWithStatus with its own overall timeout (the escrow claim and confirm, R-1254). It shares
|
||||||
|
// the pinned transport.
|
||||||
|
func (c *Client) postWithStatusTimeout(ctx context.Context, path string, body any, timeout time.Duration) (apiResponse, int, error) {
|
||||||
|
hc := *c.hc
|
||||||
|
hc.Timeout = timeout
|
||||||
|
return c.postWithStatusOn(&hc, ctx, path, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) postWithStatusOn(hc *http.Client, ctx context.Context, path string, body any) (apiResponse, int, error) {
|
||||||
var env apiResponse
|
var env apiResponse
|
||||||
buf, err := json.Marshal(body)
|
buf, err := json.Marshal(body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -982,7 +1099,7 @@ func (c *Client) postWithStatus(ctx context.Context, path string, body any) (api
|
|||||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
resp, err := c.hc.Do(req)
|
resp, err := hc.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logx.Debugf(c.logger, "[agentapi] POST %s failed after %dms: %v", path, time.Since(start).Milliseconds(), err)
|
logx.Debugf(c.logger, "[agentapi] POST %s failed after %dms: %v", path, time.Since(start).Milliseconds(), err)
|
||||||
return env, 0, fmt.Errorf("agentapi: POST %s: %w", path, err)
|
return env, 0, fmt.Errorf("agentapi: POST %s: %w", path, err)
|
||||||
@@ -1065,6 +1182,13 @@ type SmartSummary struct {
|
|||||||
ReallocatedSectors *int `json:"reallocated_sectors"`
|
ReallocatedSectors *int `json:"reallocated_sectors"`
|
||||||
PendingSectors *int `json:"pending_sectors"`
|
PendingSectors *int `json:"pending_sectors"`
|
||||||
OfflineUncorrectable *int `json:"offline_uncorrectable"`
|
OfflineUncorrectable *int `json:"offline_uncorrectable"`
|
||||||
|
// R-330 (agent v0.150.0+): three more SATA raw counters — 187 Reported_Uncorrect, 188
|
||||||
|
// Command_Timeout (vendor-packed on some drives: carried as reported), 199 UDMA_CRC_Error_Count.
|
||||||
|
// nil = unknown (an older agent, an NVMe/USB device, or not reported), never zero. CARRIED ONLY:
|
||||||
|
// no verdict, banner or mail reads them yet — that would change what a household is told.
|
||||||
|
ReportedUncorrect *int64 `json:"reported_uncorrect,omitempty"`
|
||||||
|
CommandTimeout *int64 `json:"command_timeout,omitempty"`
|
||||||
|
UDMACRCErrors *int64 `json:"udma_crc_errors,omitempty"`
|
||||||
// NVMe attributes.
|
// NVMe attributes.
|
||||||
CriticalWarning *int `json:"critical_warning"`
|
CriticalWarning *int `json:"critical_warning"`
|
||||||
MediaErrors *int `json:"media_errors"`
|
MediaErrors *int `json:"media_errors"`
|
||||||
@@ -1183,6 +1307,18 @@ func (c *Client) get(ctx context.Context, path string) (json.RawMessage, error)
|
|||||||
// post issues an authenticated JSON POST and unwraps the {ok,data,error} envelope. The agent
|
// post issues an authenticated JSON POST and unwraps the {ok,data,error} envelope. The agent
|
||||||
// returns 200 or 202 for accepted requests.
|
// returns 200 or 202 for accepted requests.
|
||||||
func (c *Client) post(ctx context.Context, path string, body any) (json.RawMessage, error) {
|
func (c *Client) post(ctx context.Context, path string, body any) (json.RawMessage, error) {
|
||||||
|
return c.postWith(c.hc, ctx, path, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// postSlow is post with its own overall timeout, for the few synchronous routes that outlast the client's 15 s
|
||||||
|
// (POST /host/line-test/run, about 55 s). It shares the pinned transport.
|
||||||
|
func (c *Client) postSlow(ctx context.Context, path string, body any, timeout time.Duration) (json.RawMessage, error) {
|
||||||
|
hc := *c.hc
|
||||||
|
hc.Timeout = timeout
|
||||||
|
return c.postWith(&hc, ctx, path, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) postWith(hc *http.Client, ctx context.Context, path string, body any) (json.RawMessage, error) {
|
||||||
buf, err := json.Marshal(body)
|
buf, err := json.Marshal(body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -1194,7 +1330,7 @@ func (c *Client) post(ctx context.Context, path string, body any) (json.RawMessa
|
|||||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
resp, err := c.hc.Do(req)
|
resp, err := hc.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logx.Debugf(c.logger, "[agentapi] POST %s failed after %dms: %v", path, time.Since(start).Milliseconds(), err)
|
logx.Debugf(c.logger, "[agentapi] POST %s failed after %dms: %v", path, time.Since(start).Milliseconds(), err)
|
||||||
return nil, fmt.Errorf("agentapi: POST %s: %w", path, err)
|
return nil, fmt.Errorf("agentapi: POST %s: %w", path, err)
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package agentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CrashGuardState mirrors the agent's GET /host/crash-guard (R-856, `09` §3 decision 143): what the
|
||||||
|
// host's crash guard (`felhom-crash-guard`, `11` §5.9) recorded about the most recent HOST boot. The
|
||||||
|
// agent reads /var/lib/felhom-crash-guard/state.json (0644) and passes these fields through.
|
||||||
|
//
|
||||||
|
// Present=false: the host has no crash guard or no state yet. An agent that predates the route answers
|
||||||
|
// 404 (a *StatusError) — both mean UNKNOWN, and the controller then keeps its normal boot grace.
|
||||||
|
type CrashGuardState struct {
|
||||||
|
Present bool `json:"present"`
|
||||||
|
LastBootAt string `json:"last_boot_at,omitempty"` // RFC3339 UTC ("2006-01-02T15:04:05Z")
|
||||||
|
LastBootUnclean bool `json:"last_boot_unclean"`
|
||||||
|
Tripped bool `json:"tripped"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CrashGuard calls GET /host/crash-guard.
|
||||||
|
func (c *Client) CrashGuard(ctx context.Context) (CrashGuardState, error) {
|
||||||
|
var out CrashGuardState
|
||||||
|
body, err := c.get(ctx, "/host/crash-guard")
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &out); err != nil {
|
||||||
|
return out, fmt.Errorf("agentapi: decode /host/crash-guard: %w", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package agentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-856: GET /host/crash-guard decodes the crash guard's fields, and an agent that predates the route
|
||||||
|
// surfaces as a typed 404 (the caller reads it as unknown → the normal boot grace).
|
||||||
|
func TestR856_CrashGuardDecodesAndAnOlderAgentIs404(t *testing.T) {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("GET /host/crash-guard", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, _ = w.Write([]byte(`{"ok":true,"data":{"present":true,"last_boot_at":"2026-10-04T12:00:00Z","last_boot_unclean":true,"tripped":false}}`))
|
||||||
|
})
|
||||||
|
s := httptest.NewTLSServer(mux)
|
||||||
|
defer s.Close()
|
||||||
|
c := clientFor(t, s, strings.TrimPrefix(s.URL, "https://"))
|
||||||
|
st, err := c.CrashGuard(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !st.Present || !st.LastBootUnclean || st.LastBootAt != "2026-10-04T12:00:00Z" || st.Tripped {
|
||||||
|
t.Fatalf("state = %+v", st)
|
||||||
|
}
|
||||||
|
|
||||||
|
old := httptest.NewTLSServer(http.NewServeMux())
|
||||||
|
defer old.Close()
|
||||||
|
_, err = clientFor(t, old, strings.TrimPrefix(old.URL, "https://")).CrashGuard(context.Background())
|
||||||
|
var se *StatusError
|
||||||
|
if !errors.As(err, &se) || se.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("an older agent must answer a typed 404, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// R-1063: the agent's two decommission refusals come back TYPED (403 a protected role, 409 the whole-guest backup
|
||||||
|
// target), with the same text as before; any other failure is not that type.
|
||||||
|
func TestDecommission_PolicyRefusalsAreTyped(t *testing.T) {
|
||||||
|
for _, c := range []struct {
|
||||||
|
code int
|
||||||
|
typed bool
|
||||||
|
}{{http.StatusForbidden, true}, {http.StatusConflict, true}, {http.StatusBadGateway, false}} {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("POST /disks/decommission", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(c.code)
|
||||||
|
_, _ = w.Write([]byte(`{"ok":false,"error":"refused for the test"}`))
|
||||||
|
})
|
||||||
|
s := httptest.NewTLSServer(mux)
|
||||||
|
_, err := clientFor(t, s, strings.TrimPrefix(s.URL, "https://")).Decommission(context.Background(), "/mnt/x")
|
||||||
|
s.Close()
|
||||||
|
var dr *DecommissionRefusedError
|
||||||
|
if got := errors.As(err, &dr); got != c.typed {
|
||||||
|
t.Fatalf("HTTP %d: typed=%v, want %v (err %v)", c.code, got, c.typed, err)
|
||||||
|
}
|
||||||
|
if c.typed && (dr.Status != c.code || !strings.Contains(err.Error(), "HTTP "+strconv.Itoa(c.code)+": refused for the test")) {
|
||||||
|
t.Fatalf("HTTP %d: %+v / %q", c.code, dr, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// R-1069: the agent's anti-retarget refusal of a blank format (its exact text, a 409) comes back as ErrNoDurableID;
|
||||||
|
// another 409 does not.
|
||||||
|
func TestFormatDisk_NoDurableIDIsTyped(t *testing.T) {
|
||||||
|
for _, c := range []struct {
|
||||||
|
body string
|
||||||
|
typed bool
|
||||||
|
}{
|
||||||
|
{`{"ok":false,"error":"format refused: device has no durable id to bind the format to (path-only formats are not permitted)","data":{"formatted":false,"data_bearing":false}}`, true},
|
||||||
|
{`{"ok":false,"error":"format refused (device may have changed since inspection): gone","data":{"formatted":false}}`, false},
|
||||||
|
} {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("POST /disks/format", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusConflict)
|
||||||
|
_, _ = w.Write([]byte(c.body))
|
||||||
|
})
|
||||||
|
s := httptest.NewTLSServer(mux)
|
||||||
|
_, err := clientFor(t, s, strings.TrimPrefix(s.URL, "https://")).FormatDisk(context.Background(), "/dev/vdb", "ext4", false, "")
|
||||||
|
s.Close()
|
||||||
|
if got := errors.Is(err, ErrNoDurableID); got != c.typed || err == nil {
|
||||||
|
t.Fatalf("body %s: ErrNoDurableID=%v want %v (err %v)", c.body[:60], got, c.typed, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -59,7 +59,7 @@ type DiskPrior struct {
|
|||||||
//
|
//
|
||||||
// 1. nil / "" / UNKNOWN -> Nincs adat
|
// 1. nil / "" / UNKNOWN -> Nincs adat
|
||||||
// 2. Health == FAILING -> Hiba (drive self-reports)
|
// 2. Health == FAILING -> Hiba (drive self-reports)
|
||||||
// 3. temperature_c >= 60 -> Hiba
|
// 3. temperature_c >= 60 (NOT for NVMe — R-333) -> Hiba
|
||||||
// 4. critical_warning > 0 (NVMe's own flag: a declaration) -> Hiba
|
// 4. critical_warning > 0 (NVMe's own flag: a declaration) -> Hiba
|
||||||
// 5. percentage_used >= 100 -> Hiba
|
// 5. percentage_used >= 100 -> Hiba
|
||||||
// 6. unreadable > 0 AND prior.SawUncorrectable -> Hiba (SUSTAINED)
|
// 6. unreadable > 0 AND prior.SawUncorrectable -> Hiba (SUSTAINED)
|
||||||
@@ -69,7 +69,7 @@ type DiskPrior struct {
|
|||||||
// 10. reallocated > 0 -> Figyelmeztetés
|
// 10. reallocated > 0 -> Figyelmeztetés
|
||||||
// 11. media_errors > 0 -> Figyelmeztetés
|
// 11. media_errors > 0 -> Figyelmeztetés
|
||||||
// 12. percentage_used >= 90 -> Figyelmeztetés
|
// 12. percentage_used >= 90 -> Figyelmeztetés
|
||||||
// 13. temperature_c >= 55 -> Figyelmeztetés
|
// 13. temperature_c >= 55 (NOT for NVMe — R-333) -> Figyelmeztetés
|
||||||
// 14. otherwise -> Rendben
|
// 14. otherwise -> Rendben
|
||||||
//
|
//
|
||||||
// WHY rows 2-8 exist at all: smart_status.passed CANNOT fail on unreadable sectors. Attributes 187,
|
// WHY rows 2-8 exist at all: smart_status.passed CANNOT fail on unreadable sectors. Attributes 187,
|
||||||
@@ -82,6 +82,12 @@ type DiskPrior struct {
|
|||||||
// drive sustain fires a full day earlier (12 Aug) than the count threshold (13 Aug). Row 8 exists for
|
// drive sustain fires a full day earlier (12 Aug) than the count threshold (13 Aug). Row 8 exists for
|
||||||
// a box that was powered off or restarted across the sustain window and so has no prior.
|
// a box that was powered off or restarted across the sustain window and so has no prior.
|
||||||
//
|
//
|
||||||
|
// WHY rows 3 and 13 skip an NVMe drive (R-333, `09` §3 decision 206, v0.308.0): the 55/60 °C bands are
|
||||||
|
// SPINNING-DISK bands. A healthy NVMe idles at 53 °C (measured on demo-hp) and routinely passes 60 °C
|
||||||
|
// under load with no fault, so the bands would tell a household "Hiba" about a working drive. An NVMe
|
||||||
|
// drive judges its own heat: critical_warning bit 1 is the device's temperature alarm, and row 4 still
|
||||||
|
// turns any critical_warning bit into Hiba. Pinned by TestDiskVerdict_NVMeHasNoHeatBand.
|
||||||
|
//
|
||||||
// Pure: no clock, no I/O, no logging. Everything it needs arrives as an argument.
|
// Pure: no clock, no I/O, no logging. Everything it needs arrives as an argument.
|
||||||
func DiskVerdictFor(s *SmartSummary, prior DiskPrior) DiskVerdict {
|
func DiskVerdictFor(s *SmartSummary, prior DiskPrior) DiskVerdict {
|
||||||
// 1 — no data. Never alarms.
|
// 1 — no data. Never alarms.
|
||||||
@@ -94,8 +100,9 @@ func DiskVerdictFor(s *SmartSummary, prior DiskPrior) DiskVerdict {
|
|||||||
}
|
}
|
||||||
// Health == PASSED (or any non-empty non-FAILING value we treat as passing): inspect the counters,
|
// Health == PASSED (or any non-empty non-FAILING value we treat as passing): inspect the counters,
|
||||||
// because the overall verdict is structurally unable to report this class of fault.
|
// because the overall verdict is structurally unable to report this class of fault.
|
||||||
|
nvme := IsNVMe(s)
|
||||||
switch {
|
switch {
|
||||||
case atLeast(s.TemperatureC, TemperatureFailC): // 3
|
case !nvme && atLeast(s.TemperatureC, TemperatureFailC): // 3
|
||||||
return DiskVerdictFail
|
return DiskVerdictFail
|
||||||
case positive(s.CriticalWarning): // 4
|
case positive(s.CriticalWarning): // 4
|
||||||
return DiskVerdictFail
|
return DiskVerdictFail
|
||||||
@@ -118,7 +125,7 @@ func DiskVerdictFor(s *SmartSummary, prior DiskPrior) DiskVerdict {
|
|||||||
return DiskVerdictWarn
|
return DiskVerdictWarn
|
||||||
case atLeast(s.PercentageUsed, percentageUsedWarn): // 12
|
case atLeast(s.PercentageUsed, percentageUsedWarn): // 12
|
||||||
return DiskVerdictWarn
|
return DiskVerdictWarn
|
||||||
case atLeast(s.TemperatureC, temperatureWarnC): // 13
|
case !nvme && atLeast(s.TemperatureC, temperatureWarnC): // 13
|
||||||
return DiskVerdictWarn
|
return DiskVerdictWarn
|
||||||
}
|
}
|
||||||
return DiskVerdictOK // 14
|
return DiskVerdictOK // 14
|
||||||
@@ -190,12 +197,21 @@ func DegradedAttributes(s *SmartSummary) []string {
|
|||||||
if atLeast(s.PercentageUsed, percentageUsedWarn) {
|
if atLeast(s.PercentageUsed, percentageUsedWarn) {
|
||||||
out = append(out, "elhasználódás")
|
out = append(out, "elhasználódás")
|
||||||
}
|
}
|
||||||
// Newly able to trigger a verdict on its own (rows 3 and 13), so it must be nameable.
|
// Newly able to trigger a verdict on its own (rows 3 and 13), so it must be nameable. Not for an
|
||||||
if atLeast(s.TemperatureC, temperatureWarnC) {
|
// NVMe drive (R-333): its heat never triggers a verdict, so naming it would give a wrong reason.
|
||||||
|
if !IsNVMe(s) && atLeast(s.TemperatureC, temperatureWarnC) {
|
||||||
out = append(out, "hőmérséklet")
|
out = append(out, "hőmérséklet")
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsNVMe reports whether the summary came from an NVMe drive. The agent fills critical_warning,
|
||||||
|
// percentage_used and media_errors ONLY from smartctl's nvme_smart_health_information_log
|
||||||
|
// (felhom-agent internal/storage/smart.go), so any of them present means NVMe; a SATA or USB drive
|
||||||
|
// carries none of them.
|
||||||
|
func IsNVMe(s *SmartSummary) bool {
|
||||||
|
return s != nil && (s.CriticalWarning != nil || s.PercentageUsed != nil || s.MediaErrors != nil)
|
||||||
|
}
|
||||||
|
|
||||||
func positive(p *int) bool { return p != nil && *p > 0 }
|
func positive(p *int) bool { return p != nil && *p > 0 }
|
||||||
func atLeast(p *int, n int) bool { return p != nil && *p >= n }
|
func atLeast(p *int, n int) bool { return p != nil && *p >= n }
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package agentapi
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
// R-333 (`09` §3 decision 206): no heat band for an NVMe drive. Both directions, because "fixed" means
|
||||||
|
// one kind of drive stopped alarming on heat and the other did not, and the drive's own alarm stays.
|
||||||
|
func TestDiskVerdict_NVMeHasNoHeatBand(t *testing.T) {
|
||||||
|
noPrior := DiskPrior{}
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
in *SmartSummary
|
||||||
|
want DiskVerdict
|
||||||
|
}{
|
||||||
|
// A healthy NVMe under load: 72 °C, the device raises no flag. No heat alarm.
|
||||||
|
{"hot NVMe, no critical warning → ok", &SmartSummary{Health: SmartPassed, TemperatureC: ip(72), CriticalWarning: ip(0), PercentageUsed: ip(3), MediaErrors: ip(0)}, DiskVerdictOK},
|
||||||
|
{"warm NVMe 56 °C, no critical warning → ok", &SmartSummary{Health: SmartPassed, TemperatureC: ip(56), CriticalWarning: ip(0)}, DiskVerdictOK},
|
||||||
|
// The same drive with its own temperature bit set (critical_warning bit 1 = 0x02): Hiba.
|
||||||
|
{"hot NVMe with critical_warning temperature bit → fail", &SmartSummary{Health: SmartPassed, TemperatureC: ip(72), CriticalWarning: ip(2)}, DiskVerdictFail},
|
||||||
|
{"cool NVMe with critical_warning → fail", &SmartSummary{Health: SmartPassed, TemperatureC: ip(40), CriticalWarning: ip(1)}, DiskVerdictFail},
|
||||||
|
// Spinning/SATA drives keep their 55/60 °C bands, unchanged.
|
||||||
|
{"SATA 56 °C → warn", &SmartSummary{Health: SmartPassed, TemperatureC: ip(56), ReallocatedSectors: ip(0)}, DiskVerdictWarn},
|
||||||
|
{"SATA 60 °C → fail", &SmartSummary{Health: SmartPassed, TemperatureC: ip(60), ReallocatedSectors: ip(0)}, DiskVerdictFail},
|
||||||
|
{"SATA 54 °C → ok", &SmartSummary{Health: SmartPassed, TemperatureC: ip(54)}, DiskVerdictOK},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
if got := DiskVerdictFor(c.in, noPrior); got != c.want {
|
||||||
|
t.Errorf("%s: DiskVerdictFor = %s, want %s", c.name, got.Label(), c.want.Label())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The alert body must not name heat as the reason for an NVMe drive.
|
||||||
|
for _, a := range DegradedAttributes(&SmartSummary{Health: SmartPassed, TemperatureC: ip(72), CriticalWarning: ip(2)}) {
|
||||||
|
if a == "hőmérséklet" {
|
||||||
|
t.Error("an NVMe alert names temperature as an attribute; the verdict fired on the drive's own warning")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Controller-driven escrow ceremony client methods (v0.127.0, agent ≥ v0.88.0). The claim call
|
// Controller-driven escrow ceremony client methods (v0.127.0, agent ≥ v0.88.0). The claim call
|
||||||
@@ -92,31 +93,70 @@ func (c *Client) EscrowCeremonyStatus(ctx context.Context) (EscrowCeremonyStatus
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EscrowClaim is a claimed recovery code. ConfirmRequired (agent ≥ 0.160.0, R-1151): the code's package reaches the
|
||||||
|
// hub only when EscrowCeremonyConfirm brings back the words at Positions (1-based); an older agent answers without
|
||||||
|
// it — its package is already on the hub, and no confirm is needed.
|
||||||
|
type EscrowClaim struct {
|
||||||
|
Code string
|
||||||
|
ConfirmRequired bool
|
||||||
|
Positions []int
|
||||||
|
}
|
||||||
|
|
||||||
// EscrowCeremonyClaim performs the ONE-SHOT R claim. Returns the recovery code + the agent's
|
// EscrowCeremonyClaim performs the ONE-SHOT R claim. Returns the recovery code + the agent's
|
||||||
// HTTP status (410 = already claimed / expired — the wizard's void state). The code must never
|
// HTTP status (410 = already claimed / expired — the wizard's void state). The code must never
|
||||||
// be logged, persisted, or placed anywhere but the claim XHR response; the error path carries
|
// be logged, persisted, or placed anywhere but the claim XHR response; the error path carries
|
||||||
// the agent's reason text, never the code.
|
// the agent's reason text, never the code.
|
||||||
func (c *Client) EscrowCeremonyClaim(ctx context.Context) (string, int, error) {
|
//
|
||||||
env, status, err := c.postWithStatus(ctx, "/escrow/ceremony/claim", struct{}{})
|
// R-1151: the claim asks the agent to keep the new package until the household typed the code back
|
||||||
|
// (`defer_upload`). An agent older than 0.160.0 ignores the body and uploads as before.
|
||||||
|
// escrowCallTimeout bounds the claim and the confirm (R-1254 H2). The agent may take its whole upload timeout (30 s)
|
||||||
|
// plus its question to the hub (15 s) before it answers; the client's own 15 s used to abandon the call while the
|
||||||
|
// agent went on — a claim abandoned that way could still store the package, and its code reached nobody. 60 s
|
||||||
|
// outlasts both (TestR1254_ClaimAndConfirmOutwaitTheAgentsUpload; the agent side: escrowUploadTimeout,
|
||||||
|
// escrowHoldTimeout in felhom-agent internal/localapi/escrow_ceremony.go — if either grows, this must too).
|
||||||
|
var escrowCallTimeout = 60 * time.Second
|
||||||
|
|
||||||
|
func (c *Client) EscrowCeremonyClaim(ctx context.Context) (EscrowClaim, int, error) {
|
||||||
|
env, status, err := c.postWithStatusTimeout(ctx, "/escrow/ceremony/claim", map[string]bool{"defer_upload": true}, escrowCallTimeout)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", status, err
|
return EscrowClaim{}, status, err
|
||||||
}
|
}
|
||||||
if status == http.StatusGone {
|
if status == http.StatusGone {
|
||||||
return "", status, fmt.Errorf("agentapi: POST /escrow/ceremony/claim: gone (claimed or expired)")
|
return EscrowClaim{}, status, fmt.Errorf("agentapi: POST /escrow/ceremony/claim: gone (claimed or expired)")
|
||||||
}
|
}
|
||||||
if err := refusalError("/escrow/ceremony/claim", status, env); err != nil {
|
if err := refusalError("/escrow/ceremony/claim", status, env); err != nil {
|
||||||
return "", status, err
|
return EscrowClaim{}, status, err
|
||||||
}
|
}
|
||||||
var out struct {
|
var out struct {
|
||||||
RecoveryCode string `json:"recovery_code"`
|
RecoveryCode string `json:"recovery_code"`
|
||||||
|
ConfirmRequired bool `json:"confirm_required"`
|
||||||
|
VerifyPositions []int `json:"verify_positions"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(env.Data, &out); err != nil {
|
if err := json.Unmarshal(env.Data, &out); err != nil {
|
||||||
return "", status, fmt.Errorf("agentapi: decode /escrow/ceremony/claim: %w", err)
|
return EscrowClaim{}, status, fmt.Errorf("agentapi: decode /escrow/ceremony/claim: %w", err)
|
||||||
}
|
}
|
||||||
if out.RecoveryCode == "" {
|
if out.RecoveryCode == "" {
|
||||||
return "", status, fmt.Errorf("agentapi: /escrow/ceremony/claim returned no code")
|
return EscrowClaim{}, status, fmt.Errorf("agentapi: /escrow/ceremony/claim returned no code")
|
||||||
}
|
}
|
||||||
return out.RecoveryCode, status, nil
|
if out.ConfirmRequired && len(out.VerifyPositions) != 2 {
|
||||||
|
return EscrowClaim{}, status, fmt.Errorf("agentapi: /escrow/ceremony/claim asks for a confirmation without two positions")
|
||||||
|
}
|
||||||
|
return EscrowClaim{Code: out.RecoveryCode, ConfirmRequired: out.ConfirmRequired, Positions: out.VerifyPositions}, status, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EscrowCeremonyConfirm sends the two words the household typed back (R-1151, agent ≥ 0.160.0); on success the agent
|
||||||
|
// has stored the new package on the hub. The status is returned for the caller to classify: 422 the words do not
|
||||||
|
// match (still waiting), 410 the window ran out, 404 nothing waits (superseded, restarted), 502 the hub failed (still
|
||||||
|
// waiting). The words are part of the recovery code — never logged.
|
||||||
|
func (c *Client) EscrowCeremonyConfirm(ctx context.Context, words []string) (int, error) {
|
||||||
|
env, status, err := c.postWithStatusTimeout(ctx, "/escrow/ceremony/confirm", map[string][]string{"words": words}, escrowCallTimeout)
|
||||||
|
if err != nil {
|
||||||
|
return status, err
|
||||||
|
}
|
||||||
|
if err := refusalError("/escrow/ceremony/confirm", status, env); err != nil {
|
||||||
|
return status, err
|
||||||
|
}
|
||||||
|
return status, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// RecoverOffsiteRepoPassword asks the agent to open this host's hub-held sealed bundle with the
|
// RecoverOffsiteRepoPassword asks the agent to open this host's hub-held sealed bundle with the
|
||||||
@@ -210,6 +250,10 @@ const (
|
|||||||
// out loud — a true sentence about our own incuriosity that a customer reads as a statement about
|
// out loud — a true sentence about our own incuriosity that a customer reads as a statement about
|
||||||
// their code.
|
// their code.
|
||||||
RecoveryCodeOpensRetained
|
RecoveryCodeOpensRetained
|
||||||
|
// RecoveryOlderUnchecked — the code did not open the current package, no earlier package opened it, and
|
||||||
|
// NOT every earlier package the hub holds was tried (R-304, agent 424). So whether the code is wrong is
|
||||||
|
// NOT known. The customer must not be told to check their typing as if it were.
|
||||||
|
RecoveryOlderUnchecked
|
||||||
)
|
)
|
||||||
|
|
||||||
// ClassifyRecoveryFailure maps an unlock error to its class, from the VALUE and never the text.
|
// ClassifyRecoveryFailure maps an unlock error to its class, from the VALUE and never the text.
|
||||||
@@ -251,6 +295,12 @@ func ClassifyRecoveryFailure(err error, trustRefusal, trustRetained bool) Recove
|
|||||||
return RecoveryCodeOpensRetained
|
return RecoveryCodeOpensRetained
|
||||||
}
|
}
|
||||||
return RecoveryUnknown
|
return RecoveryUnknown
|
||||||
|
case http.StatusFailedDependency:
|
||||||
|
// R-304. NOT version-gated, deliberately — unlike 400 and 422 above. Those two make a claim about the
|
||||||
|
// customer's code (wrong / correct), so a status we did not design must not be read as one. This class
|
||||||
|
// claims only „not everything was checked; contact support", which is the same direction as
|
||||||
|
// RecoveryUnknown: misreading a stray 424 here can never accuse anyone.
|
||||||
|
return RecoveryOlderUnchecked
|
||||||
case http.StatusBadRequest:
|
case http.StatusBadRequest:
|
||||||
if trustRefusal {
|
if trustRefusal {
|
||||||
return RecoveryAskedAndRefused
|
return RecoveryAskedAndRefused
|
||||||
@@ -276,6 +326,8 @@ func (f RecoveryFailure) String() string {
|
|||||||
return "bundle-too-old"
|
return "bundle-too-old"
|
||||||
case RecoveryCodeOpensRetained:
|
case RecoveryCodeOpensRetained:
|
||||||
return "code-opens-retained"
|
return "code-opens-retained"
|
||||||
|
case RecoveryOlderUnchecked:
|
||||||
|
return "older-unchecked"
|
||||||
default:
|
default:
|
||||||
return "unknown"
|
return "unknown"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package agentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1151 — the claim asks the agent to keep the package until the words come back, and reads the agent's answer;
|
||||||
|
// the confirm carries the two words. An agent older than 0.160.0 answers without confirm_required.
|
||||||
|
func TestEscrowClaimAndConfirm_R1151(t *testing.T) {
|
||||||
|
var claimBody map[string]any
|
||||||
|
var confirmBody map[string][]string
|
||||||
|
newAgent := true
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("POST /escrow/ceremony/claim", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
claimBody = nil
|
||||||
|
_ = json.NewDecoder(r.Body).Decode(&claimBody)
|
||||||
|
if newAgent {
|
||||||
|
_, _ = w.Write([]byte(`{"ok":true,"data":{"recovery_code":"a-b-c","confirm_required":true,"verify_positions":[1,3]}}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = w.Write([]byte(`{"ok":true,"data":{"recovery_code":"a-b-c"}}`))
|
||||||
|
})
|
||||||
|
mux.HandleFunc("POST /escrow/ceremony/confirm", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_ = json.NewDecoder(r.Body).Decode(&confirmBody)
|
||||||
|
if confirmBody["words"][0] != "a" {
|
||||||
|
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||||
|
_, _ = w.Write([]byte(`{"ok":false,"error":"the words do not match the recovery code"}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = w.Write([]byte(`{"ok":true,"data":{"uploaded":true}}`))
|
||||||
|
})
|
||||||
|
s := httptest.NewTLSServer(mux)
|
||||||
|
defer s.Close()
|
||||||
|
c := clientFor(t, s, strings.TrimPrefix(s.URL, "https://"))
|
||||||
|
|
||||||
|
claim, status, err := c.EscrowCeremonyClaim(context.Background())
|
||||||
|
if err != nil || status != http.StatusOK || claim.Code != "a-b-c" || !claim.ConfirmRequired || len(claim.Positions) != 2 || claim.Positions[1] != 3 {
|
||||||
|
t.Fatalf("claim: %+v %d %v", claim, status, err)
|
||||||
|
}
|
||||||
|
if claimBody["defer_upload"] != true {
|
||||||
|
t.Fatalf("the claim did not ask the agent to wait for the words: body %v", claimBody)
|
||||||
|
}
|
||||||
|
if st, err := c.EscrowCeremonyConfirm(context.Background(), []string{"a", "c"}); err != nil || st != http.StatusOK {
|
||||||
|
t.Fatalf("confirm: %d %v", st, err)
|
||||||
|
}
|
||||||
|
if strings.Join(confirmBody["words"], ",") != "a,c" {
|
||||||
|
t.Fatalf("confirm sent %v", confirmBody)
|
||||||
|
}
|
||||||
|
if st, err := c.EscrowCeremonyConfirm(context.Background(), []string{"x", "c"}); err == nil || st != http.StatusUnprocessableEntity {
|
||||||
|
t.Fatalf("a wrong word must come back as a 422 error: %d %v", st, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
newAgent = false // agent 0.159.2: no confirm request
|
||||||
|
claim, _, err = c.EscrowCeremonyClaim(context.Background())
|
||||||
|
if err != nil || claim.ConfirmRequired || claim.Code != "a-b-c" {
|
||||||
|
t.Fatalf("claim on an old agent: %+v %v", claim, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -83,6 +83,16 @@ const FeatureRecoveryFailureClass Feature = "recovery_failure_class"
|
|||||||
// for two months, and it heals itself when the agent updates.
|
// for two months, and it heals itself when the agent updates.
|
||||||
const FeatureRetainedRecoveryClass Feature = "retained_recovery_class"
|
const FeatureRetainedRecoveryClass Feature = "retained_recovery_class"
|
||||||
|
|
||||||
|
// FeatureHostPowerOff is the household power-off (R-998, agent v0.155.0): POST /host/poweroff. A POST that switches
|
||||||
|
// the machine off cannot be probed, so the VERSION decides. The settings card hides only on a definite SupportNo; on
|
||||||
|
// Unknown it stays, and an old agent's 404 is answered with the update sentence.
|
||||||
|
const FeatureHostPowerOff Feature = "host_poweroff"
|
||||||
|
|
||||||
|
// FeatureSameDisk — POST /disks/same-disk (agent v0.157.0, felhom.eu architecture/16-storage-physical-identity.md
|
||||||
|
// §4): the agent's physical-disk verdict for two guest paths. Below it the Tier-2 runner keeps the old st_dev
|
||||||
|
// rule (backup.Manager.diskRelation), logged once.
|
||||||
|
const FeatureSameDisk Feature = "same_disk"
|
||||||
|
|
||||||
// SupportState is a probe verdict. The zero value is SupportUnknown (fail-open: unknown never
|
// SupportState is a probe verdict. The zero value is SupportUnknown (fail-open: unknown never
|
||||||
// refuses — the existing agent-error paths speak honestly when the agent is down).
|
// refuses — the existing agent-error paths speak honestly when the agent is down).
|
||||||
type SupportState int
|
type SupportState int
|
||||||
@@ -159,6 +169,13 @@ var featureProbes = map[Feature]func(ctx context.Context, p SupportProber) error
|
|||||||
FeatureRetainedRecoveryClass: func(ctx context.Context, p SupportProber) error {
|
FeatureRetainedRecoveryClass: func(ctx context.Context, p SupportProber) error {
|
||||||
return errNoRecoveryProbe
|
return errNoRecoveryProbe
|
||||||
},
|
},
|
||||||
|
// R-998: probing would switch the machine off. The row must exist (table-gap rule above).
|
||||||
|
FeatureHostPowerOff: func(ctx context.Context, p SupportProber) error {
|
||||||
|
return errNoRecoveryProbe
|
||||||
|
},
|
||||||
|
FeatureSameDisk: func(ctx context.Context, p SupportProber) error {
|
||||||
|
return errNoRecoveryProbe // not probeable: decided by the version header alone
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// errNoMemoryProbe classifies to SupportUnknown (not a *StatusError 404), so a prober that cannot be
|
// errNoMemoryProbe classifies to SupportUnknown (not a *StatusError 404), so a prober that cannot be
|
||||||
@@ -192,6 +209,11 @@ var featureMinAgent = map[Feature]string{
|
|||||||
// screen must keep saying it cannot tell the two apart — which was true, and is what this gate
|
// screen must keep saying it cannot tell the two apart — which was true, and is what this gate
|
||||||
// preserves for boxes that have not updated yet.
|
// preserves for boxes that have not updated yet.
|
||||||
FeatureRetainedRecoveryClass: "0.129.0",
|
FeatureRetainedRecoveryClass: "0.129.0",
|
||||||
|
|
||||||
|
// R-998 — POST /host/poweroff, the household's „A gép kikapcsolása".
|
||||||
|
FeatureHostPowerOff: "0.155.0",
|
||||||
|
|
||||||
|
FeatureSameDisk: "0.157.0",
|
||||||
}
|
}
|
||||||
|
|
||||||
// MinAgentFor returns the declared minimum agent version for a feature ("" when the feature has no
|
// MinAgentFor returns the declared minimum agent version for a feature ("" when the feature has no
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package agentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GuestOOMKillsState mirrors the agent's GET /guest/oom-kills (R-528, agent ≥ the R-528 commit): the kernel's oom_kill
|
||||||
|
// counter of each of THIS guest's containers, read on the host — Docker's own OOMKilled flag can stay false inside an
|
||||||
|
// LXC guest. Containers maps the full 64-hex container id to the count for the container's current run.
|
||||||
|
// Available=false: the guest has no cgroup folder the host can read. An agent that predates the route answers 404 (a
|
||||||
|
// *StatusError) — the controller then keeps Docker's flag only.
|
||||||
|
type GuestOOMKillsState struct {
|
||||||
|
VMID int `json:"vmid"`
|
||||||
|
Available bool `json:"available"`
|
||||||
|
Containers map[string]int64 `json:"containers"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GuestOOMKills calls GET /guest/oom-kills.
|
||||||
|
func (c *Client) GuestOOMKills(ctx context.Context) (GuestOOMKillsState, error) {
|
||||||
|
var out GuestOOMKillsState
|
||||||
|
body, err := c.get(ctx, "/guest/oom-kills")
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &out); err != nil {
|
||||||
|
return out, fmt.Errorf("agentapi: decode /guest/oom-kills: %w", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package agentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/logx"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ── POST /host/poweroff (R-998, agent >= 0.155.0, felhom.eu documentation/architecture/14-host-power-off.md) ──
|
||||||
|
//
|
||||||
|
// The household's „A gép kikapcsolása". The agent answers 202 (it shuts this guest down, then the host) or 409
|
||||||
|
// with a machine-readable reason. Unlike post(), the 409 BODY matters here: the dashboard tells the household
|
||||||
|
// WHY (a backup runs, too soon after start, already asked…), so this call reads it.
|
||||||
|
|
||||||
|
// Agent refusal reasons (stable wire values; mirror felhom-agent internal/localapi/hostpoweroff.go).
|
||||||
|
const (
|
||||||
|
PowerOffTooSoon = "too_soon_after_boot"
|
||||||
|
PowerOffAlreadyAsked = "already_requested_this_boot"
|
||||||
|
PowerOffBackup = "backup_running"
|
||||||
|
PowerOffRestoreTest = "restore_test_running"
|
||||||
|
PowerOffOSUpdate = "os_update_running"
|
||||||
|
PowerOffCtrlUpdate = "controller_update_running"
|
||||||
|
PowerOffDrive = "drive_operation_running"
|
||||||
|
PowerOffEscrow = "escrow_ceremony_running"
|
||||||
|
PowerOffBusy = "host_busy"
|
||||||
|
PowerOffOtherGuests = "other_guests_running"
|
||||||
|
PowerOffUnknown = "state_unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PowerOffRefused is the agent's 409: Reason is one of the constants above (or a newer one), Detail is for the log.
|
||||||
|
type PowerOffRefused struct {
|
||||||
|
Reason string
|
||||||
|
Detail string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *PowerOffRefused) Error() string {
|
||||||
|
return "agent refused the power-off: " + e.Reason + " (" + e.Detail + ")"
|
||||||
|
}
|
||||||
|
|
||||||
|
// HostPowerOff asks the agent to shut this guest down and power the host off. nil = accepted (the box goes down
|
||||||
|
// within minutes). A *PowerOffRefused = the agent said no, with its reason. A *StatusError 404 = an agent that
|
||||||
|
// predates the route.
|
||||||
|
func (c *Client) HostPowerOff(ctx context.Context) error {
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/host/poweroff", bytes.NewReader([]byte("{}")))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
start := time.Now()
|
||||||
|
resp, err := c.hc.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("agentapi: POST /host/poweroff: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
c.noteAgentVersion(resp)
|
||||||
|
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
|
||||||
|
logx.Debugf(c.logger, "[agentapi] POST /host/poweroff -> %d (%dms)", resp.StatusCode, time.Since(start).Milliseconds())
|
||||||
|
switch resp.StatusCode {
|
||||||
|
case http.StatusAccepted, http.StatusOK:
|
||||||
|
return nil
|
||||||
|
case http.StatusConflict:
|
||||||
|
var env struct {
|
||||||
|
Data struct {
|
||||||
|
Reason string `json:"reason"`
|
||||||
|
Detail string `json:"detail"`
|
||||||
|
} `json:"data"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal(raw, &env) != nil || env.Data.Reason == "" {
|
||||||
|
return &PowerOffRefused{Reason: PowerOffUnknown, Detail: "unreadable 409 body"}
|
||||||
|
}
|
||||||
|
return &PowerOffRefused{Reason: env.Data.Reason, Detail: env.Data.Detail}
|
||||||
|
default:
|
||||||
|
return &StatusError{Method: http.MethodPost, Path: "/host/poweroff", Code: resp.StatusCode}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsPowerOffRefused returns the refusal, if err is one.
|
||||||
|
func IsPowerOffRefused(err error) (*PowerOffRefused, bool) {
|
||||||
|
var r *PowerOffRefused
|
||||||
|
ok := errors.As(err, &r)
|
||||||
|
return r, ok
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package agentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LineTestState mirrors the agent's GET /host/line-test (agent ≥ 0.164.0; felhom.eu R-1247): the host's weekly upload
|
||||||
|
// line test — a 10-second iperf3 upload to ep0 inside the offsite tunnel, best of three runs, as ep0's server counted
|
||||||
|
// it. Present=false: never measured (no tunnel, not yet due, or disabled). An agent before the route answers 404 (a
|
||||||
|
// *StatusError); all three mean UNKNOWN, and the controller then sets no qBittorrent limit.
|
||||||
|
type LineTestState struct {
|
||||||
|
Present bool `json:"present"`
|
||||||
|
Mbps float64 `json:"mbps,omitempty"`
|
||||||
|
MeasuredAt string `json:"measured_at,omitempty"` // RFC3339 UTC
|
||||||
|
Method string `json:"method,omitempty"`
|
||||||
|
// WaitingForQuiet (agent ≥ 0.165.0, R-1250): a test is due and could start now, but the host's uplink has not been
|
||||||
|
// quiet for 10 minutes. With a seeding torrent app the controller then holds the app's limit and calls LineTestRun.
|
||||||
|
WaitingForQuiet bool `json:"waiting_for_quiet,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LineTestRunResult mirrors POST /host/line-test/run. OK=false with Refused: nothing ran (not-due, outside-window,
|
||||||
|
// tries-used, no-tunnel, heavy-op, not-quiet, server-busy); OK=false without it: the runs failed.
|
||||||
|
type LineTestRunResult struct {
|
||||||
|
OK bool `json:"ok"`
|
||||||
|
Mbps float64 `json:"mbps,omitempty"`
|
||||||
|
RunsMbps []float64 `json:"runs_mbps,omitempty"`
|
||||||
|
Refused string `json:"refused,omitempty"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LineTestRunTimeout bounds the synchronous request: about 55 s on the agent (5 s settle, 10 s quiet check, three
|
||||||
|
// 10-second runs 5 s apart), each run itself bounded at 25 s.
|
||||||
|
const LineTestRunTimeout = 2 * time.Minute
|
||||||
|
|
||||||
|
// LineTestRun calls POST /host/line-test/run (R-1250): a test on request while the caller holds its torrent app's
|
||||||
|
// upload down. An agent before the route answers 404 (*StatusError).
|
||||||
|
func (c *Client) LineTestRun(ctx context.Context) (LineTestRunResult, error) {
|
||||||
|
var out LineTestRunResult
|
||||||
|
body, err := c.postSlow(ctx, "/host/line-test/run", struct{}{}, LineTestRunTimeout)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &out); err != nil {
|
||||||
|
return out, fmt.Errorf("agentapi: decode /host/line-test/run: %w", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LineTest calls GET /host/line-test.
|
||||||
|
func (c *Client) LineTest(ctx context.Context) (LineTestState, error) {
|
||||||
|
var out LineTestState
|
||||||
|
body, err := c.get(ctx, "/host/line-test")
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &out); err != nil {
|
||||||
|
return out, fmt.Errorf("agentapi: decode /host/line-test: %w", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MeasuredAtTime parses MeasuredAt (zero time when absent or garbled).
|
||||||
|
func (s LineTestState) MeasuredAtTime() time.Time {
|
||||||
|
t, _ := time.Parse(time.RFC3339, s.MeasuredAt)
|
||||||
|
return t
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package agentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1247: GET /host/line-test decodes the agent's weekly line test, and an agent before the route is a typed 404 (the
|
||||||
|
// controller reads it as „not measured" → no qBittorrent limit).
|
||||||
|
func TestLineTestDecodesAndAnOlderAgentIs404(t *testing.T) {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("GET /host/line-test", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, _ = w.Write([]byte(`{"ok":true,"data":{"present":true,"mbps":90.7,"measured_at":"2026-10-24T06:31:00Z","method":"iperf3-tunnel"}}`))
|
||||||
|
})
|
||||||
|
s := httptest.NewTLSServer(mux)
|
||||||
|
defer s.Close()
|
||||||
|
st, err := clientFor(t, s, strings.TrimPrefix(s.URL, "https://")).LineTest(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !st.Present || st.Mbps != 90.7 || !st.MeasuredAtTime().Equal(time.Date(2026, 10, 24, 6, 31, 0, 0, time.UTC)) {
|
||||||
|
t.Fatalf("state = %+v", st)
|
||||||
|
}
|
||||||
|
old := httptest.NewTLSServer(http.NewServeMux())
|
||||||
|
defer old.Close()
|
||||||
|
_, err = clientFor(t, old, strings.TrimPrefix(old.URL, "https://")).LineTest(context.Background())
|
||||||
|
var se *StatusError
|
||||||
|
if !errors.As(err, &se) || se.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("an older agent must answer a typed 404, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// R-1250: the request decodes its outcome, waiting_for_quiet decodes, and the request outlasts the client's own
|
||||||
|
// timeout (the agent answers after about 55 s; the client's default is 15 s).
|
||||||
|
func TestLineTestRunOutlastsTheClientTimeout(t *testing.T) {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("GET /host/line-test", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, _ = w.Write([]byte(`{"ok":true,"data":{"present":false,"waiting_for_quiet":true}}`))
|
||||||
|
})
|
||||||
|
mux.HandleFunc("POST /host/line-test/run", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
time.Sleep(300 * time.Millisecond)
|
||||||
|
_, _ = w.Write([]byte(`{"ok":true,"data":{"ok":true,"mbps":93.5,"runs_mbps":[92,93.5,93]}}`))
|
||||||
|
})
|
||||||
|
s := httptest.NewTLSServer(mux)
|
||||||
|
defer s.Close()
|
||||||
|
c := clientFor(t, s, strings.TrimPrefix(s.URL, "https://"))
|
||||||
|
st, err := c.LineTest(context.Background())
|
||||||
|
if err != nil || st.Present || !st.WaitingForQuiet {
|
||||||
|
t.Fatalf("GET = %+v %v, want present:false waiting_for_quiet:true", st, err)
|
||||||
|
}
|
||||||
|
c.hc.Timeout = 100 * time.Millisecond // stands in for the 15 s default against a 55 s answer
|
||||||
|
if _, err := c.post(context.Background(), "/host/line-test/run", struct{}{}); err == nil {
|
||||||
|
t.Fatal("the plain POST should time out here — the seam does not test anything")
|
||||||
|
}
|
||||||
|
res, err := c.LineTestRun(context.Background())
|
||||||
|
if err != nil || !res.OK || res.Mbps != 93.5 || len(res.RunsMbps) != 3 {
|
||||||
|
t.Fatalf("LineTestRun = %+v %v", res, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package agentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// OperatorReboot calls GET /guest/operator-reboot (D65 = A, agent ≥ the reboot_guest commit): the time the operator
|
||||||
|
// rebooted THIS guest from the hub, when it is less than a day old; the zero time when there is none. An agent that
|
||||||
|
// predates the route answers 404 (a *StatusError) — such an agent cannot reboot from the hub either, so there is
|
||||||
|
// nothing to show and no MinAgent is needed.
|
||||||
|
func (c *Client) OperatorReboot(ctx context.Context) (time.Time, error) {
|
||||||
|
body, err := c.get(ctx, "/guest/operator-reboot")
|
||||||
|
if err != nil {
|
||||||
|
return time.Time{}, err
|
||||||
|
}
|
||||||
|
var out struct {
|
||||||
|
At string `json:"at"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &out); err != nil {
|
||||||
|
return time.Time{}, fmt.Errorf("agentapi: decode /guest/operator-reboot: %w", err)
|
||||||
|
}
|
||||||
|
if out.At == "" {
|
||||||
|
return time.Time{}, nil
|
||||||
|
}
|
||||||
|
at, err := time.Parse(time.RFC3339, out.At)
|
||||||
|
if err != nil {
|
||||||
|
return time.Time{}, fmt.Errorf("agentapi: /guest/operator-reboot: bad time %q", out.At)
|
||||||
|
}
|
||||||
|
return at, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package agentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1254 H2: the agent's claim/confirm may take its whole upload timeout (30 s) plus the hub question (15 s) before it
|
||||||
|
// answers. The controller's agent client gives up at 15 s — and a claim the controller abandons can still complete on
|
||||||
|
// the agent: the hub then holds a package whose code nobody saw. The two calls carry their own, longer timeout.
|
||||||
|
// RED-PROOF: send claim/confirm through the plain 15 s client again → the slow agent below times them out → FAILS.
|
||||||
|
func TestR1254_ClaimAndConfirmOutwaitTheAgentsUpload(t *testing.T) {
|
||||||
|
if escrowCallTimeout < 45*time.Second+10*time.Second {
|
||||||
|
t.Fatalf("escrowCallTimeout %s must outlast the agent's upload (30 s) + hub question (15 s) with room", escrowCallTimeout)
|
||||||
|
}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("POST /escrow/ceremony/claim", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
time.Sleep(300 * time.Millisecond)
|
||||||
|
_, _ = w.Write([]byte(`{"ok":true,"data":{"recovery_code":"a-b-c"}}`))
|
||||||
|
})
|
||||||
|
mux.HandleFunc("POST /escrow/ceremony/confirm", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
time.Sleep(300 * time.Millisecond)
|
||||||
|
_, _ = w.Write([]byte(`{"ok":true,"data":{"uploaded":true}}`))
|
||||||
|
})
|
||||||
|
s := httptest.NewTLSServer(mux)
|
||||||
|
defer s.Close()
|
||||||
|
c := clientFor(t, s, strings.TrimPrefix(s.URL, "https://"))
|
||||||
|
c.hc.Timeout = 100 * time.Millisecond // the client's own short timeout, scaled down
|
||||||
|
old := escrowCallTimeout
|
||||||
|
escrowCallTimeout = 5 * time.Second
|
||||||
|
defer func() { escrowCallTimeout = old }()
|
||||||
|
if claim, st, err := c.EscrowCeremonyClaim(context.Background()); err != nil || st != http.StatusOK || claim.Code != "a-b-c" {
|
||||||
|
t.Fatalf("a slow claim was abandoned: %+v %d %v", claim, st, err)
|
||||||
|
}
|
||||||
|
if st, err := c.EscrowCeremonyConfirm(context.Background(), []string{"a", "c"}); err != nil || st != http.StatusOK {
|
||||||
|
t.Fatalf("a slow confirm was abandoned: %d %v", st, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package agentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-330 (disk health Phase 2, the wire only). The agent (v0.150.0+) sends three more SATA raw
|
||||||
|
// counters; the controller must DECODE them (a field the struct lacks is silently dropped by
|
||||||
|
// encoding/json) and must not yet ACT on them.
|
||||||
|
|
||||||
|
// The 2026-08-14 failing drive as the agent now reports it (values from
|
||||||
|
// felhom.eu/documentation/audits/fixtures/smart-ST3000VX010-failing-2026-08-14.json).
|
||||||
|
const r330AgentJSON = `{"health":"PASSED","temperature_c":40,"power_on_hours":null,
|
||||||
|
"reallocated_sectors":0,"pending_sectors":352,"offline_uncorrectable":352,
|
||||||
|
"reported_uncorrect":1001,"command_timeout":0,"udma_crc_errors":0,
|
||||||
|
"critical_warning":null,"media_errors":null,"percentage_used":null}`
|
||||||
|
|
||||||
|
// COMPANION RED-PROOF (observed): rename the controller tag `reported_uncorrect` → `reported_uncorrectable`
|
||||||
|
// → this fails with "187 must decode from the agent's JSON (raw 1001); got <nil>". Restored.
|
||||||
|
func TestR330_DecodesTheThreeCounters(t *testing.T) {
|
||||||
|
var s SmartSummary
|
||||||
|
if err := json.Unmarshal([]byte(r330AgentJSON), &s); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if s.ReportedUncorrect == nil || *s.ReportedUncorrect != 1001 {
|
||||||
|
t.Fatalf("187 must decode from the agent's JSON (raw 1001); got %v", s.ReportedUncorrect)
|
||||||
|
}
|
||||||
|
// A measured ZERO stays a zero (not nil): 188 and 199 were reported as 0 by this drive.
|
||||||
|
if s.CommandTimeout == nil || *s.CommandTimeout != 0 || s.UDMACRCErrors == nil || *s.UDMACRCErrors != 0 {
|
||||||
|
t.Fatalf("188/199 reported as 0 must decode as a measured 0; got %v %v", s.CommandTimeout, s.UDMACRCErrors)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An older agent omits the keys → nil (unknown), never 0.
|
||||||
|
var old SmartSummary
|
||||||
|
if err := json.Unmarshal([]byte(`{"health":"PASSED","pending_sectors":0}`), &old); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if old.ReportedUncorrect != nil || old.CommandTimeout != nil || old.UDMACRCErrors != nil {
|
||||||
|
t.Fatalf("an older agent's report must leave the counters nil (unknown); got %v %v %v",
|
||||||
|
old.ReportedUncorrect, old.CommandTimeout, old.UDMACRCErrors)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CARRIED ONLY: tonight the counters change no verdict, label or degraded-attribute list — reading
|
||||||
|
// them is a change to what a household is told and is not taken here (R-330's next slice).
|
||||||
|
func TestR330_CountersChangeNoVerdictYet(t *testing.T) {
|
||||||
|
with := realDrive()
|
||||||
|
big := int64(5000)
|
||||||
|
with.ReportedUncorrect, with.CommandTimeout, with.UDMACRCErrors = &big, &big, &big
|
||||||
|
without := realDrive()
|
||||||
|
for _, prior := range []DiskPrior{{}, {SawUncorrectable: true}} {
|
||||||
|
if a, b := DiskVerdictFor(with, prior), DiskVerdictFor(without, prior); a != b {
|
||||||
|
t.Fatalf("prior %+v: the R-330 counters changed the verdict (%v vs %v) — that is a household-facing change", prior, a, b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if a, b := DegradedAttributes(with), DegradedAttributes(without); !reflect.DeepEqual(a, b) {
|
||||||
|
t.Fatalf("the R-330 counters changed the degraded-attribute list: %v vs %v", a, b)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package agentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-899: a household press tells the agent so (`trigger=manual`), and nothing else does — the agent runs the
|
||||||
|
// night's OS leg only after a backup that is not a press. The request the agent RECEIVES is asserted.
|
||||||
|
func TestR899_PressCarriesTriggerManual(t *testing.T) {
|
||||||
|
var got []string
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("POST /backup", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
got = append(got, r.URL.RawQuery)
|
||||||
|
w.WriteHeader(http.StatusAccepted)
|
||||||
|
_, _ = w.Write([]byte(`{"ok":true,"data":{"vmid":9201,"job_id":"backup-9201-2","phase":"running"}}`))
|
||||||
|
})
|
||||||
|
s := httptest.NewTLSServer(mux)
|
||||||
|
defer s.Close()
|
||||||
|
c := clientFor(t, s, strings.TrimPrefix(s.URL, "https://"))
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
if _, err := c.StartBackup(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := c.StartBackupFor(ctx, "local"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := c.StartBackupForTrigger(ctx, "local", true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := c.StartBackupForTrigger(ctx, "", true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := []string{"", "target=local", "target=local&trigger=manual", "trigger=manual"}
|
||||||
|
if len(got) != len(want) {
|
||||||
|
t.Fatalf("queries = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
for i := range want {
|
||||||
|
if got[i] != want[i] {
|
||||||
|
t.Fatalf("query %d = %q, want %q (all: %q)", i, got[i], want[i], got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package agentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-921: the pre-check reads the agent's real wire shapes — GET /backup/tiers, then GET /backup/status per
|
||||||
|
// target — and reports exactly the tiers whose job is running or snapshotted (the agent's in-flight set).
|
||||||
|
func TestBackupJobsInFlight_ReportsRunningAndSnapshottedTiers(t *testing.T) {
|
||||||
|
phases := map[string]string{"local": "done", "felhom-pbs": "snapshotted", "extra": "running"}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("GET /backup/tiers", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, _ = w.Write([]byte(`{"ok":true,"data":{"vmid":9201,"tiers":[` +
|
||||||
|
`{"target":"local","cadence_seconds":86400,"primary":true,"storage":"present"},` +
|
||||||
|
`{"target":"felhom-pbs","cadence_seconds":604800,"primary":false,"storage":"present"},` +
|
||||||
|
`{"target":"extra","cadence_seconds":604800,"primary":false,"storage":"present"}]}}`))
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /backup/status", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
tg := r.URL.Query().Get("target")
|
||||||
|
ph, ok := phases[tg]
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, "unexpected target "+tg, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = w.Write([]byte(`{"ok":true,"data":{"vmid":9201,"phase":"` + ph + `","target":"` + tg + `"}}`))
|
||||||
|
})
|
||||||
|
s := httptest.NewTLSServer(mux)
|
||||||
|
defer s.Close()
|
||||||
|
c := clientFor(t, s, strings.TrimPrefix(s.URL, "https://"))
|
||||||
|
|
||||||
|
got, err := c.BackupJobsInFlight(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BackupJobsInFlight: %v", err)
|
||||||
|
}
|
||||||
|
if want := []string{"felhom-pbs", "extra"}; !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("in-flight tiers = %v, want %v (done must not count; running and snapshotted must)", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A pre-R-82 agent (no /backup/tiers → 404) has no per-tier jobs: nil, nil — never an error that would be
|
||||||
|
// read as "cannot tell", and never a busy verdict.
|
||||||
|
func TestBackupJobsInFlight_PreR82AgentIsNotBusy(t *testing.T) {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
s := httptest.NewTLSServer(mux) // every route 404s
|
||||||
|
defer s.Close()
|
||||||
|
c := clientFor(t, s, strings.TrimPrefix(s.URL, "https://"))
|
||||||
|
|
||||||
|
got, err := c.BackupJobsInFlight(context.Background())
|
||||||
|
if err != nil || got != nil {
|
||||||
|
t.Fatalf("pre-R-82 agent: got %v, %v — want nil, nil", got, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A status read that fails is returned, so the loop can fail toward backing up and say so.
|
||||||
|
func TestBackupJobsInFlight_StatusErrorIsReturned(t *testing.T) {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("GET /backup/tiers", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, _ = w.Write([]byte(`{"ok":true,"data":{"vmid":9201,"tiers":[{"target":"local","primary":true}]}}`))
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /backup/status", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.Error(w, "boom", http.StatusInternalServerError)
|
||||||
|
})
|
||||||
|
s := httptest.NewTLSServer(mux)
|
||||||
|
defer s.Close()
|
||||||
|
c := clientFor(t, s, strings.TrimPrefix(s.URL, "https://"))
|
||||||
|
|
||||||
|
if _, err := c.BackupJobsInFlight(context.Background()); err == nil {
|
||||||
|
t.Fatal("a failed status read was swallowed — the caller could not tell it from 'nothing in flight'")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// R-921 part 2: HostBusy reads the agent's real wire shape (untargeted GET /backup/status, `host_busy`); an agent
|
||||||
|
// without the field is „not known" — never „free".
|
||||||
|
func TestHostBusy_ReadsTheAgentsGate(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, body string
|
||||||
|
busy, known bool
|
||||||
|
what string
|
||||||
|
}{
|
||||||
|
{"held", `{"ok":true,"data":{"vmid":9201,"phase":"idle","host_busy":{"busy":true,"what":"os-pve-step"}}}`, true, true, "os-pve-step"},
|
||||||
|
{"free", `{"ok":true,"data":{"vmid":9201,"phase":"idle","host_busy":{"busy":false}}}`, false, true, ""},
|
||||||
|
{"older agent", `{"ok":true,"data":{"vmid":9201,"phase":"idle"}}`, false, false, ""},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("GET /backup/status", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.RawQuery != "" {
|
||||||
|
http.Error(w, "want the untargeted status", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = w.Write([]byte(tc.body))
|
||||||
|
})
|
||||||
|
s := httptest.NewTLSServer(mux)
|
||||||
|
defer s.Close()
|
||||||
|
c := clientFor(t, s, strings.TrimPrefix(s.URL, "https://"))
|
||||||
|
busy, what, known, err := c.HostBusy(context.Background())
|
||||||
|
if err != nil || busy != tc.busy || known != tc.known || what != tc.what {
|
||||||
|
t.Fatalf("HostBusy = %v %q known=%v err=%v, want %v %q known=%v", busy, what, known, err, tc.busy, tc.what, tc.known)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestWriteConfig0600 asserts F8: controller.yaml is persisted 0600 (it holds infra secrets), even when
|
|
||||||
// the target file already existed with looser (0644) permissions. POSIX modes only — skipped on Windows.
|
|
||||||
func TestWriteConfig0600(t *testing.T) {
|
|
||||||
if runtime.GOOS == "windows" {
|
|
||||||
t.Skip("POSIX file modes not represented on Windows")
|
|
||||||
}
|
|
||||||
dir := t.TempDir()
|
|
||||||
path := filepath.Join(dir, "controller.yaml")
|
|
||||||
|
|
||||||
// Pre-create with world-readable 0644 to prove the helper tightens an existing file.
|
|
||||||
if err := os.WriteFile(path, []byte("old: true\n"), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := writeConfig0600(path, []byte("hub:\n api_key: redacted\n")); err != nil {
|
|
||||||
t.Fatalf("writeConfig0600: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
fi, err := os.Stat(path)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if mode := fi.Mode().Perm(); mode != 0o600 {
|
|
||||||
t.Fatalf("config mode = %o, want 0600", mode)
|
|
||||||
}
|
|
||||||
// No leftover temp file.
|
|
||||||
if _, err := os.Stat(path + ".tmp"); !os.IsNotExist(err) {
|
|
||||||
t.Fatalf("temp file not cleaned up")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
// D4 (`16` §5): the no-drive refusal is a 400 the household can act on — not a 500.
|
||||||
|
func TestD4_NeedsDriveIs400(t *testing.T) {
|
||||||
|
err := util.MsgErrorf(stacks.ErrNeedsDrive, "err.stacks.needs_drive")
|
||||||
|
if got := deployStatusFor(err); got != http.StatusBadRequest {
|
||||||
|
t.Fatalf("ErrNeedsDrive → %d, want 400", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"go/ast"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/i18n"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// D72 / D84 (`09` §3 decisions 292, 309; `07-backup-architecture.md` §8.2f).
|
||||||
|
// RED-PROOFS: felhom.eu/documentation/audits/build-release-4-2026-11-15/A/redproof-ctrl-press.txt.
|
||||||
|
|
||||||
|
func endsRouter(t *testing.T, transport string) (*Router, *settings.Settings) {
|
||||||
|
t.Helper()
|
||||||
|
r, _ := newR442Router(t, "deployed: true\nenv: {}\n")
|
||||||
|
lg := log.New(io.Discard, "", 0)
|
||||||
|
sett, err := settings.Load(filepath.Join(t.TempDir(), "settings.json"), lg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := sett.SetOffboxTarget(&settings.OffboxTarget{Enabled: true, Host: "h", User: "u", RepoPath: "/r", Transport: transport}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg := &config.Config{}
|
||||||
|
cfg.Paths.DataDir = t.TempDir()
|
||||||
|
r.backupMgr = backup.NewManager(cfg, sett, lg)
|
||||||
|
r.sett = sett
|
||||||
|
return r, sett
|
||||||
|
}
|
||||||
|
|
||||||
|
// THE DATE IS SHOWN BEFORE THE PRESS (D72): the dialog's data carries the day the off-site copies would be deleted —
|
||||||
|
// today + 30 days, in the household's date form — only on a box where a press starts the clock.
|
||||||
|
func TestD72_BackupDataCarriesTheEndDateBeforeThePress(t *testing.T) {
|
||||||
|
get := func(r *Router, lang string) map[string]any {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.getStackBackupData(w, httptest.NewRequest(http.MethodGet, "/api/stacks/app/backup-data?lang="+lang, nil), "app")
|
||||||
|
var resp struct {
|
||||||
|
OK bool `json:"ok"`
|
||||||
|
Data map[string]any `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil || !resp.OK {
|
||||||
|
t.Fatalf("backup-data: %s (%v)", w.Body.String(), err)
|
||||||
|
}
|
||||||
|
return resp.Data
|
||||||
|
}
|
||||||
|
r, sett := endsRouter(t, settings.TransportRclonePinned)
|
||||||
|
want := time.Now().Add(settings.OffsiteEndAfter).Local()
|
||||||
|
for _, lang := range []string{"hu", "en"} {
|
||||||
|
got, _ := get(r, lang)["offsite_end_date"].(string)
|
||||||
|
if got != i18n.FormatDate(lang, want) && got != i18n.FormatDate(lang, want.Add(-time.Minute)) {
|
||||||
|
t.Errorf("[%s] offsite_end_date = %q, want %q (today + 30 days)", lang, got, i18n.FormatDate(lang, want))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// reading the dialog's data writes NOTHING: the record is the press's, not the look's
|
||||||
|
if n := len(sett.GetOffsiteEnds()); n != 0 {
|
||||||
|
t.Fatalf("opening the dialog wrote %d end record(s)", n)
|
||||||
|
}
|
||||||
|
// the household's own NAS (no hub window): the dialog says nothing about off-site copies
|
||||||
|
r2, _ := endsRouter(t, "")
|
||||||
|
if v, has := get(r2, "hu")["offsite_end_date"]; has {
|
||||||
|
t.Fatalf("a box without the hub's tier names an end date: %v", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MUST-HOLD 1, at the handler: the end record is written ONLY when the household pressed „delete backup data”.
|
||||||
|
// removeStack's success path needs Docker, so this reads the handler's source (as R-486/R-491 do): every call of
|
||||||
|
// StartOffsiteEnd in removeStack sits inside an `if` whose condition names body.RemoveBackups — and there is one.
|
||||||
|
// What the call then does is pinned on the real code in backup (TestD84_OnePressOneMail and the window tests).
|
||||||
|
func TestD72_RemovalWritesTheEndRecordOnlyWithDeleteBackupData(t *testing.T) {
|
||||||
|
fset := token.NewFileSet()
|
||||||
|
f, err := parser.ParseFile(fset, "router.go", nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
calls, guarded := 0, 0
|
||||||
|
for _, d := range f.Decls {
|
||||||
|
fn, ok := d.(*ast.FuncDecl)
|
||||||
|
if !ok || fn.Name.Name != "removeStack" || fn.Body == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
isCall := func(n ast.Node) bool {
|
||||||
|
s, ok := n.(*ast.SelectorExpr)
|
||||||
|
return ok && s.Sel.Name == "StartOffsiteEnd"
|
||||||
|
}
|
||||||
|
ast.Inspect(fn.Body, func(n ast.Node) bool {
|
||||||
|
if isCall(n) {
|
||||||
|
calls++
|
||||||
|
}
|
||||||
|
ifs, ok := n.(*ast.IfStmt)
|
||||||
|
if !ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
names := false
|
||||||
|
ast.Inspect(ifs.Cond, func(c ast.Node) bool {
|
||||||
|
if s, ok := c.(*ast.SelectorExpr); ok && s.Sel.Name == "RemoveBackups" {
|
||||||
|
names = true
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if names {
|
||||||
|
ast.Inspect(ifs.Body, func(b ast.Node) bool {
|
||||||
|
if isCall(b) {
|
||||||
|
guarded++
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if calls != 1 || guarded != 1 {
|
||||||
|
t.Fatalf("removeStack: %d call(s) of StartOffsiteEnd, %d inside `if … body.RemoveBackups …` — want exactly one, guarded: "+
|
||||||
|
"a removal that KEEPS the backups must write no end record", calls, guarded)
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile("router.go")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if n := strings.Count(string(raw), "StartOffsiteEnd("); n != 1 {
|
||||||
|
t.Fatalf("router.go calls StartOffsiteEnd %d time(s) — the removal is its only caller here", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,6 +20,10 @@ type keptChoiceData struct {
|
|||||||
UseDesc string `json:"use_desc"` // "" when use is off
|
UseDesc string `json:"use_desc"` // "" when use is off
|
||||||
UseOff string `json:"use_off"` // "" when use is offered
|
UseOff string `json:"use_off"` // "" when use is offered
|
||||||
UseOffered bool `json:"use_offered"` // a database copy exists for these files
|
UseOffered bool `json:"use_offered"` // a database copy exists for these files
|
||||||
|
// UseFuture / UseWarn (R-1271): the only copy is dated in the future — offered, NOT recommended (the page draws
|
||||||
|
// „use" as the plain button), and the sentence says why.
|
||||||
|
UseFuture bool `json:"use_future,omitempty"`
|
||||||
|
UseWarn string `json:"use_warn,omitempty"`
|
||||||
FreshLabel string `json:"fresh_label"`
|
FreshLabel string `json:"fresh_label"`
|
||||||
FreshDesc string `json:"fresh_desc"`
|
FreshDesc string `json:"fresh_desc"`
|
||||||
NotBacked string `json:"not_backed_up"`
|
NotBacked string `json:"not_backed_up"`
|
||||||
@@ -71,13 +75,17 @@ func (r *Router) keptDataAtInstall(w http.ResponseWriter, req *http.Request, nam
|
|||||||
}
|
}
|
||||||
if cp.ok {
|
if cp.ok {
|
||||||
data.UseDesc = r.msgLang(lang, "kept.choice.use.desc_from", r.keptCopyName(lang, cp.c))
|
data.UseDesc = r.msgLang(lang, "kept.choice.use.desc_from", r.keptCopyName(lang, cp.c))
|
||||||
|
if cp.c.Future {
|
||||||
|
data.UseFuture = true
|
||||||
|
data.UseWarn = r.msgLang(lang, "kept.choice.use.future", localMinute(cp.c.Time))
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
data.UseOff = r.msgLang(lang, "kept.choice.use_off")
|
data.UseOff = r.msgLang(lang, "kept.choice.use_off")
|
||||||
}
|
}
|
||||||
|
|
||||||
switch choice {
|
switch choice {
|
||||||
case "":
|
case "":
|
||||||
r.logger.Printf("[INFO] [api] Deploy %s: the drive already holds its old data %v (%d bytes) — asking the household (use offered: %v)", name, old, size, cp.ok)
|
r.logger.Printf("[INFO] [api] Deploy %s: the drive already holds its old data %v (%d bytes) — asking the household (use offered: %v, future-dated: %v)", name, old, size, cp.ok, cp.c.Future)
|
||||||
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: data.Title, Data: data})
|
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: data.Title, Data: data})
|
||||||
return true
|
return true
|
||||||
case stacks.KeptChoiceUse:
|
case stacks.KeptChoiceUse:
|
||||||
@@ -86,7 +94,9 @@ func (r *Router) keptDataAtInstall(w http.ResponseWriter, req *http.Request, nam
|
|||||||
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: data.UseOff, Data: data})
|
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: data.UseOff, Data: data})
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if st := r.backupMgr.RestoreStatus(); st.Running || r.backupMgr.IsRunning() {
|
// R-1256 H6: every operation — a restore, a backup run, a second-drive copy — not only the first two; and the
|
||||||
|
// load itself begins in the same step as this question (startKeptLoad → ErrRestoreBusy).
|
||||||
|
if busy, _ := r.backupMgr.RestoreBusy(); busy != "" {
|
||||||
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: r.msgLang(lang, "api.kept.busy")})
|
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: r.msgLang(lang, "api.kept.busy")})
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -96,7 +106,11 @@ func (r *Router) keptDataAtInstall(w http.ResponseWriter, req *http.Request, nam
|
|||||||
}
|
}
|
||||||
r.logger.Printf("[INFO] [api] Deploy %s: USE MY KEPT DATA — loading from %s (tier %d, %s) under the kept files %v", name, src, cp.c.Tier, cp.c.Time.UTC().Format(time.RFC3339), old)
|
r.logger.Printf("[INFO] [api] Deploy %s: USE MY KEPT DATA — loading from %s (tier %d, %s) under the kept files %v", name, src, cp.c.Tier, cp.c.Time.UTC().Format(time.RFC3339), old)
|
||||||
r.dropLeftoverHold(name, "use-kept-data") // R-704: this is a new install of an app that is not installed
|
r.dropLeftoverHold(name, "use-kept-data") // R-704: this is a new install of an app that is not installed
|
||||||
r.startKeptLoad(name, hdd, cp.c, lang, nil)
|
if err := r.startKeptLoad(name, hdd, cp.c, lang, nil); err != nil {
|
||||||
|
r.logger.Printf("[WARN] [api] Deploy %s: use my kept data REFUSED at its start: %v", name, err)
|
||||||
|
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: r.msgLang(lang, "api.kept.busy")})
|
||||||
|
return true
|
||||||
|
}
|
||||||
writeJSON(w, http.StatusAccepted, apiResponse{OK: true, Message: r.msgLang(lang, "kept.load.started", display)})
|
writeJSON(w, http.StatusAccepted, apiResponse{OK: true, Message: r.msgLang(lang, "kept.load.started", display)})
|
||||||
return true
|
return true
|
||||||
default:
|
default:
|
||||||
@@ -112,7 +126,7 @@ func (r *Router) keptCopyName(lang string, c backup.KeptCopy) string {
|
|||||||
|
|
||||||
// startKeptLoad runs the load and, when it succeeded, the app's after_load. then(ok) runs last. The
|
// startKeptLoad runs the load and, when it succeeded, the app's after_load. then(ok) runs last. The
|
||||||
// off-site copy goes through LoadKeptOffsite (download the unit alone, judge it, then the same restore).
|
// off-site copy goes through LoadKeptOffsite (download the unit alone, judge it, then the same restore).
|
||||||
func (r *Router) startKeptLoad(name, drive string, c backup.KeptCopy, lang string, then func(ok bool)) {
|
func (r *Router) startKeptLoad(name, drive string, c backup.KeptCopy, lang string, then func(ok bool)) error {
|
||||||
display := name
|
display := name
|
||||||
if st, ok := r.stackMgr.GetStack(name); ok && st.Meta.DisplayName != "" {
|
if st, ok := r.stackMgr.GetStack(name); ok && st.Meta.DisplayName != "" {
|
||||||
display = st.Meta.DisplayName
|
display = st.Meta.DisplayName
|
||||||
@@ -120,10 +134,9 @@ func (r *Router) startKeptLoad(name, drive string, c backup.KeptCopy, lang strin
|
|||||||
okMsg := func(error) string { return r.msgLang(lang, "kept.load.done", display) }
|
okMsg := func(error) string { return r.msgLang(lang, "kept.load.done", display) }
|
||||||
failMsg := func(err error) string { return r.msgLang(lang, "kept.load.failed", display, err) }
|
failMsg := func(err error) string { return r.msgLang(lang, "kept.load.failed", display, err) }
|
||||||
if c.Tier == backup.KeptTierOffsite {
|
if c.Tier == backup.KeptTierOffsite {
|
||||||
r.backupMgr.LoadKeptOffsite(name, drive, c, nil, okMsg, failMsg, r.keptAfterLoad(name, then))
|
return r.backupMgr.LoadKeptOffsite(name, drive, c, nil, okMsg, failMsg, r.keptAfterLoad(name, then))
|
||||||
return
|
|
||||||
}
|
}
|
||||||
r.backupMgr.LoadKeptApp(name, c.UnitDir, okMsg, failMsg, r.keptAfterLoad(name, then))
|
return r.backupMgr.LoadKeptApp(name, c.UnitDir, nil, okMsg, failMsg, r.keptAfterLoad(name, then))
|
||||||
}
|
}
|
||||||
|
|
||||||
// keptAfterLoad runs the app's after_load when the load succeeded, then then(ok).
|
// keptAfterLoad runs the app's after_load when the load succeeded, then then(ok).
|
||||||
|
|||||||
@@ -162,7 +162,10 @@ func TestR691_InstallChoiceNamesTheOffsiteCopy(t *testing.T) {
|
|||||||
// copy, restic and the unit restore behind their seams — no Docker).
|
// copy, restic and the unit restore behind their seams — no Docker).
|
||||||
// COMPANION RED-PROOF: remove the dropLeftoverHold call from keptDataAtInstall → the hold is still there
|
// COMPANION RED-PROOF: remove the dropLeftoverHold call from keptDataAtInstall → the hold is still there
|
||||||
// after the 202 and the first assertion fails; remove it from deployStack → the AST check fails.
|
// after the 202 and the first assertion fails; remove it from deployStack → the AST check fails.
|
||||||
func TestR704_AFreshInstallDropsALeftoverHold(t *testing.T) {
|
// keptInstallRig is an installable app with old data on its drive and an off-site copy of its unit; done receives
|
||||||
|
// once per unit restore the load reaches.
|
||||||
|
func keptInstallRig(t *testing.T) (*Router, *settings.Settings, string, chan struct{}) {
|
||||||
|
t.Helper()
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
drive := filepath.Join(dir, "drive")
|
drive := filepath.Join(dir, "drive")
|
||||||
cfg := &config.Config{}
|
cfg := &config.Config{}
|
||||||
@@ -234,6 +237,11 @@ func TestR704_AFreshInstallDropsALeftoverHold(t *testing.T) {
|
|||||||
return backup.UnitRestoreResult{}, nil
|
return backup.UnitRestoreResult{}, nil
|
||||||
})
|
})
|
||||||
r := &Router{stackMgr: m, backupMgr: bm, sett: sett, logger: log.New(io.Discard, "", 0)}
|
r := &Router{stackMgr: m, backupMgr: bm, sett: sett, logger: log.New(io.Discard, "", 0)}
|
||||||
|
return r, sett, drive, done
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestR704_AFreshInstallDropsALeftoverHold(t *testing.T) {
|
||||||
|
r, sett, drive, done := keptInstallRig(t)
|
||||||
|
|
||||||
// A leftover update hold from an earlier install (the demo-hp shape): the new install drops it.
|
// A leftover update hold from an earlier install (the demo-hp shape): the new install drops it.
|
||||||
_ = sett.SetRestoreHold(settings.RestoreHold{Stack: "cloudapp", At: "2026-09-13T19:56:32Z", Reason: settings.HoldReasonUpdateFailed})
|
_ = sett.SetRestoreHold(settings.RestoreHold{Stack: "cloudapp", At: "2026-09-13T19:56:32Z", Reason: settings.HoldReasonUpdateFailed})
|
||||||
@@ -287,3 +295,38 @@ func TestR704_AFreshInstallDropsALeftoverHold(t *testing.T) {
|
|||||||
t.Fatalf("deployStack must call dropLeftoverHold before DeployStack (drop=%v deploy=%v)", dropAt, deployAt)
|
t.Fatalf("deployStack must call dropLeftoverHold before DeployStack (drop=%v deploy=%v)", dropAt, deployAt)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// R-1256 H6: the install-time „use my kept data" asks about EVERY operation — a second-drive copy too, not only a
|
||||||
|
// restore record and the backup run — and the load begins in the same step as the question.
|
||||||
|
// RED-PROOF: restore the RestoreStatus/IsRunning-only check and LoadKept*'s plain BeginRestoreOp → 202 and the load
|
||||||
|
// runs beside the copy → FAILS.
|
||||||
|
func TestR1256_H6_AKeptLoadAtInstallIsRefusedWhileASecondDriveCopyRuns(t *testing.T) {
|
||||||
|
r, _, drive, done := keptInstallRig(t)
|
||||||
|
end := backup.MarkTier2CopyForTest("someapp")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/stacks/cloudapp/deploy?lang=en", nil)
|
||||||
|
r.keptDataAtInstall(w, req, "cloudapp", drive, "use")
|
||||||
|
end()
|
||||||
|
if w.Code != http.StatusConflict {
|
||||||
|
t.Fatalf("a load during a second-drive copy: code %d, want 409 — body %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
t.Fatal("the load ran beside the second-drive copy")
|
||||||
|
case <-time.After(300 * time.Millisecond):
|
||||||
|
}
|
||||||
|
if st := r.backupMgr.RestoreStatus(); st.Running {
|
||||||
|
t.Fatal("a refused load left a restore op recorded")
|
||||||
|
}
|
||||||
|
// The copy ended: the same press loads.
|
||||||
|
w = httptest.NewRecorder()
|
||||||
|
r.keptDataAtInstall(w, httptest.NewRequest(http.MethodPost, "/api/stacks/cloudapp/deploy?lang=en", nil), "cloudapp", drive, "use")
|
||||||
|
if w.Code != http.StatusAccepted {
|
||||||
|
t.Fatalf("after the copy: code %d — body %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(10 * time.Second):
|
||||||
|
t.Fatal("the load never reached the unit restore")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-1271 (brief 2026-10-25 Part 4) — a future-dated off-site copy, the ONLY copy of the kept files: still offered (it
|
||||||
|
// may be the household's), but the question says its date is in the future and does not recommend it. Same rig as
|
||||||
|
// TestR691 (the restic runner seam; nothing reaches restic, ssh or Docker).
|
||||||
|
// COMPANION RED-PROOF (REPORT.md): with keptPick ignoring the future date, use_future stays false and this fails.
|
||||||
|
func TestR1271_AFutureCopyAloneIsSaidAndNotRecommended(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
drive := filepath.Join(dir, "drive")
|
||||||
|
cfg := &config.Config{}
|
||||||
|
cfg.Paths.StacksDir = filepath.Join(dir, "stacks")
|
||||||
|
cfg.Paths.DataDir = filepath.Join(dir, "data")
|
||||||
|
cfg.Stacks.ComposeCommand = "docker compose"
|
||||||
|
app := filepath.Join(cfg.Paths.StacksDir, "cloudapp")
|
||||||
|
for _, d := range []string{app, filepath.Join(drive, "appdata/cloudapp"), cfg.Paths.DataDir} {
|
||||||
|
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = os.WriteFile(filepath.Join(app, "docker-compose.yml"), []byte("services:\n cloudapp:\n image: busybox\n volumes:\n - ${HDD_PATH}/appdata/cloudapp:/data\n"), 0o644)
|
||||||
|
_ = os.WriteFile(filepath.Join(app, ".felhom.yml"), []byte("display_name: Cloud App\n"), 0o644)
|
||||||
|
_ = os.WriteFile(filepath.Join(drive, "appdata/cloudapp/old.txt"), []byte("old"), 0o644)
|
||||||
|
m, err := stacks.NewManager(cfg, log.New(io.Discard, "", 0))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := m.ScanStacks(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
sett, err := settings.Load(filepath.Join(cfg.Paths.DataDir, "settings.json"), log.New(io.Discard, "", 0))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := sett.SetOffboxTarget(&settings.OffboxTarget{Enabled: true, Host: "nas.local", Port: 22, User: "felhom",
|
||||||
|
RepoPath: "/srv/repo", Schedule: "daily", EscrowState: "escrowed"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
bm := backup.NewManager(cfg, sett, log.New(io.Discard, "", 0))
|
||||||
|
if err := bm.WriteOffboxSecrets("KEY", "nas.local ssh-ed25519 AAAA"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
snapAt := time.Now().Add(4 * 24 * time.Hour) // the rehearsal box's clock: four days ahead
|
||||||
|
bm.SetOffboxRunner(func(_ context.Context, _ []string, args ...string) ([]byte, error) {
|
||||||
|
for _, a := range args {
|
||||||
|
if a == "snapshots" {
|
||||||
|
return json.Marshal([]map[string]interface{}{{"short_id": "abba81ba", "time": snapAt,
|
||||||
|
"tags": []string{"cloudapp"}, "paths": []string{drive + "/backups/primary/cloudapp", drive + "/appdata/cloudapp"}}})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
r := &Router{stackMgr: m, backupMgr: bm, logger: log.New(io.Discard, "", 0)}
|
||||||
|
for lang, want := range map[string]string{"hu": "a jövőben van", "en": "is in the future"} {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/stacks/cloudapp/deploy?lang="+lang, nil)
|
||||||
|
if !r.keptDataAtInstall(w, req, "cloudapp", drive, "") || w.Code != http.StatusConflict {
|
||||||
|
t.Fatalf("%s: the choice was not asked (code %d)", lang, w.Code)
|
||||||
|
}
|
||||||
|
var body map[string]interface{}
|
||||||
|
_ = json.Unmarshal(w.Body.Bytes(), &body)
|
||||||
|
data, _ := body["data"].(map[string]interface{})
|
||||||
|
warn, _ := data["use_warn"].(string)
|
||||||
|
if data["use_offered"] != true || data["use_future"] != true || !strings.Contains(warn, want) {
|
||||||
|
t.Fatalf("%s: a future-dated only copy is offered, marked and said: offered=%v future=%v warn=%q", lang, data["use_offered"], data["use_future"], warn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -33,7 +33,10 @@ func TestR474_RemoveHandlerDeletesUnitMirrorAndPrefs(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
joined := " " + strings.Join(sel, " ") + " "
|
joined := " " + strings.Join(sel, " ") + " "
|
||||||
for _, want := range []string{"RecoveryUnitPath", "Tier2MirrorDirsForApp", "RemoveTier2Mirrors", "DeleteAppBackupPrefs"} {
|
// 2026-10-25: the set-aside units of earlier installs (D47) and the restore's kept undo copy (found live on 9202: a
|
||||||
|
// not-started restore's copy outlived the app's remove with its backups) go too.
|
||||||
|
for _, want := range []string{"RecoveryUnitPath", "Tier2MirrorDirsForApp", "RemoveTier2Mirrors", "DeleteAppBackupPrefs",
|
||||||
|
"SetAsideDirsForApp", "RemoveSetAsideUnits", "RestoreUndoDir"} {
|
||||||
if !strings.Contains(joined, " "+want+" ") {
|
if !strings.Contains(joined, " "+want+" ") {
|
||||||
t.Errorf("removeStack must call %s", want)
|
t.Errorf("removeStack must call %s", want)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-569 — the stop/start/restart/update, remove and delete handlers pick their status by the
|
||||||
|
// refusal's KIND. Every row passes a REWORDED message: the words the handlers used to match
|
||||||
|
// ("protected", "not found", "not deployed", "still running", "not orphaned") are gone, only the
|
||||||
|
// kind remains. RED-PROOF (REPORT): restore any strings.Contains chain and its family's reworded rows
|
||||||
|
// answer 500.
|
||||||
|
func TestR569_StackOpStatus_SurvivesRewording(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
family, name string
|
||||||
|
err error
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
// action family (start/stop/restart/update)
|
||||||
|
{"action", "unknown app, reworded", util.KindErrorf(stacks.ErrStackNotFound, "no app called %q", "x"), http.StatusNotFound},
|
||||||
|
{"action", "unknown app, wrapped by the caller", fmt.Errorf("restarting: %w",
|
||||||
|
util.KindErrorf(stacks.ErrStackNotFound, "no app called %q", "x")), http.StatusNotFound},
|
||||||
|
{"action", "protected, reworded", util.KindErrorf(stacks.ErrProtectedStack, "%q is infrastructure", "traefik"), http.StatusForbidden},
|
||||||
|
{"action", "update refusal", &stacks.UpdateRefusal{Reason: "busy", Message: "foglalt"}, http.StatusConflict},
|
||||||
|
{"action", "update refusal: unknown app", &stacks.UpdateRefusal{Reason: "not_found", Message: "nincs ilyen"}, http.StatusNotFound},
|
||||||
|
// remove family
|
||||||
|
{"remove", "not deployed, reworded", util.KindErrorf(stacks.ErrNotDeployed, "%q has nothing installed", "x"), http.StatusConflict},
|
||||||
|
{"remove", "still running, reworded", util.KindErrorf(stacks.ErrStillRunning, "%q is up — stop it first", "x"), http.StatusConflict},
|
||||||
|
{"remove", "protected, reworded", util.KindErrorf(stacks.ErrProtectedStack, "cannot take %q away", "traefik"), http.StatusForbidden},
|
||||||
|
// delete family
|
||||||
|
{"delete", "not orphaned, reworded", util.KindErrorf(stacks.ErrNotOrphaned, "%q still belongs to the catalog", "x"), http.StatusConflict},
|
||||||
|
{"delete", "still running, reworded", util.KindErrorf(stacks.ErrStillRunning, "%q is up", "x"), http.StatusConflict},
|
||||||
|
{"delete", "unknown, reworded", util.KindErrorf(stacks.ErrStackNotFound, "nothing named %q", "x"), http.StatusNotFound},
|
||||||
|
// the negative half: the old WORDS without a kind are not a refusal
|
||||||
|
{"any", "text that merely contains the old words", errors.New("docker: image not found; protected; still running"), http.StatusInternalServerError},
|
||||||
|
{"any", "anything else", errors.New("compose exploded"), http.StatusInternalServerError},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
if got := stackOpStatusFor(c.err); got != c.want {
|
||||||
|
t.Errorf("%s / %s: stackOpStatusFor(%q) = %d, want %d", c.family, c.name, c.err.Error(), got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The seam must be WIRED in all three handlers, and none may decide by reading the error text again.
|
||||||
|
func TestR569_HandlersUseTheKind(t *testing.T) {
|
||||||
|
src, err := os.ReadFile("router.go")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body := string(src)
|
||||||
|
for _, fn := range []string{"func (r *Router) actionStack(", "func (r *Router) removeStack(", "func (r *Router) deleteStack("} {
|
||||||
|
i := strings.Index(body, fn)
|
||||||
|
if i < 0 {
|
||||||
|
t.Fatalf("%s not found — this test no longer reads what it thinks it reads", fn)
|
||||||
|
}
|
||||||
|
h := body[i:]
|
||||||
|
if j := strings.Index(h[10:], "\nfunc "); j > 0 {
|
||||||
|
h = h[:j+10]
|
||||||
|
}
|
||||||
|
if !strings.Contains(h, "stackOpStatusFor(err)") {
|
||||||
|
t.Errorf("%s no longer asks stackOpStatusFor for the status code", fn)
|
||||||
|
}
|
||||||
|
for _, line := range strings.Split(h, "\n") {
|
||||||
|
if strings.HasPrefix(strings.TrimSpace(line), "//") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.Contains(line, "strings.Contains(err.Error()") {
|
||||||
|
t.Errorf("%s decides by reading the error text again (R-569): %s", fn, strings.TrimSpace(line))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-575: the deploy answer renders the overcommit warning in the reader's language — English for an
|
||||||
|
// English request (it used to be Hungarian on every page), Hungarian by default.
|
||||||
|
func TestR575_OvercommitWarningFollowsTheLanguage(t *testing.T) {
|
||||||
|
r := &Router{}
|
||||||
|
en := r.deployWarningData(httptest.NewRequest("POST", "/api/stacks/x/deploy?lang=en", nil), stacks.KeyMemoryOvercommitWarning)
|
||||||
|
hu := r.deployWarningData(httptest.NewRequest("POST", "/api/stacks/x/deploy?lang=hu", nil), stacks.KeyMemoryOvercommitWarning)
|
||||||
|
if en == nil || hu == nil {
|
||||||
|
t.Fatal("a warning key must produce a warning")
|
||||||
|
}
|
||||||
|
if !strings.Contains(en["warning"], "memory") || strings.Contains(en["warning"], "memóri") {
|
||||||
|
t.Errorf("English page got %q", en["warning"])
|
||||||
|
}
|
||||||
|
if !strings.Contains(hu["warning"], "memóri") {
|
||||||
|
t.Errorf("Hungarian page got %q", hu["warning"])
|
||||||
|
}
|
||||||
|
if strings.Contains(en["warning"], "err.stacks.") || strings.Contains(hu["warning"], "err.stacks.") {
|
||||||
|
t.Error("a raw key reached the page")
|
||||||
|
}
|
||||||
|
if d := r.deployWarningData(httptest.NewRequest("POST", "/", nil), ""); d != nil {
|
||||||
|
t.Errorf("no warning -> no data, got %v", d)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,9 +4,13 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
|
||||||
"gitea.dooplex.hu/admin/felhom-controller/internal/dockerexec"
|
"gitea.dooplex.hu/admin/felhom-controller/internal/dockerexec"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestMain puts a silent docker stub on PATH for every test in this package: R-650, the fixtures
|
// TestMain puts a silent docker stub on PATH for every test in this package: R-650, the fixtures
|
||||||
// here build a real stacks.Manager, and on the build host (DooPlex) that reached production Docker.
|
// here build a real stacks.Manager, and on the build host (DooPlex) that reached production Docker.
|
||||||
func TestMain(m *testing.M) { os.Exit(dockerexec.RunWithStub(m)) }
|
func TestMain(m *testing.M) {
|
||||||
|
backup.ShortenRestoreTimingForTests() // fix A's stable windows in milliseconds here too
|
||||||
|
os.Exit(dockerexec.RunWithStub(m))
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// R-970 (v0.322.0): the router has no /config routes at all — even a SIGNED-IN request gets the router's 404 for every
|
||||||
|
// method, and the settings file is neither served nor written.
|
||||||
|
// RED-PROOF (2026-10-16, REPORT): with the `/config` GET case put back, this failed at „GET /api/config answered 200".
|
||||||
|
func TestR970_ConfigRoutesAreGone(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
path := filepath.Join(dir, "controller.yaml")
|
||||||
|
planted := "customer:\n id: t\n domain: example.hu\nhub:\n api_key: TESTONLY-key-r970\n"
|
||||||
|
if err := os.WriteFile(path, []byte(planted), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r := &Router{configPath: path, logger: log.New(io.Discard, "", 0)}
|
||||||
|
r.restart = func() { t.Fatal("a /config request restarted the controller") }
|
||||||
|
for _, p := range []string{"/api/config", "/api/config/", "/api/config/apply", "/api/config/hash"} {
|
||||||
|
for _, m := range []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch} {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, httptest.NewRequest(m, p, strings.NewReader("customer:\n id: evil\n domain: e.example\n")))
|
||||||
|
if w.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("%s %s answered %d, want the router's 404", m, p, w.Code)
|
||||||
|
}
|
||||||
|
if strings.Contains(w.Body.String(), "TESTONLY-key-r970") {
|
||||||
|
t.Fatalf("%s %s served the settings file", m, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got, _ := os.ReadFile(path); string(got) != planted {
|
||||||
|
t.Fatal("the settings file was written")
|
||||||
|
}
|
||||||
|
}
|
||||||
+102
-145
@@ -1,15 +1,12 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -19,6 +16,7 @@ import (
|
|||||||
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
|
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
|
||||||
cf "gitea.dooplex.hu/admin/felhom-controller/internal/cloudflare"
|
cf "gitea.dooplex.hu/admin/felhom-controller/internal/cloudflare"
|
||||||
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
|
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
|
||||||
|
"gitea.dooplex.hu/admin/felhom-controller/internal/i18n"
|
||||||
"gitea.dooplex.hu/admin/felhom-controller/internal/integrations"
|
"gitea.dooplex.hu/admin/felhom-controller/internal/integrations"
|
||||||
"gitea.dooplex.hu/admin/felhom-controller/internal/metrics"
|
"gitea.dooplex.hu/admin/felhom-controller/internal/metrics"
|
||||||
"gitea.dooplex.hu/admin/felhom-controller/internal/notify"
|
"gitea.dooplex.hu/admin/felhom-controller/internal/notify"
|
||||||
@@ -180,17 +178,11 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|||||||
case path == "/selfupdate/update" && req.Method == http.MethodPost:
|
case path == "/selfupdate/update" && req.Method == http.MethodPost:
|
||||||
r.selfupdateTrigger(w, req)
|
r.selfupdateTrigger(w, req)
|
||||||
|
|
||||||
// POST /api/config/apply — Hub pushes generated YAML to update controller.yaml
|
// v0.322.0 (R-970): /api/config, /api/config/hash and /api/config/apply are GONE. They read the box's
|
||||||
case path == "/config/apply" && req.Method == http.MethodPost:
|
// controller.yaml with every secret in it and replaced it — reachable with the box's own hub key, unsigned,
|
||||||
r.configApply(w, req)
|
// which contradicted `01-topology-and-trust.md` §4/§10. Nothing called them (the hub never connects to a box;
|
||||||
|
// the agent injects config at provision; the signed config bundle writes root files). Pinned by
|
||||||
// GET /api/config/hash — return current config file hash
|
// TestR970_ConfigRoutesAreGone and cmd/controller TestR970_HubKeyOpensNoDoor.
|
||||||
case path == "/config/hash" && req.Method == http.MethodGet:
|
|
||||||
r.configHash(w, req)
|
|
||||||
|
|
||||||
// GET /api/config — return raw controller.yaml content
|
|
||||||
case path == "/config" && req.Method == http.MethodGet:
|
|
||||||
r.configContent(w, req)
|
|
||||||
|
|
||||||
// POST /api/selfrestart — customer-facing graceful self-restart (auth + CSRF via /api/ mount)
|
// POST /api/selfrestart — customer-facing graceful self-restart (auth + CSRF via /api/ mount)
|
||||||
case path == "/selfrestart" && req.Method == http.MethodPost:
|
case path == "/selfrestart" && req.Method == http.MethodPost:
|
||||||
@@ -437,7 +429,9 @@ func deployStatusFor(err error) int {
|
|||||||
switch {
|
switch {
|
||||||
case errors.Is(err, stacks.ErrAlreadyDeployed), errors.Is(err, stacks.ErrKeptDataChoice):
|
case errors.Is(err, stacks.ErrAlreadyDeployed), errors.Is(err, stacks.ErrKeptDataChoice):
|
||||||
return http.StatusConflict
|
return http.StatusConflict
|
||||||
case errors.Is(err, stacks.ErrRequiredField), errors.Is(err, stacks.ErrPathMissing),
|
case errors.Is(err, stacks.ErrProtectedStack):
|
||||||
|
return http.StatusForbidden
|
||||||
|
case errors.Is(err, stacks.ErrRequiredField), errors.Is(err, stacks.ErrPathMissing), errors.Is(err, stacks.ErrNeedsDrive),
|
||||||
errors.Is(err, stacks.ErrNotEnoughMemory):
|
errors.Is(err, stacks.ErrNotEnoughMemory):
|
||||||
return http.StatusBadRequest
|
return http.StatusBadRequest
|
||||||
}
|
}
|
||||||
@@ -473,6 +467,14 @@ func (r *Router) deployStack(w http.ResponseWriter, req *http.Request, name stri
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// v0.320.0: a protected infra stack is part of the box, never an app to install. Refused here, before the
|
||||||
|
// kept-data check or anything else that reads the request, and again inside DeployStack for every other caller.
|
||||||
|
if st, ok := r.stackMgr.GetStack(name); ok && (st.Protected || r.cfg.IsProtectedStack(name)) {
|
||||||
|
r.logger.Printf("[WARN] [api] Deploy refused for %s: a protected infra stack is part of the box", name)
|
||||||
|
writeJSON(w, http.StatusForbidden, apiResponse{OK: false, Error: r.msg(req, "api.deploy.part_of_box")})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// Prevention layer (storage-split): refuse a deploy when the Docker-data volume is at/under its
|
// Prevention layer (storage-split): refuse a deploy when the Docker-data volume is at/under its
|
||||||
// reserved buffer, so customer apps can't fill the volume the infra containers (controller,
|
// reserved buffer, so customer apps can't fill the volume the infra containers (controller,
|
||||||
// traefik, cloudflared, filebrowser) depend on. Fail-OPEN on a measurement error — the buffer is
|
// traefik, cloudflared, filebrowser) depend on. Fail-OPEN on a measurement error — the buffer is
|
||||||
@@ -535,7 +537,12 @@ func (r *Router) deployStack(w http.ResponseWriter, req *http.Request, name stri
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
r.logger.Printf("[ERROR] [api] Deploy failed for %s: %v", name, err)
|
r.logger.Printf("[ERROR] [api] Deploy failed for %s: %v", name, err)
|
||||||
// R-553 — the status code comes from the refusal's KIND (deployStatusFor), never from its words.
|
// R-553 — the status code comes from the refusal's KIND (deployStatusFor), never from its words.
|
||||||
writeJSON(w, deployStatusFor(err), apiResponse{OK: false, Error: r.errText(req, err)})
|
resp := apiResponse{OK: false, Error: r.errText(req, err)}
|
||||||
|
if errors.Is(err, stacks.ErrNeedsDrive) {
|
||||||
|
// D4 (`16` §5): the wizard renders the sentence with a link to the drives page.
|
||||||
|
resp.Data = map[string]string{"code": "needs_drive", "link": "/storage"}
|
||||||
|
}
|
||||||
|
writeJSON(w, deployStatusFor(err), resp)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -544,8 +551,8 @@ func (r *Router) deployStack(w http.ResponseWriter, req *http.Request, name stri
|
|||||||
// was true — misleading for API/script consumers. Report that the deploy STARTED, not that it
|
// was true — misleading for API/script consumers. Report that the deploy STARTED, not that it
|
||||||
// finished. 202 Accepted reflects "accepted, processing"; ok:true is preserved for the UI.
|
// finished. 202 Accepted reflects "accepted, processing"; ok:true is preserved for the UI.
|
||||||
resp := apiResponse{OK: true, Message: r.msg(req, "api.deploy.started")}
|
resp := apiResponse{OK: true, Message: r.msg(req, "api.deploy.started")}
|
||||||
if warning != "" {
|
if d := r.deployWarningData(req, warning); d != nil {
|
||||||
resp.Data = map[string]string{"warning": warning}
|
resp.Data = d
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusAccepted, resp)
|
writeJSON(w, http.StatusAccepted, resp)
|
||||||
|
|
||||||
@@ -623,6 +630,36 @@ func desiredStateForAction(action string) (string, bool) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// stackOpStatusFor maps a stack-lifecycle refusal (stop/start/restart/update, remove, delete) to its
|
||||||
|
// HTTP status by the refusal's KIND (R-569) — the R-553 rule one handler family over.
|
||||||
|
//
|
||||||
|
// Until R-569 these three handlers matched "protected", "not found", "not deployed", "still running"
|
||||||
|
// and "not orphaned" in err.Error(). Those strings are internal English, so localisation never moved
|
||||||
|
// them; a reworded internal message would have, silently turning a 404/403/409 into a 500. The kinds
|
||||||
|
// come from internal/stacks (stack_errors.go); the messages are unchanged.
|
||||||
|
//
|
||||||
|
// One function serves the three families because their kinds are disjoint: an action never returns
|
||||||
|
// ErrNotOrphaned, a remove never returns an UpdateRefusal. Pinned by
|
||||||
|
// TestR569_StackOpStatus_SurvivesRewording and TestR569_HandlersUseTheKind.
|
||||||
|
func stackOpStatusFor(err error) int {
|
||||||
|
var ref *stacks.UpdateRefusal
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, stacks.ErrStackNotFound):
|
||||||
|
return http.StatusNotFound
|
||||||
|
case errors.As(err, &ref):
|
||||||
|
if ref.Reason == "not_found" {
|
||||||
|
return http.StatusNotFound
|
||||||
|
}
|
||||||
|
return http.StatusConflict
|
||||||
|
case errors.Is(err, stacks.ErrProtectedStack):
|
||||||
|
return http.StatusForbidden
|
||||||
|
case errors.Is(err, stacks.ErrNotDeployed), errors.Is(err, stacks.ErrStillRunning),
|
||||||
|
errors.Is(err, stacks.ErrNotOrphaned):
|
||||||
|
return http.StatusConflict
|
||||||
|
}
|
||||||
|
return http.StatusInternalServerError
|
||||||
|
}
|
||||||
|
|
||||||
func (r *Router) actionStack(w http.ResponseWriter, req *http.Request, action, name string) {
|
func (r *Router) actionStack(w http.ResponseWriter, req *http.Request, action, name string) {
|
||||||
r.logger.Printf("[INFO] [api] %s requested for stack: %s", action, name)
|
r.logger.Printf("[INFO] [api] %s requested for stack: %s", action, name)
|
||||||
r.dbg("actionStack: action=%s name=%s", action, name)
|
r.dbg("actionStack: action=%s name=%s", action, name)
|
||||||
@@ -735,6 +772,12 @@ func (r *Router) actionStack(w http.ResponseWriter, req *http.Request, action, n
|
|||||||
// above, so nothing is recorded for an action that was never going to happen.
|
// above, so nothing is recorded for an action that was never going to happen.
|
||||||
if desired, ok := desiredStateForAction(action); ok {
|
if desired, ok := desiredStateForAction(action); ok {
|
||||||
if derr := r.stackMgr.SetDesiredState(name, desired); derr != nil {
|
if derr := r.stackMgr.SetDesiredState(name, desired); derr != nil {
|
||||||
|
if errors.Is(derr, stacks.ErrStackNotFound) {
|
||||||
|
// no app by that name on this box (e.g. the bootstrap-managed controller): a 404, not a save failure
|
||||||
|
r.logger.Printf("[WARN] [api] %s for %s refused: no such app", action, name)
|
||||||
|
writeJSON(w, stackOpStatusFor(derr), apiResponse{OK: false, Error: r.errText(req, derr)})
|
||||||
|
return
|
||||||
|
}
|
||||||
r.logger.Printf("[ERROR] [api] %s for %s refused: could not record desired state: %v", action, name, derr)
|
r.logger.Printf("[ERROR] [api] %s for %s refused: could not record desired state: %v", action, name, derr)
|
||||||
writeJSON(w, http.StatusInternalServerError, apiResponse{
|
writeJSON(w, http.StatusInternalServerError, apiResponse{
|
||||||
OK: false,
|
OK: false,
|
||||||
@@ -760,17 +803,7 @@ func (r *Router) actionStack(w http.ResponseWriter, req *http.Request, action, n
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
r.logger.Printf("[ERROR] [api] %s failed for %s: %v", action, name, err)
|
r.logger.Printf("[ERROR] [api] %s failed for %s: %v", action, name, err)
|
||||||
status := http.StatusInternalServerError
|
status := stackOpStatusFor(err) // R-569: by kind, never by the error's words
|
||||||
var ref *stacks.UpdateRefusal
|
|
||||||
if errors.As(err, &ref) {
|
|
||||||
status = http.StatusConflict
|
|
||||||
}
|
|
||||||
if strings.Contains(err.Error(), "protected") {
|
|
||||||
status = http.StatusForbidden
|
|
||||||
}
|
|
||||||
if strings.Contains(err.Error(), "not found") {
|
|
||||||
status = http.StatusNotFound
|
|
||||||
}
|
|
||||||
writeJSON(w, status, apiResponse{OK: false, Error: r.errText(req, err)})
|
writeJSON(w, status, apiResponse{OK: false, Error: r.errText(req, err)})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -931,6 +964,10 @@ func (r *Router) getStackBackupData(w http.ResponseWriter, req *http.Request, na
|
|||||||
writeJSON(w, http.StatusNotFound, apiResponse{OK: false, Error: r.errText(req, err)})
|
writeJSON(w, http.StatusNotFound, apiResponse{OK: false, Error: r.errText(req, err)})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// D72: the date is on the dialog BEFORE the press. Only where a press would start the 30 days.
|
||||||
|
if r.backupMgr != nil && r.backupMgr.OffsiteEndOffered() {
|
||||||
|
resp.OffsiteEndDate = i18n.FormatDate(r.langFor(req), r.backupMgr.OffsiteEndDateIfPressedNow().Local())
|
||||||
|
}
|
||||||
writeJSON(w, http.StatusOK, apiResponse{OK: true, Data: resp})
|
writeJSON(w, http.StatusOK, apiResponse{OK: true, Data: resp})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1024,13 +1061,16 @@ func (r *Router) removeStack(w http.ResponseWriter, req *http.Request, name stri
|
|||||||
// volume tars) and its Tier-2 mirror, not only db-dumps. The mirror is on another drive, outside
|
// volume tars) and its Tier-2 mirror, not only db-dumps. The mirror is on another drive, outside
|
||||||
// RemoveStack's per-app base, so the backup manager removes it — and its location is read NOW,
|
// RemoveStack's per-app base, so the backup manager removes it — and its location is read NOW,
|
||||||
// before the cross-drive record is cleared below. Off-site snapshots are not touched by this path.
|
// before the cross-drive record is cleared below. Off-site snapshots are not touched by this path.
|
||||||
var backupPaths, mirrorDirs []string
|
var backupPaths, mirrorDirs, setAsideDirs []string
|
||||||
if body.RemoveBackups && r.backupMgr != nil {
|
if body.RemoveBackups && r.backupMgr != nil {
|
||||||
nsRoot := r.backupMgr.AppNamespaceRoot(name)
|
nsRoot := r.backupMgr.AppNamespaceRoot(name)
|
||||||
if nsRoot != "" {
|
if nsRoot != "" {
|
||||||
backupPaths = append(backupPaths, backup.RecoveryUnitPath(nsRoot, name), backup.AppDBDumpPath(nsRoot, name))
|
backupPaths = append(backupPaths, backup.RecoveryUnitPath(nsRoot, name), backup.AppDBDumpPath(nsRoot, name),
|
||||||
|
backup.RestoreUndoDir(nsRoot, name)) // a restore's kept undo copy is a backup of the app too (2026-10-25)
|
||||||
}
|
}
|
||||||
mirrorDirs = r.backupMgr.Tier2MirrorDirsForApp(name)
|
mirrorDirs = r.backupMgr.Tier2MirrorDirsForApp(name)
|
||||||
|
// D47: the units of earlier installs set aside for this app are its backups too (the D25 kept-copy rule).
|
||||||
|
setAsideDirs = r.backupMgr.SetAsideDirsForApp(name)
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, err := r.stackMgr.RemoveStack(name, body.RemoveHDDData, backupPaths)
|
resp, err := r.stackMgr.RemoveStack(name, body.RemoveHDDData, backupPaths)
|
||||||
@@ -1052,16 +1092,7 @@ func (r *Router) removeStack(w http.ResponseWriter, req *http.Request, name stri
|
|||||||
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: r.errText(req, err)})
|
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: r.errText(req, err)})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
status := http.StatusInternalServerError
|
status := stackOpStatusFor(err) // R-569: by kind, never by the error's words
|
||||||
if strings.Contains(err.Error(), "protected") {
|
|
||||||
status = http.StatusForbidden
|
|
||||||
}
|
|
||||||
if strings.Contains(err.Error(), "not found") {
|
|
||||||
status = http.StatusNotFound
|
|
||||||
}
|
|
||||||
if strings.Contains(err.Error(), "not deployed") || strings.Contains(err.Error(), "still running") {
|
|
||||||
status = http.StatusConflict
|
|
||||||
}
|
|
||||||
writeJSON(w, status, apiResponse{OK: false, Error: r.errText(req, err)})
|
writeJSON(w, status, apiResponse{OK: false, Error: r.errText(req, err)})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -1069,9 +1100,25 @@ func (r *Router) removeStack(w http.ResponseWriter, req *http.Request, name stri
|
|||||||
if body.RemoveBackups && r.backupMgr != nil && len(mirrorDirs) > 0 {
|
if body.RemoveBackups && r.backupMgr != nil && len(mirrorDirs) > 0 {
|
||||||
resp.BackupPathsRemoved = append(resp.BackupPathsRemoved, r.backupMgr.RemoveTier2Mirrors(name, mirrorDirs)...)
|
resp.BackupPathsRemoved = append(resp.BackupPathsRemoved, r.backupMgr.RemoveTier2Mirrors(name, mirrorDirs)...)
|
||||||
}
|
}
|
||||||
|
if body.RemoveBackups && r.backupMgr != nil && len(setAsideDirs) > 0 {
|
||||||
|
resp.BackupPathsRemoved = append(resp.BackupPathsRemoved, r.backupMgr.RemoveSetAsideUnits(name, setAsideDirs)...)
|
||||||
|
}
|
||||||
if body.RemoveBackups {
|
if body.RemoveBackups {
|
||||||
resp.BackupPathsRemoved = append(resp.BackupPathsRemoved, r.removeVerificationCopy(name)...)
|
resp.BackupPathsRemoved = append(resp.BackupPathsRemoved, r.removeVerificationCopy(name)...)
|
||||||
}
|
}
|
||||||
|
// D72 / D84 (`07` §8.2f): „delete backup data” deletes the LOCAL backups now (above) and starts the 30 days of
|
||||||
|
// the app's OFF-SITE copies: the end record, and the household's one mail. Never on a removal that kept the
|
||||||
|
// backups; never on a box without the hub-provisioned tier (nothing would carry the deletion out).
|
||||||
|
if body.RemoveBackups && r.backupMgr != nil {
|
||||||
|
switch rec, created, serr := r.backupMgr.StartOffsiteEnd(name); {
|
||||||
|
case errors.Is(serr, backup.ErrOffsiteEndNotOffered):
|
||||||
|
r.dbg("removeStack: %s: no hub-provisioned off-site tier — no off-site end record", name)
|
||||||
|
case serr != nil:
|
||||||
|
r.logger.Printf("[WARN] [api] remove %s: its off-site end record was NOT written (%v) — its off-site copies stay; the Backups page offers „delete in 30 days”", name, serr)
|
||||||
|
case created:
|
||||||
|
r.logger.Printf("[INFO] [api] remove %s: its off-site copies end %s (D72)", name, rec.EndsAt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// R-486 (v0.240.0): the app's backup preferences — and with them the Tier-2 RECORD that
|
// R-486 (v0.240.0): the app's backup preferences — and with them the Tier-2 RECORD that
|
||||||
// tier2RecordedCopyDir needs — are forgotten ONLY when the customer asked for the backups to be
|
// tier2RecordedCopyDir needs — are forgotten ONLY when the customer asked for the backups to be
|
||||||
@@ -1137,16 +1184,7 @@ func (r *Router) deleteStack(w http.ResponseWriter, req *http.Request, name stri
|
|||||||
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: refused.Message})
|
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: refused.Message})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
status := http.StatusInternalServerError
|
status := stackOpStatusFor(err) // R-569: by kind, never by the error's words
|
||||||
if strings.Contains(err.Error(), "protected") {
|
|
||||||
status = http.StatusForbidden
|
|
||||||
}
|
|
||||||
if strings.Contains(err.Error(), "not found") {
|
|
||||||
status = http.StatusNotFound
|
|
||||||
}
|
|
||||||
if strings.Contains(err.Error(), "not orphaned") || strings.Contains(err.Error(), "still running") {
|
|
||||||
status = http.StatusConflict
|
|
||||||
}
|
|
||||||
writeJSON(w, status, apiResponse{OK: false, Error: r.errText(req, err)})
|
writeJSON(w, status, apiResponse{OK: false, Error: r.errText(req, err)})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -1169,9 +1207,9 @@ func (r *Router) triggerSync(w http.ResponseWriter, _ *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Router) systemInfo(w http.ResponseWriter, _ *http.Request) {
|
func (r *Router) systemInfo(w http.ResponseWriter, _ *http.Request) {
|
||||||
// R-490 / R-465: the same default-storage-path fallback every other reader of the always-empty
|
// R-490 / R-465 / R-492: the default storage path is the only source (the always-empty global
|
||||||
// cfg.Paths.HDDPath has; without it hdd_configured was false on every box.
|
// paths.hdd_path was deleted in R-492); without it hdd_configured was false on every box.
|
||||||
hddPath := r.cfg.Paths.HDDPath
|
hddPath := ""
|
||||||
if r.sett != nil {
|
if r.sett != nil {
|
||||||
if p := r.sett.GetDefaultStoragePath(); p != "" {
|
if p := r.sett.GetDefaultStoragePath(); p != "" {
|
||||||
hddPath = p
|
hddPath = p
|
||||||
@@ -1514,97 +1552,6 @@ func (r *Router) selfupdateTrigger(w http.ResponseWriter, req *http.Request) {
|
|||||||
writeJSON(w, http.StatusOK, apiResponse{OK: true, Message: r.msg(req, "api.update.kicked_off")})
|
writeJSON(w, http.StatusOK, apiResponse{OK: true, Message: r.msg(req, "api.update.kicked_off")})
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Config apply handler ---
|
|
||||||
|
|
||||||
func (r *Router) configApply(w http.ResponseWriter, req *http.Request) {
|
|
||||||
r.dbg("configApply: contentLength=%d remoteAddr=%s", req.ContentLength, req.RemoteAddr)
|
|
||||||
// Read YAML body (limit to 1MB)
|
|
||||||
body, err := io.ReadAll(io.LimitReader(req.Body, 1<<20))
|
|
||||||
if err != nil {
|
|
||||||
writeJSON(w, http.StatusBadRequest, apiResponse{OK: false, Error: "failed to read request body"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if len(body) == 0 {
|
|
||||||
writeJSON(w, http.StatusBadRequest, apiResponse{OK: false, Error: "empty request body"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate it's parseable YAML by attempting to load it
|
|
||||||
if _, err := config.LoadFromBytes(body); err != nil {
|
|
||||||
r.logger.Printf("[WARN] [api] Config apply rejected: invalid YAML: %v", err)
|
|
||||||
writeJSON(w, http.StatusBadRequest, apiResponse{OK: false, Error: fmt.Sprintf("invalid config YAML: %v", err)})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// No-op guard: if the pushed config is byte-identical to what is already on disk, do
|
|
||||||
// nothing — don't rewrite, don't restart. The hub may re-push the same config
|
|
||||||
// idempotently, and a self-restart on every push would be a needless flap.
|
|
||||||
if prior, rerr := os.ReadFile(r.configPath); rerr == nil && bytes.Equal(prior, body) {
|
|
||||||
r.logger.Printf("[INFO] [api] Config apply: identical to current config (%d bytes) — no change, no restart", len(body))
|
|
||||||
writeJSON(w, http.StatusOK, apiResponse{OK: true, Message: r.msg(req, "api.config.unchanged")})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write config 0600: it holds infra credentials (cf_api_token, cf_tunnel_token, hub api_key) in
|
|
||||||
// plaintext (F8), so it must not be world-readable. writeConfig0600 enforces the mode even when the
|
|
||||||
// target file already existed with looser perms (os.WriteFile does not chmod an existing file).
|
|
||||||
if err := writeConfig0600(r.configPath, body); err != nil {
|
|
||||||
r.logger.Printf("[ERROR] [api] Config apply: failed to write config: %v", err)
|
|
||||||
writeJSON(w, http.StatusInternalServerError, apiResponse{OK: false, Error: "failed to apply config"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Respond to the hub FIRST (and flush), THEN self-restart. The new config only takes
|
|
||||||
// effect on restart — singletons such as the Cloudflare client are built once at
|
|
||||||
// startup, so an in-process write alone would leave e.g. a rotated CF token unused.
|
|
||||||
r.logger.Printf("[INFO] [api] Config applied from Hub (%d bytes) — self-restarting to take effect", len(body))
|
|
||||||
writeJSON(w, http.StatusOK, apiResponse{OK: true, Message: r.msg(req, "api.config.applied")})
|
|
||||||
flushResponse(w)
|
|
||||||
if r.restart != nil {
|
|
||||||
r.restart()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// writeConfig0600 writes config bytes to path with mode 0600, atomically when possible (tmp+rename),
|
|
||||||
// falling back to a direct write for Docker bind mounts (where os.Rename returns EBUSY). It ALWAYS
|
|
||||||
// enforces 0600 on the final file — even if it already existed with looser perms — because controller.yaml
|
|
||||||
// holds infra credentials in plaintext (F8); os.WriteFile only applies the mode when creating a new file.
|
|
||||||
func writeConfig0600(path string, body []byte) error {
|
|
||||||
tmpPath := path + ".tmp"
|
|
||||||
if err := os.WriteFile(tmpPath, body, 0600); err != nil {
|
|
||||||
return fmt.Errorf("writing temp config: %w", err)
|
|
||||||
}
|
|
||||||
if err := os.Rename(tmpPath, path); err != nil {
|
|
||||||
os.Remove(tmpPath)
|
|
||||||
if err := os.WriteFile(path, body, 0600); err != nil { // bind-mount fallback
|
|
||||||
return fmt.Errorf("writing config: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := os.Chmod(path, 0600); err != nil {
|
|
||||||
return fmt.Errorf("chmod config 0600: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Router) configHash(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
hash, err := config.FileHash(r.configPath)
|
|
||||||
if err != nil {
|
|
||||||
writeJSON(w, http.StatusInternalServerError, apiResponse{OK: false, Error: "failed to read config"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeJSON(w, http.StatusOK, apiResponse{OK: true, Data: map[string]string{"hash": hash, "path": filepath.Base(r.configPath)}})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Router) configContent(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
data, err := os.ReadFile(r.configPath)
|
|
||||||
if err != nil {
|
|
||||||
writeJSON(w, http.StatusInternalServerError, apiResponse{OK: false, Error: "failed to read config"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "text/yaml; charset=utf-8")
|
|
||||||
w.Write(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Asset sync handlers ---
|
// --- Asset sync handlers ---
|
||||||
|
|
||||||
func (r *Router) triggerAssetSync(w http.ResponseWriter, req *http.Request) {
|
func (r *Router) triggerAssetSync(w http.ResponseWriter, req *http.Request) {
|
||||||
@@ -1649,3 +1596,13 @@ func startAnswer(name, action, state string) apiResponse {
|
|||||||
Message: "Stack " + name + " " + action + " requested — state now: " + state,
|
Message: "Stack " + name + " " + action + " requested — state now: " + state,
|
||||||
Data: map[string]interface{}{"state": state}}
|
Data: map[string]interface{}{"state": state}}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// deployWarningData renders the deploy's soft warning for the answer. R-575: DeployStack hands back the
|
||||||
|
// warning's bundle KEY, never a sentence, so it is rendered here in the reader's language. nil = none.
|
||||||
|
// Pinned by TestR575_OvercommitWarningFollowsTheLanguage.
|
||||||
|
func (r *Router) deployWarningData(req *http.Request, warningKey string) map[string]string {
|
||||||
|
if warningKey == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return map[string]string{"warning": r.msg(req, warningKey)}
|
||||||
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -28,61 +27,6 @@ func newRestartTestRouter(t *testing.T, prior []byte) (*Router, *int, string) {
|
|||||||
return r, &calls, path
|
return r, &calls, path
|
||||||
}
|
}
|
||||||
|
|
||||||
// a minimal config that passes config.LoadFromBytes (customer.id + customer.domain required).
|
|
||||||
var validConfig = []byte("customer:\n id: test\n domain: test.example\n")
|
|
||||||
|
|
||||||
func TestConfigApply_ChangedConfig_Restarts(t *testing.T) {
|
|
||||||
prior := []byte("customer:\n id: old\n domain: old.example\n")
|
|
||||||
r, calls, path := newRestartTestRouter(t, prior)
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/config/apply", bytes.NewReader(validConfig))
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
r.configApply(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
if *calls != 1 {
|
|
||||||
t.Fatalf("restart called %d times, want 1 (config changed)", *calls)
|
|
||||||
}
|
|
||||||
got, _ := os.ReadFile(path)
|
|
||||||
if !bytes.Equal(got, validConfig) {
|
|
||||||
t.Fatalf("config not written: got %q", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// COMPANION: an identical re-push must NOT restart (the old handler always restarted /
|
|
||||||
// always ran its post-apply hook regardless of whether anything changed).
|
|
||||||
func TestConfigApply_IdenticalConfig_NoRestart(t *testing.T) {
|
|
||||||
r, calls, _ := newRestartTestRouter(t, validConfig) // prior == body
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/config/apply", bytes.NewReader(validConfig))
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
r.configApply(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
if *calls != 0 {
|
|
||||||
t.Fatalf("restart called %d times, want 0 (config byte-identical)", *calls)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestConfigApply_InvalidYAML_NoRestart(t *testing.T) {
|
|
||||||
r, calls, _ := newRestartTestRouter(t, validConfig)
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/config/apply", bytes.NewReader([]byte("customer:\n id: only-id-no-domain\n")))
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
r.configApply(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusBadRequest {
|
|
||||||
t.Fatalf("status = %d, want 400 (missing customer.domain)", rec.Code)
|
|
||||||
}
|
|
||||||
if *calls != 0 {
|
|
||||||
t.Fatalf("restart called %d times, want 0 (validation failed)", *calls)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSelfRestart_InvokesRestarter(t *testing.T) {
|
func TestSelfRestart_InvokesRestarter(t *testing.T) {
|
||||||
r, calls, _ := newRestartTestRouter(t, nil)
|
r, calls, _ := newRestartTestRouter(t, nil)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Found walking the capability map's B2 („App lifecycle") on 9202, 2026-10-28 night: a Stop of a name that is no app
|
||||||
|
// on this box (`felhom-controller` — bootstrap-managed, not a stack) answered 500 „…az alkalmazás beállításai nem
|
||||||
|
// menthetők." — the desired-state write's „not found" read as a save failure. It is a 404 now, before any intent is
|
||||||
|
// recorded. RED-PROOF: drop the ErrStackNotFound branch in actionStack → 500 → FAILS.
|
||||||
|
func TestAnActionOnANameThatIsNoAppIsA404(t *testing.T) {
|
||||||
|
r, _, _, _ := newSlice4Router(t)
|
||||||
|
for _, action := range []string{"stop", "start"} {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.actionStack(w, httptest.NewRequest("POST", "/api/stacks/nosuchapp/"+action, nil), action, "nosuchapp")
|
||||||
|
var resp apiResponse
|
||||||
|
_ = json.Unmarshal(w.Body.Bytes(), &resp)
|
||||||
|
if w.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("%s of a name that is no app: %d %q — want 404", action, w.Code, resp.Error)
|
||||||
|
}
|
||||||
|
if strings.Contains(strings.ToLower(resp.Error), "mentheto") || strings.Contains(resp.Error, "menthetők") {
|
||||||
|
t.Fatalf("%s: the answer still blames a save: %q", action, resp.Error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -87,6 +87,20 @@ type RecoveryInfo struct {
|
|||||||
// `installed_images`, as `ref@digest` (the plain ref when no digest was recorded). Stamped beside each
|
// `installed_images`, as `ref@digest` (the plain ref when no digest was recorded). Stamped beside each
|
||||||
// data file the backup writes, so the data says which versions wrote it. Nil = unknown, never current.
|
// data file the backup writes, so the data says which versions wrote it. Nil = unknown, never current.
|
||||||
InstalledImages map[string]string
|
InstalledImages map[string]string
|
||||||
|
// SetupGate (v0.314.0, R-1057) is the app's setup gate AT THIS BACKUP: „closed" (its first setup was not done) or
|
||||||
|
// „open" (and by whom). Nil for an app whose template has no gate. The restore applies it, so a backup made before
|
||||||
|
// the household's first setup never comes back open (`09` §3 decision 253).
|
||||||
|
SetupGate *GateState
|
||||||
|
// InstallID (D47, R-1269) is the install the app's data belongs to (app.yaml `install_id:`); "" for an app installed
|
||||||
|
// before D47. The unit records it, and a backup of another install never writes into that unit (backup/unit_owner.go).
|
||||||
|
InstallID string
|
||||||
|
}
|
||||||
|
|
||||||
|
// GateState is the setup gate as a backup records it (the unit's app.yaml `setup_gate:`). The same two keys as the
|
||||||
|
// live app.yaml's record, so a restore reads either file the same way (stacks.ReadGateAtBackup).
|
||||||
|
type GateState struct {
|
||||||
|
State string `yaml:"state"`
|
||||||
|
OpenedBy string `yaml:"opened_by,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseComposeImages extracts the pinned image references (`image: repo:tag`) from a
|
// ParseComposeImages extracts the pinned image references (`image: repo:tag`) from a
|
||||||
|
|||||||
@@ -51,6 +51,19 @@ type BackupSpec struct {
|
|||||||
// WHOLE-BLOCK, so a stale `userdata: import/<app>` would discard the app's OTHER classifications
|
// WHOLE-BLOCK, so a stale `userdata: import/<app>` would discard the app's OTHER classifications
|
||||||
// (e.g. an hdd appdata path classed mandatory) and silently degrade it to legacy.
|
// (e.g. an hdd appdata path classed mandatory) and silently degrade it to legacy.
|
||||||
Import []BindSpec `yaml:"import,omitempty" json:"import,omitempty"`
|
Import []BindSpec `yaml:"import,omitempty" json:"import,omitempty"`
|
||||||
|
// Volumes classifies the compose file's top-level NAMED volumes (R-49, operator ruling D21 = B, 2026-10-22).
|
||||||
|
// Only `excluded` means anything: the volume is never dumped, so it is in no recovery unit — not on the
|
||||||
|
// drive's copy, the second drive or off-site. For a pure cache the app rebuilds by itself (Immich's model
|
||||||
|
// cache). Deliberately NOT checked by ValidateBackupSpec: a wrong entry must never cost the app its bind
|
||||||
|
// classifications (that rejection is whole-block) — ExcludedDockerVolumes ignores it with a reason instead.
|
||||||
|
Volumes []VolumeSpec `yaml:"volumes,omitempty" json:"volumes,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// VolumeSpec is one classified named volume: Name is the compose `volumes:` key (not the project-prefixed
|
||||||
|
// Docker name).
|
||||||
|
type VolumeSpec struct {
|
||||||
|
Name string `yaml:"name" json:"name"`
|
||||||
|
Class BindClass `yaml:"class" json:"class"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// BindSpec is one classified entry in a BackupSpec.
|
// BindSpec is one classified entry in a BackupSpec.
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package appbackup
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -41,6 +42,9 @@ func dbTypeForImage(image string) (DBType, bool) {
|
|||||||
return DBType(""), false
|
return DBType(""), false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DBTypeForImage is dbTypeForImage for other packages (R-1187 g: the .fab import classifies with the SAME predicate).
|
||||||
|
func DBTypeForImage(image string) (DBType, bool) { return dbTypeForImage(image) }
|
||||||
|
|
||||||
// composeServicesDoc is the minimal view of a compose file needed here: the `services:` MAP and each
|
// composeServicesDoc is the minimal view of a compose file needed here: the `services:` MAP and each
|
||||||
// service's `image:`. Deliberately a real YAML parse and not a line scan — a top-level `volumes:`
|
// service's `image:`. Deliberately a real YAML parse and not a line scan — a top-level `volumes:`
|
||||||
// block (immich's `immich_ml_cache:`) has exactly the shape a naive scan misreads as a service, and
|
// block (immich's `immich_ml_cache:`) has exactly the shape a naive scan misreads as a service, and
|
||||||
@@ -80,3 +84,121 @@ func DBServiceNames(composePath string) ([]string, error) {
|
|||||||
sort.Strings(names)
|
sort.Strings(names)
|
||||||
return names, nil
|
return names, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// dbCredentialKeyRe matches a database service's credential variable (POSTGRES_PASSWORD, MARIADB_ROOT_PASSWORD,
|
||||||
|
// MYSQL_PASSWORD, …): the engine images read these ONLY when they initialise an empty data directory, so once a
|
||||||
|
// restore puts a data directory back, the value that matches it is the one it was created with (R-1106).
|
||||||
|
var dbCredentialKeyRe = regexp.MustCompile(`^(POSTGRES|PG|MARIADB|MYSQL)_[A-Z_]*PASSWORD$`)
|
||||||
|
|
||||||
|
// interpRefRe pulls the variable names out of a compose value: ${NAME}, ${NAME:-x}, ${NAME-x}, $NAME.
|
||||||
|
var interpRefRe = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)(?:[:]?[-?+][^}]*)?\}|\$([A-Za-z_][A-Za-z0-9_]*)`)
|
||||||
|
|
||||||
|
type composeDBEnvDoc struct {
|
||||||
|
Services map[string]struct {
|
||||||
|
Image string `yaml:"image"`
|
||||||
|
Environment yaml.Node `yaml:"environment"`
|
||||||
|
} `yaml:"services"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DBCredentialVars (R-1106, `07` §7.4 — operator decision 1A, 2026-10-16) returns the sorted, unique app.yaml
|
||||||
|
// variable names that feed a database service's credential variables in composePath — e.g. rallly's
|
||||||
|
// `POSTGRES_PASSWORD=${DB_PASSWORD}` → DB_PASSWORD. These are the values a restore must put back WITH the data it puts
|
||||||
|
// back: a fresh install's generated value does not open a restored data directory. A literal credential (no
|
||||||
|
// variable) yields nothing — there is nothing to carry. Same parse and same DB predicate as DBServiceNames, so the
|
||||||
|
// two cannot disagree about which services hold a database. Pinned by TestR1106_DBCredentialVars*.
|
||||||
|
func DBCredentialVars(composePath string) ([]string, error) {
|
||||||
|
data, err := os.ReadFile(composePath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("reading compose file: %w", err)
|
||||||
|
}
|
||||||
|
var doc composeDBEnvDoc
|
||||||
|
if err := yaml.Unmarshal(data, &doc); err != nil {
|
||||||
|
return nil, fmt.Errorf("parsing compose file %s: %w", composePath, err)
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
add := func(key, val string) {
|
||||||
|
if !dbCredentialKeyRe.MatchString(key) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, m := range interpRefRe.FindAllStringSubmatch(val, -1) {
|
||||||
|
n := m[1]
|
||||||
|
if n == "" {
|
||||||
|
n = m[2]
|
||||||
|
}
|
||||||
|
seen[n] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, svc := range doc.Services {
|
||||||
|
if _, ok := dbTypeForImage(svc.Image); !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
env := svc.Environment
|
||||||
|
switch env.Kind {
|
||||||
|
case yaml.SequenceNode: // - KEY=value
|
||||||
|
for _, it := range env.Content {
|
||||||
|
if k, v, ok := strings.Cut(it.Value, "="); ok {
|
||||||
|
add(strings.TrimSpace(k), v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case yaml.MappingNode: // KEY: value
|
||||||
|
for i := 0; i+1 < len(env.Content); i += 2 {
|
||||||
|
add(env.Content[i].Value, env.Content[i+1].Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out := make([]string, 0, len(seen))
|
||||||
|
for n := range seen {
|
||||||
|
out = append(out, n)
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type composeDBVolDoc struct {
|
||||||
|
Services map[string]struct {
|
||||||
|
Image string `yaml:"image"`
|
||||||
|
Volumes []interface{} `yaml:"volumes"`
|
||||||
|
} `yaml:"services"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DBDataVolumes (R-1106) returns the sorted NAMED volumes (not binds) that a database service in composePath mounts —
|
||||||
|
// its data directory. A restore that replays one of these puts back a data directory that only its own password
|
||||||
|
// opens; a restore that replays only a logical dump does not, and the current password stays right.
|
||||||
|
func DBDataVolumes(composePath string) ([]string, error) {
|
||||||
|
data, err := os.ReadFile(composePath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("reading compose file: %w", err)
|
||||||
|
}
|
||||||
|
var doc composeDBVolDoc
|
||||||
|
if err := yaml.Unmarshal(data, &doc); err != nil {
|
||||||
|
return nil, fmt.Errorf("parsing compose file %s: %w", composePath, err)
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, svc := range doc.Services {
|
||||||
|
if _, ok := dbTypeForImage(svc.Image); !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, v := range svc.Volumes {
|
||||||
|
var src string
|
||||||
|
switch t := v.(type) {
|
||||||
|
case string:
|
||||||
|
src, _, _ = strings.Cut(t, ":")
|
||||||
|
case map[string]interface{}:
|
||||||
|
if typ, _ := t["type"].(string); typ != "" && typ != "volume" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
src, _ = t["source"].(string)
|
||||||
|
}
|
||||||
|
if src == "" || strings.ContainsAny(src, "/.$~") {
|
||||||
|
continue // a bind or an interpolated path — not a named volume
|
||||||
|
}
|
||||||
|
seen[src] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out := make([]string, 0, len(seen))
|
||||||
|
for n := range seen {
|
||||||
|
out = append(out, n)
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
Loaded 100 of 868 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user