@crvouga/homelab 0.23.6 → 0.23.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -152,6 +152,9 @@
152
152
  # the I/O weights of T3 and the agents without effect. The user manager takes it on its next start.
153
153
  [Service]
154
154
  Delegate=cpu io memory pids
155
+ # Override Ubuntu's ancestor PSI killer for this worker user only.
156
+ # Local MemoryHigh reclaim is bounded by the existing hard caps.
157
+ ManagedOOMMemoryPressure=auto
155
158
  loop_control:
156
159
  label: '{{ item.dest }}'
157
160
  register: slice_policy
@@ -201,8 +204,9 @@
201
204
  TasksMax={{ resourceSafety.agentSlice.tasks }}
202
205
  CPUWeight={{ resourceSafety.agentSlice.weight }}
203
206
  IOWeight={{ resourceSafety.agentSlice.weight }}
204
- ManagedOOMMemoryPressure=kill
205
- ManagedOOMMemoryPressureLimit={{ resourceSafety.agentSlice.oomPressurePercent }}%
207
+ # Reclaim at MemoryHigh must not terminate whole sessions. Host-level
208
+ # guards and hard memory caps still contain runaway workloads.
209
+ ManagedOOMMemoryPressure=auto
206
210
  loop:
207
211
  - unit: app-t3code-agents
208
212
  high: '{{ resourceSafety.agentSlice.highPercent }}'
@@ -211,19 +215,45 @@
211
215
  high: '{{ resourceSafety.agentSlice.threadHighPercent }}'
212
216
  max: '{{ resourceSafety.agentSlice.threadMaxPercent }}'
213
217
  register: agent_slices
214
- - name: Restore the declared properties over systemctl set-property overrides
218
+ - name: Find property overrides for agent slices
219
+ become: true
220
+ become_user: '{{ development_user }}'
221
+ ansible.builtin.find:
222
+ paths:
223
+ - '{{ development_home }}/.config/systemd/user.control'
224
+ - '/run/user/{{ development_uid }}/systemd/user.control'
225
+ recurse: true
226
+ file_type: file
227
+ patterns:
228
+ - 50-MemoryHigh.conf
229
+ - 50-MemoryMax.conf
230
+ - 50-MemorySwapMax.conf
231
+ - 50-TasksMax.conf
232
+ - 50-CPUWeight.conf
233
+ - 50-IOWeight.conf
234
+ - 50-ManagedOOMMemoryPressure.conf
235
+ - 50-ManagedOOMMemoryPressureLimit.conf
236
+ register: agent_override_files
237
+ - name: Restore declared properties for aggregate and existing thread slices
215
238
  become: true
216
239
  become_user: '{{ development_user }}'
217
240
  ansible.builtin.file:
218
- path: '{{ item.0 }}/systemd/user.control/app-t3code-agents.slice.d/50-{{ item.1 }}.conf'
241
+ path: '{{ item.path }}'
219
242
  state: absent
220
- loop: "{{ [development_home ~ '/.config', '/run/user/' ~ development_uid] | product(['MemoryHigh', 'MemoryMax', 'MemorySwapMax', 'TasksMax', 'CPUWeight', 'IOWeight']) | list }}"
243
+ loop: '{{ agent_override_files.files }}'
244
+ when: item.path is match('^.*/app-t3code-agents(?:-[^/]*)?\.slice\.d/50-[^/]+\.conf$')
221
245
  register: agent_overrides
246
+ - name: Restore declared pressure policy over worker user-service overrides
247
+ ansible.builtin.file:
248
+ path: '{{ item.0 }}/systemd/system.control/user@{{ development_uid }}.service.d/50-{{ item.1 }}.conf'
249
+ state: absent
250
+ loop: "{{ ['/etc', '/run'] | product(['ManagedOOMMemoryPressure', 'ManagedOOMMemoryPressureLimit']) | list }}"
251
+ register: user_service_overrides
222
252
  - name: Apply slice limits without restarting services
223
253
  ansible.builtin.systemd_service:
224
254
  daemon_reload: true
225
- when: slice_policy.changed
226
- - name: Load the agent limits into the running user manager for new agents
255
+ when: slice_policy.changed or user_service_overrides.changed
256
+ - name: Apply agent slice policy to the running user manager without restarting agents
227
257
  become: true
228
258
  become_user: '{{ development_user }}'
229
259
  environment:
