Files
felhom-agent/internal/hub/contract_test.go
T
admin b527430ec7 v0.6.0-rc1: slice 6 Phase A — backup + the self-restore-test (local target)
The guest-level backup layer + the journaled self-restore-test (restore→boot→verify→
teardown) that closes "a backup you haven't restored isn't a backup". All benign
(reuses the slice-4 classifier/gate/journal; no new destructive class/crypto). Local
target only; PBS = Phase B. Restore to a NEW guest only. Backups crash-consistent.

- proxmox: DestroyLXC, VzdumpOptions.Notes (notes-template), LatestBackupVolID.
- reconcile: Engine.RunRestoreTest (journal Scratch entry BEFORE mutation; net link-down
  pre-boot; defer teardown always; benign gated destroy) + Recover extended to reap a
  leaked scratch guest (Scratch flag, special-cased before the UPID path; idempotent).
- internal/backup: runner (vzdump + archive resolve + bulk-gap = backup!=1) + cadence
  scheduler (4th daemon goroutine, default 24h) + in-memory report store.
- hub: Backup/RestoreTest filled; collector seams; cross-repo golden byte-identical +
  bidirectional key-set tests; hub handler logs a FAILED restore-test prominently.
- config BackupConfig (band 990000-990009 default); --selftest=backup / restore-test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 13:49:39 +02:00

124 lines
4.2 KiB
Go

package hub
import (
"encoding/json"
"os"
"reflect"
"sort"
"testing"
)
// The host-report shape is a contract DUPLICATED across two repos (no shared types
// module yet). testdata/host-report.golden.json MUST be kept byte-identical with
// felhom-hub's hub/internal/api/testdata/host-report.golden.json. This test fails
// if a json tag on HostReport/HostMetrics/Guest is renamed/added/removed relative
// to the golden, catching silent drift before slices 5/6 populate the empty
// collections. (Promote to a shared types module when those land.)
func TestHostReport_ContractMatchesGolden(t *testing.T) {
raw, err := os.ReadFile("testdata/host-report.golden.json")
if err != nil {
t.Fatal(err)
}
var golden map[string]any
if err := json.Unmarshal(raw, &golden); err != nil {
t.Fatalf("golden is not valid JSON: %v", err)
}
// A constructed report mirroring the golden's populated shape: guests[0] has spec,
// storage_targets[0] is an lvmthin (so its thin_pool + smart sub-objects are exercised).
report := &HostReport{
HostID: "demo-host-01", ReportedAt: "2026-06-08T12:00:00Z", AgentVersion: "0.3.1",
Host: HostMetrics{Node: "demo-felhom", LoadAvg: []string{"0.10"}},
Guests: []Guest{
{VMID: 100, Name: "a", Status: "running", ControllerVersion: "", Spec: &GuestSpec{Cores: 2}},
{VMID: 101, Name: "b", Status: "stopped", ControllerVersion: ""},
},
StorageTargets: []StorageTarget{
{
Name: "local-lvm", Type: StorageTypeLVMThin, DurableID: "pve/data",
State: StorageStateAttached, Reachable: true, ClassHint: "fast",
ThinPool: &ThinPoolFill{DataUsedFraction: 0.42},
Smart: SmartSummary{Health: SmartUnknown},
},
{
Name: "usb-backup", Type: StorageTypeUSB, DurableID: "uuid:x",
State: StorageStateAttached, Reachable: true,
Smart: SmartSummary{Health: SmartUnknown},
},
},
Backups: []Backup{
{
TargetID: "local", VMID: 9001, Archive: "local:backup/x.tar.zst", Mode: "snapshot",
CrashConsistent: true, SizeBytes: 1, Success: true, StartedAt: "2026-06-09T11:00:00Z",
DurationSeconds: 1, UncoveredVolumes: []string{"/mnt/bulk"},
},
},
RestoreTests: []RestoreTest{
{
SourceArchive: "local:backup/x.tar.zst", SourceTier: "local", ScratchVMID: 990000,
Pass: true, Verified: "boot+running", TestedAt: "2026-06-09T11:05:00Z", DurationSeconds: 1,
},
},
PBSSnapshots: []PBSSnapshot{}, AuditTail: []AuditEntry{},
Cloudflared: Cloudflared{Status: "active"},
}
b, _ := json.Marshal(report)
var got map[string]any
json.Unmarshal(b, &got)
assertSameKeys(t, "<top>", golden, got)
assertSameKeys(t, "host", golden["host"], got["host"])
assertSameKeys(t, "guests[0]",
firstElem(golden["guests"]), firstElem(got["guests"]))
// storage_targets[0] is the slice-5 addition — assert its full key set and both
// sub-objects (smart always present; thin_pool present for the lvmthin element).
gst := firstElem(golden["storage_targets"])
sst := firstElem(got["storage_targets"])
assertSameKeys(t, "storage_targets[0]", gst, sst)
assertSameKeys(t, "storage_targets[0].smart", field(gst, "smart"), field(sst, "smart"))
assertSameKeys(t, "storage_targets[0].thin_pool", field(gst, "thin_pool"), field(sst, "thin_pool"))
// slice-6 additions — backups[0] / restore_tests[0] key sets (the bidirectional guard).
assertSameKeys(t, "backups[0]", firstElem(golden["backups"]), firstElem(got["backups"]))
assertSameKeys(t, "restore_tests[0]", firstElem(golden["restore_tests"]), firstElem(got["restore_tests"]))
}
// field extracts a nested object value from a decoded JSON map (nil if absent/not a map).
func field(v any, key string) any {
m, ok := v.(map[string]any)
if !ok {
return nil
}
return m[key]
}
func firstElem(v any) any {
arr, ok := v.([]any)
if !ok || len(arr) == 0 {
return map[string]any{}
}
return arr[0]
}
func assertSameKeys(t *testing.T, where string, a, b any) {
t.Helper()
ka, kb := keysOf(a), keysOf(b)
if !reflect.DeepEqual(ka, kb) {
t.Errorf("contract drift at %s:\n golden keys = %v\n struct keys = %v", where, ka, kb)
}
}
func keysOf(v any) []string {
m, ok := v.(map[string]any)
if !ok {
return nil
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}