@@ -313,6 +343,14 @@
313
343
  checksum_algorithm: sha256
314
344
  register: disk_guard_source
315
345
  when: development_source is defined
346
+ - name: Install the tracked disk guard outside pruned revisions
347
+ ansible.builtin.copy:
348
+ src: '{{ playbook_dir }}/disk-guard.py'
349
+ dest: '{{ resourceSafety.diskGuardScript }}'
350
+ owner: root
351
+ group: root
352
+ mode: '0644'
353
+ when: development_source is defined and disk_guard_source.stat.exists
316
354
  - name: Declare the disk guard service
317
355
  ansible.builtin.copy:
318
356
  dest: /etc/systemd/system/personal-fleet-disk-guard.service
@@ -327,7 +365,7 @@
327
365
  StartLimitIntervalSec=0
328
366
  [Service]
329
367
  Type=simple
330
- ExecStart=/usr/bin/python3 -I -B {{ disk_guard_source.stat.path }} --path / --path {{ development_home }} --floor-mib {{ worker_disk_guard_floor_mib }} --inode-floor-percent {{ resourceSafety.inodeFailFreePercent }} --managed-cgroup /sys/fs/cgroup/system.slice/personal-fleet-disk-gc.service --write-mib {{ resourceSafety.diskGuardWriteMiB }} --interval {{ resourceSafety.diskGuardIntervalSeconds }}
368
+ ExecStart=/usr/bin/python3 -I -B {{ resourceSafety.diskGuardScript }} --path / --path {{ development_home }} --floor-mib {{ worker_disk_guard_floor_mib }} --inode-floor-percent {{ resourceSafety.inodeFailFreePercent }} --managed-cgroup /sys/fs/cgroup/system.slice/personal-fleet-disk-gc.service --write-mib {{ resourceSafety.diskGuardWriteMiB }} --interval {{ resourceSafety.diskGuardIntervalSeconds }}
331
369
  Restart=always
332
370
  RestartSec=5
333
371
  OOMScoreAdjust=-1000
@@ -362,6 +400,16 @@
362
400
  checksum_algorithm: sha256
363
401
  register: disk_gc_source
364
402
  when: development_source is defined
403
+ # Keep the running collector outside the revision cache it prunes. This also
404
+ # supports applying the resource play independently of a toolchain/T3 rollout.
405
+ - name: Install the tracked disk GC outside pruned revisions
406
+ ansible.builtin.copy:
407
+ src: '{{ playbook_dir }}/disk-gc.py'
408
+ dest: '{{ resourceSafety.diskGcScript }}'
409
+ owner: root
410
+ group: root
411
+ mode: '0644'
412
+ when: development_source is defined and disk_gc_source.stat.exists
365
413
  # storage.disposable in fleet.json (fleet_storage_disposable) switches every
366
414
  # node to the disposable policy (docs/ubuntu-sync.md, Disk GC): hours instead
367
415
  # of days, worktrees saved in a recovery ref or done with on their remote,
@@ -392,7 +440,7 @@
392
440
  After=docker.service
393
441
  [Service]
394
442
  Type=oneshot
395
- ExecStart=/usr/bin/python3 -I -B {{ disk_gc_source.stat.path }} --home {{ development_home }} --git-temp-hours {{ resourceSafety.diskGcGitTempHours }} --fetch-max-mib {{ resourceSafety.diskGcFetchMaxMiB }} --path / --path {{ development_home }} --idle-days {{ gc_idle_days }} --pressure-mib {{ worker_disk_gc_pressure_mib }}{{ (' --target-used-percent ' ~ (fleet_storage_target_used_percent | default(gc_disposable.targetUsedPercent))) if disposable else '' }} --pressure-inode-percent {{ resourceSafety.inodeWarnFreePercent }} --pressure-idle-hours {{ resourceSafety.diskGcPressureIdleHours }} --docker-age-hours {{ resourceSafety.diskGcDockerAgeHours }} --pressure-docker-age-hours {{ resourceSafety.diskGcPressureDockerAgeHours }} --docker-cap-percent {{ resourceSafety.diskGcBuildCachePercent }} --host-var-tmp /run/homelab-host-var-tmp --host-tmp /run/homelab-host-tmp --mise-cache-mib {{ resourceSafety.diskGcMiseCacheMiB }} --home-cache-mib {{ resourceSafety.diskGcHomeCacheMiB }}{% for cache in resourceSafety.diskGcExcludedCaches %} --exclude-cache {{ cache }}{% endfor %}{% for store, mib in resourceSafety.diskGcStoreCapsMiB.items() %} --store-cap {{ store }}={{ mib }}{% endfor %}{% for root in resourceSafety.diskGcWorktreeRoots %} --worktree-root {{ root }}{% endfor %} --worktree-idle-days {{ gc_worktree_idle_days }}{{ ' --disposable' if disposable else '' }}{% for cache, mib in resourceSafety.diskGcCacheCapsMiB.items() %} --cache-cap {{ cache }}={{ mib }}{% endfor %} --keep-newest /var/cache/personal-fleet={{ resourceSafety.diskGcPackagesKept }}{% for root in resourceSafety.diskGcCheckoutRoots %} --keep-checkouts {{ root }}={{ resourceSafety.diskGcCheckoutsKept }}{% endfor %} --current {{ resourceSafety.diskGcCurrentCheckout }}{% for directory, hours in resourceSafety.diskGcExpireHours.items() %} --expire {{ directory }}={{ hours }}{% endfor %} --report {{ resourceSafety.diskGcReport }} --mise {{ development_home }}/.local/bin/mise --user {{ development_user }}{{ '' if worker_containers_on | default(true) | bool else ' --no-docker' }}
443
+ ExecStart=/usr/bin/python3 -I -B {{ resourceSafety.diskGcScript }} --home {{ development_home }} --git-temp-hours {{ resourceSafety.diskGcGitTempHours }} --fetch-max-mib {{ resourceSafety.diskGcFetchMaxMiB }} --path / --path {{ development_home }} --idle-days {{ gc_idle_days }} --pressure-mib {{ worker_disk_gc_pressure_mib }}{{ (' --target-used-percent ' ~ (fleet_storage_target_used_percent | default(gc_disposable.targetUsedPercent))) if disposable else '' }} --pressure-inode-percent {{ resourceSafety.inodeWarnFreePercent }} --pressure-idle-hours {{ resourceSafety.diskGcPressureIdleHours }} --docker-age-hours {{ resourceSafety.diskGcDockerAgeHours }} --pressure-docker-age-hours {{ resourceSafety.diskGcPressureDockerAgeHours }} --docker-cap-percent {{ resourceSafety.diskGcBuildCachePercent }} --host-var-tmp /run/homelab-host-var-tmp --host-tmp /run/homelab-host-tmp --mise-cache-mib {{ resourceSafety.diskGcMiseCacheMiB }} --home-cache-mib {{ resourceSafety.diskGcHomeCacheMiB }}{% for cache in resourceSafety.diskGcExcludedCaches %} --exclude-cache {{ cache }}{% endfor %}{% for store, mib in resourceSafety.diskGcStoreCapsMiB.items() %} --store-cap {{ store }}={{ mib }}{% endfor %}{% for root in resourceSafety.diskGcWorktreeRoots %} --worktree-root {{ root }}{% endfor %} --worktree-idle-days {{ gc_worktree_idle_days }}{{ ' --disposable' if disposable else '' }}{% for cache, mib in resourceSafety.diskGcCacheCapsMiB.items() %} --cache-cap {{ cache }}={{ mib }}{% endfor %} --keep-newest /var/cache/personal-fleet={{ resourceSafety.diskGcPackagesKept }}{% for root in resourceSafety.diskGcCheckoutRoots %} --keep-checkouts {{ root }}={{ resourceSafety.diskGcCheckoutsKept }}{% endfor %} --current {{ resourceSafety.diskGcCurrentCheckout }}{% for directory, hours in resourceSafety.diskGcExpireHours.items() %} --expire {{ directory }}={{ hours }}{% endfor %} --report {{ resourceSafety.diskGcReport }} --mise {{ development_home }}/.local/bin/mise --user {{ development_user }}{{ '' if worker_containers_on | default(true) | bool else ' --no-docker' }}
396
444
 
397
445
  StateDirectory=personal-fleet-disk-gc
398
446
  StateDirectoryMode=0755
@@ -400,7 +448,7 @@
400
448
  Nice=19
401
449
  IOSchedulingClass=idle
402
450
  CPUQuota=50%
403
- MemoryMax=512M
451
+ MemoryMax={{ resourceSafety.diskGcMemoryMaxMiB }}M
404
452
  NoNewPrivileges=true
405
453
  PrivateTmp=true
406
454
  BindPaths=/var/tmp:/run/homelab-host-var-tmp /tmp:/run/homelab-host-tmp
@@ -0,0 +1,15 @@
1
+ GC failures retain the existing timestamp marker and a companion
2
+ `state/status/gc-failed.json` containing only the operation, stage and stable
3
+ error code. Stages distinguish credentials, checkpoint freshness, integrity,
4
+ retention, pruning and local worktrees. Subprocess output and exception text
5
+ are suppressed. A successful backup does not clear a GC failure.
6
+
7
+ `homelab proxy gc --dry-run` checks credentials without renewing them, reads
8
+ checkpoint freshness and integrity, and asks Restic to preview retention and
9
+ pruning without repository locks or writes. It checks local retirement
10
+ eligibility without removing worktrees or changing status markers. The preview
11
+ is an observation, not a reservation: apply rechecks all conditions.
12
+
13
+ `homelab proxy gc --local-only --dry-run` previews only clean retired worktree
14
+ cleanup; omit `--dry-run` to apply it without cloud access. Local cleanup never
15
+ advances cloud GC freshness or clears its failure marker.
@@ -17,14 +17,24 @@ os.umask(0o077)
17
17
  os.environ["PATH"] = str(root / "scripts") + ":" + os.environ["PATH"]
18
18
  state = root / "state"
19
19
  status = state / "status"
20
- status.mkdir(parents=True, exist_ok=True)
21
- lock = open(status / "operation.lock", "w")
22
- if os.geteuid() == 0:
23
- os.chown(status / "operation.lock", 1000, 1000)
24
- fcntl.flock(lock, fcntl.LOCK_EX)
25
20
  command = sys.argv[1] if len(sys.argv) > 1 else "backup"
21
+ flags = sys.argv[2:]
22
+ preview = command == "gc" and "--dry-run" in flags
23
+ local_only = command == "gc" and "--local-only" in flags
24
+ if command == "gc" and any(flag not in ["--dry-run", "--local-only"] for flag in flags):
25
+ sys.exit("Usage: gc [--dry-run] [--local-only]")
26
+ if not preview:
27
+ status.mkdir(parents=True, exist_ok=True)
28
+ lock = None
29
+ if not preview or (status / "operation.lock").exists():
30
+ lock = open(status / "operation.lock", "r" if preview else "a")
31
+ if os.geteuid() == 0 and not preview:
32
+ os.chown(status / "operation.lock", 1000, 1000)
33
+ fcntl.flock(lock, fcntl.LOCK_SH if preview else fcntl.LOCK_EX)
26
34
  failure = status / (
27
- "backup-failed"
35
+ "gc-local-failed"
36
+ if local_only
37
+ else "backup-failed"
28
38
  if command == "backup"
29
39
  else "backup-check-failed"
30
40
  if command in ["check", "check-full"]
@@ -35,6 +45,8 @@ failure = status / (
35
45
 
36
46
 
37
47
  def run(args, **kw):
48
+ kw.setdefault("stdout", subprocess.PIPE)
49
+ kw.setdefault("stderr", subprocess.PIPE)
38
50
  return subprocess.run(args, check=True, **kw)
39
51
 
40
52
 
@@ -44,191 +56,215 @@ def write(path, text):
44
56
  os.chown(path, 1000, 1000)
45
57
 
46
58
 
47
- try:
48
- retention.staging(root)
49
- spec = importlib.util.spec_from_file_location(
50
- "vault_access", root / "scripts/vault-access.py"
51
- )
52
- vault = importlib.util.module_from_spec(spec)
53
- spec.loader.exec_module(vault)
54
- vault.renew()
55
- cfg = vault.credentials()
56
- identity = {k: cfg[k] for k in ["S3_ENDPOINT", "S3_BUCKET", "S3_REGION"]}
57
- destination = state / "repository.json"
58
- if destination.exists() and json.loads(destination.read_text()) != identity:
59
- sys.exit(
60
- "Vault repository location changed. Review and update state/repository.json explicitly; refusing to silently switch repositories."
61
- )
62
- if not destination.exists() and command != "restore-cache":
63
- write(destination, json.dumps(identity) + "\n")
64
- if not cfg["S3_ENDPOINT"].startswith("https://"):
65
- raise ValueError("Storage endpoint must use TLS")
66
- env = os.environ.copy()
67
- env.update(
68
- AWS_ACCESS_KEY_ID=cfg["S3_ACCESS_KEY_ID"],
69
- AWS_SECRET_ACCESS_KEY=cfg["S3_SECRET_ACCESS_KEY"],
70
- AWS_DEFAULT_REGION=cfg["S3_REGION"],
71
- RESTIC_REPOSITORY="s3:"
72
- + cfg["S3_ENDPOINT"].rstrip("/")
73
- + "/"
74
- + cfg["S3_BUCKET"]
75
- + "/cliproxy-fleet/restic",
76
- RESTIC_PASSWORD_FILE=str(state / "secrets/restic-password"),
77
- )
78
-
79
- def restic(*args, **kw):
80
- return run(
81
- ["restic", "-o", "s3.bucket-lookup=path", *args, "--no-cache"],
82
- env=env,
83
- **kw,
84
- )
59
+ stage = "setup"
85
60
 
86
- if command == "init":
87
- restic("init")
88
- elif command == "check":
89
- restic("check", "--read-data-subset=10%")
90
- elif command == "check-full":
91
- restic("check", "--read-data")
92
- elif command == "gc":
93
- retention.prune(restic)
94
- removed = retention.revisions(root)
95
- write(
96
- status / "gc-success.json",
97
- json.dumps(
98
- {
99
- "time": datetime.datetime.now(datetime.timezone.utc).isoformat(),
100
- "retired_worktrees": removed,
101
- }
102
- )
103
- + "\n",
104
- )
105
- print(
106
- "Cloud garbage collected and integrity checked; retired clean worktrees removed:",
107
- removed,
61
+
62
+ def set_stage(value):
63
+ global stage
64
+ stage = value
65
+
66
+
67
+ try:
68
+ if local_only:
69
+ set_stage("local-worktrees")
70
+ removed = retention.revisions(root, dry_run=preview)
71
+ print(json.dumps(dict(operation="gc", local_only=True, preview=preview, worktrees=removed)))
72
+ else:
73
+ if not preview:
74
+ retention.staging(root)
75
+ spec = importlib.util.spec_from_file_location(
76
+ "vault_access", root / "scripts/vault-access.py"
108
77
  )
109
- elif command == "snapshots":
110
- restic("snapshots")
111
- elif command == "restore":
112
- if len(sys.argv) != 4:
113
- sys.exit("Usage: backup restore SNAPSHOT EMPTY_DIRECTORY")
114
- target = pathlib.Path(sys.argv[3]).resolve()
115
- if target.exists() and any(target.iterdir()):
116
- sys.exit("Restore target must be empty.")
117
- target.mkdir(parents=True, exist_ok=True)
118
- restic("restore", sys.argv[2], "--target", str(target), "--verify")
119
- elif command == "restore-cache":
120
- if sys.argv[2:] != ["--previous-node-stopped"]:
121
- raise ValueError("Explicit previous-node-stopped acknowledgement required")
122
- # This local check complements operator fencing of the previous machine.
123
- active = subprocess.check_output(
124
- [
125
- "docker",
126
- "compose",
127
- "--profile",
128
- "portable-endpoint",
129
- "--profile",
130
- "public-endpoint",
131
- "ps",
132
- "--status",
133
- "running",
134
- "--services",
135
- ],
136
- cwd=root,
137
- text=True,
138
- ).strip()
139
- if active:
140
- raise ValueError("Stop the local stack before recovery")
141
- with tempfile.TemporaryDirectory(
142
- prefix="restore-", dir=root / "recovery"
143
- ) as temporary:
144
- target = pathlib.Path(temporary)
145
- restic(
146
- "restore",
147
- "latest",
148
- "--tag",
149
- "cliproxy-checkpoint-v1",
150
- "--host",
151
- "cliproxy-primary",
152
- "--target",
153
- str(target),
154
- "--verify",
155
- stdout=subprocess.PIPE,
156
- stderr=subprocess.PIPE,
78
+ vault = importlib.util.module_from_spec(spec)
79
+ spec.loader.exec_module(vault)
80
+ set_stage("credentials")
81
+ if not preview:
82
+ vault.renew()
83
+ cfg = vault.credentials()
84
+ identity = {k: cfg[k] for k in ["S3_ENDPOINT", "S3_BUCKET", "S3_REGION"]}
85
+ destination = state / "repository.json"
86
+ if destination.exists() and json.loads(destination.read_text()) != identity:
87
+ sys.exit(
88
+ "Vault repository location changed. Review and update state/repository.json explicitly; refusing to silently switch repositories."
157
89
  )
158
- payload = checkpoint.locate(target)
159
- saved_destination = payload / "state/repository.json"
160
- if (
161
- not saved_destination.exists()
162
- or json.loads(saved_destination.read_text()) != identity
163
- ):
164
- raise ValueError("Recovered repository identity differs from Vault")
165
- checkpoint.hydrate(payload, state)
166
- print(
167
- "Cloud checkpoint recovered into empty cache. No services started. Run install, then health verification."
90
+ if not destination.exists() and command != "restore-cache" and not preview:
91
+ write(destination, json.dumps(identity) + "\n")
92
+ if not cfg["S3_ENDPOINT"].startswith("https://"):
93
+ raise ValueError("Storage endpoint must use TLS")
94
+ env = os.environ.copy()
95
+ env.update(
96
+ AWS_ACCESS_KEY_ID=cfg["S3_ACCESS_KEY_ID"],
97
+ AWS_SECRET_ACCESS_KEY=cfg["S3_SECRET_ACCESS_KEY"],
98
+ AWS_DEFAULT_REGION=cfg["S3_REGION"],
99
+ RESTIC_REPOSITORY="s3:"
100
+ + cfg["S3_ENDPOINT"].rstrip("/")
101
+ + "/"
102
+ + cfg["S3_BUCKET"]
103
+ + "/cliproxy-fleet/restic",
104
+ RESTIC_PASSWORD_FILE=str(state / "secrets/restic-password"),
168
105
  )
169
- elif command == "backup":
170
- if not (state / "secrets/recovery-confirmed").exists():
171
- sys.exit(
172
- "Store Restic password independently; then create state/secrets/recovery-confirmed."
106
+
107
+ def restic(*args, **kw):
108
+ return run(
109
+ ["restic", "-o", "s3.bucket-lookup=path", *args, "--no-cache"],
110
+ env=env,
111
+ **kw,
173
112
  )
174
113
 
175
- recovery = root / "recovery"
176
- recovery.mkdir(mode=0o700, exist_ok=True)
177
- if os.geteuid() == 0:
178
- os.chown(recovery, 1000, 1000)
179
- with tempfile.TemporaryDirectory(
180
- prefix="checkpoint-", dir=recovery
181
- ) as temporary:
182
- captured = pathlib.Path(temporary) / "payload"
183
- # The stack keeps running: a live, verified-stable copy.
184
- checkpoint.capture(root, captured)
185
- result = restic(
186
- "backup",
187
- "--json",
188
- str(captured),
189
- "--tag",
190
- "cliproxy-fleet",
191
- "--tag",
192
- "cliproxy-checkpoint-v1",
193
- "--host",
194
- "cliproxy-primary",
195
- stdout=subprocess.PIPE,
196
- stderr=subprocess.PIPE,
114
+ if command == "init":
115
+ restic("init")
116
+ elif command == "check":
117
+ restic("check", "--read-data-subset=10%")
118
+ elif command == "check-full":
119
+ restic("check", "--read-data")
120
+ elif command == "gc":
121
+ retention.prune(restic, dry_run=preview, stage=set_stage)
122
+ set_stage("local-worktrees")
123
+ removed = retention.revisions(root, dry_run=preview)
124
+ if preview:
125
+ print(json.dumps(dict(operation="gc", preview=True, worktrees=removed)))
126
+ else:
127
+ write(
128
+ status / "gc-success.json",
129
+ json.dumps(
130
+ {
131
+ "time": datetime.datetime.now(datetime.timezone.utc).isoformat(),
132
+ "retired_worktrees": removed,
133
+ }
134
+ )
135
+ + "\n",
136
+ )
137
+ print(
138
+ "Cloud garbage collected and integrity checked; retired clean worktrees removed:",
139
+ removed,
140
+ )
141
+ elif command == "snapshots":
142
+ restic("snapshots", stdout=None)
143
+ elif command == "restore":
144
+ if len(sys.argv) != 4:
145
+ sys.exit("Usage: backup restore SNAPSHOT EMPTY_DIRECTORY")
146
+ target = pathlib.Path(sys.argv[3]).resolve()
147
+ if target.exists() and any(target.iterdir()):
148
+ sys.exit("Restore target must be empty.")
149
+ target.mkdir(parents=True, exist_ok=True)
150
+ restic("restore", sys.argv[2], "--target", str(target), "--verify")
151
+ elif command == "restore-cache":
152
+ if sys.argv[2:] != ["--previous-node-stopped"]:
153
+ raise ValueError("Explicit previous-node-stopped acknowledgement required")
154
+ # This local check complements operator fencing of the previous machine.
155
+ active = subprocess.check_output(
156
+ [
157
+ "docker",
158
+ "compose",
159
+ "--profile",
160
+ "portable-endpoint",
161
+ "--profile",
162
+ "public-endpoint",
163
+ "ps",
164
+ "--status",
165
+ "running",
166
+ "--services",
167
+ ],
168
+ cwd=root,
197
169
  text=True,
170
+ ).strip()
171
+ if active:
172
+ raise ValueError("Stop the local stack before recovery")
173
+ with tempfile.TemporaryDirectory(
174
+ prefix="restore-", dir=root / "recovery"
175
+ ) as temporary:
176
+ target = pathlib.Path(temporary)
177
+ restic(
178
+ "restore",
179
+ "latest",
180
+ "--tag",
181
+ "cliproxy-checkpoint-v1",
182
+ "--host",
183
+ "cliproxy-primary",
184
+ "--target",
185
+ str(target),
186
+ "--verify",
187
+ stdout=subprocess.PIPE,
188
+ stderr=subprocess.PIPE,
189
+ )
190
+ payload = checkpoint.locate(target)
191
+ saved_destination = payload / "state/repository.json"
192
+ if (
193
+ not saved_destination.exists()
194
+ or json.loads(saved_destination.read_text()) != identity
195
+ ):
196
+ raise ValueError("Recovered repository identity differs from Vault")
197
+ checkpoint.hydrate(payload, state)
198
+ print(
199
+ "Cloud checkpoint recovered into empty cache. No services started. Run install, then health verification."
198
200
  )
199
- summaries = [json.loads(line) for line in result.stdout.splitlines()]
200
- summary = next(
201
- item
202
- for item in reversed(summaries)
203
- if item.get("message_type") == "summary"
201
+ elif command == "backup":
202
+ if not (state / "secrets/recovery-confirmed").exists():
203
+ sys.exit(
204
+ "Store Restic password independently; then create state/secrets/recovery-confirmed."
205
+ )
206
+
207
+ recovery = root / "recovery"
208
+ recovery.mkdir(mode=0o700, exist_ok=True)
209
+ if os.geteuid() == 0:
210
+ os.chown(recovery, 1000, 1000)
211
+ with tempfile.TemporaryDirectory(
212
+ prefix="checkpoint-", dir=recovery
213
+ ) as temporary:
214
+ captured = pathlib.Path(temporary) / "payload"
215
+ # The stack keeps running: a live, verified-stable copy.
216
+ checkpoint.capture(root, captured)
217
+ result = restic(
218
+ "backup",
219
+ "--json",
220
+ str(captured),
221
+ "--tag",
222
+ "cliproxy-fleet",
223
+ "--tag",
224
+ "cliproxy-checkpoint-v1",
225
+ "--host",
226
+ "cliproxy-primary",
227
+ stdout=subprocess.PIPE,
228
+ stderr=subprocess.PIPE,
229
+ text=True,
230
+ )
231
+ summaries = [json.loads(line) for line in result.stdout.splitlines()]
232
+ summary = next(
233
+ item
234
+ for item in reversed(summaries)
235
+ if item.get("message_type") == "summary"
236
+ )
237
+ snapshot = summary["snapshot_id"]
238
+ if not isinstance(snapshot, str) or not snapshot:
239
+ raise ValueError("Missing snapshot acknowledgement")
240
+ print("Complete encrypted checkpoint saved:", snapshot)
241
+ retention.forget(restic)
242
+ write(
243
+ status / "backup-success.json",
244
+ json.dumps(
245
+ {
246
+ "snapshot": snapshot,
247
+ "time": datetime.datetime.now(datetime.timezone.utc).isoformat(),
248
+ "destination": "configured R2 bucket / cliproxy-fleet/restic",
249
+ }
250
+ )
251
+ + "\n",
204
252
  )
205
- snapshot = summary["snapshot_id"]
206
- if not isinstance(snapshot, str) or not snapshot:
207
- raise ValueError("Missing snapshot acknowledgement")
208
- print("Complete encrypted checkpoint saved:", snapshot)
209
- retention.forget(restic)
210
- write(
211
- status / "backup-success.json",
212
- json.dumps(
213
- {
214
- "snapshot": snapshot,
215
- "time": datetime.datetime.now(datetime.timezone.utc).isoformat(),
216
- "destination": "configured R2 bucket / cliproxy-fleet/restic",
217
- }
253
+ else:
254
+ sys.exit(
255
+ "Use init, backup, gc, snapshots, check, check-full, restore SNAPSHOT EMPTY_DIRECTORY, or restore-cache --previous-node-stopped."
218
256
  )
219
- + "\n",
220
- )
221
- else:
222
- sys.exit(
223
- "Use init, backup, gc, snapshots, check, check-full, restore SNAPSHOT EMPTY_DIRECTORY, or restore-cache --previous-node-stopped."
224
- )
225
- except (Exception, SystemExit):
226
- write(failure, datetime.datetime.now(datetime.timezone.utc).isoformat() + "\n")
227
- sys.exit(
228
- "Backup operation failed. Inspect systemd unit status; credentials suppressed."
229
- )
257
+ except (Exception, SystemExit) as error:
258
+ code = "PROCESS_FAILED" if isinstance(error, subprocess.CalledProcessError) else "OPERATION_REFUSED"
259
+ detail = dict(operation=command if command in ["backup", "gc", "check", "check-full", "restore", "restore-cache", "snapshots", "init"] else "unknown", stage=stage, code=code)
260
+ if not preview:
261
+ write(failure, datetime.datetime.now(datetime.timezone.utc).isoformat() + "\n")
262
+ write(failure.with_suffix(".json"), json.dumps(detail) + "\n")
263
+ sys.exit(json.dumps(detail))
230
264
  else:
231
- failure.unlink(missing_ok=True)
232
-
265
+ if not preview:
266
+ failure.unlink(missing_ok=True)
267
+ failure.with_suffix(".json").unlink(missing_ok=True)
233
268
  finally:
234
- lock.close()
269
+ if lock is not None:
270
+ lock.close()
@@ -21,7 +21,7 @@ root = cliproxy_host.default_root().resolve()
21
21
  args = sys.argv[1:]
22
22
  if not args or args[0] in ["help", "--help", "-h"]:
23
23
  print(
24
- "Usage: homelab proxy COMMAND\nCommands: install [--revision REV|--rollback|--dry-run|--prepare-only], audit, public-endpoint [enable|start|disable|verify], status, start, stop, restart, health, models, logs, validate, apply FILE, add-account PROVIDER, relogin PROVIDER INDEX, remove-account PROVIDER INDEX, accounts [--json], client-keys, issue-key|rotate-key|retire-key|revoke-key NODE, inference PROTOCOL MODEL, model-health [--profile liveness|readiness|light|nightly|manual] [--suite core|cursor|all] [--target live|mock], model-suite (same flags; defaults to nightly), backup, gc, snapshots, check, check-full, restore SNAPSHOT EMPTY_DIRECTORY, restore-cache --previous-node-stopped, vault-login, recover, recover-node NEW_DIRECTORY [--vault-token-file FILE], verify-recovery, portable-login, activate, drain"
24
+ "Usage: homelab proxy COMMAND\nCommands: install [--revision REV|--rollback|--dry-run|--prepare-only], audit, public-endpoint [enable|start|disable|verify], status, start, stop, restart, health, models, logs, validate, apply FILE, add-account PROVIDER, relogin PROVIDER INDEX, remove-account PROVIDER INDEX, accounts [--json], client-keys, issue-key|rotate-key|retire-key|revoke-key NODE, inference PROTOCOL MODEL, model-health [--profile liveness|readiness|light|nightly|manual] [--suite core|cursor|all] [--target live|mock], model-suite (same flags; defaults to nightly), backup, gc [--dry-run] [--local-only], snapshots, check, check-full, restore SNAPSHOT EMPTY_DIRECTORY, restore-cache --previous-node-stopped, vault-login, recover, recover-node NEW_DIRECTORY [--vault-token-file FILE], verify-recovery, portable-login, activate, drain"
25
25
  )
26
26
  sys.exit(0)
27
27
  command, *rest = args