package host import ( "context" "encoding/json" "errors" "os" "os/exec" "path/filepath" "testing" "time" "github.com/carlosframework/platform/internal/hostbox" "github.com/carlosframework/platform/internal/hostclaim" "github.com/carlosframework/platform/internal/hostguard" "github.com/carlosframework/platform/internal/hostwrite" "github.com/carlosframework/platform/internal/registry" "github.com/carlosframework/platform/internal/release" "github.com/carlosframework/platform/internal/rootparticipation" ) type restartRequestProcessFixture struct { Unit rollbackProcessFixture Claim *hostclaim.Claim Installations, Journal string } func TestPlan14RootRestartProductionCrash(t *testing.T) { t.Parallel() if boundary := os.Getenv("PLAN14_REQUEST_CRASH"); boundary != "" { dir := os.Getenv("PLAN14_REQUEST_DIR") f := newRestartConsumptionFixture(t) if err := f.run(t); err != nil { t.Fatal(err) } f.request(t, release.RestartScopeHost, observedHost) storeDir := filepath.Join(dir, "deployment") store := release.NewDirStore(storeDir) keys, err := f.e.store.List(t.Context(), "") if err != nil { t.Fatal(err) } for _, key := range keys { raw, _, err := f.e.store.Get(t.Context(), key) if err != nil { t.Fatal(err) } if _, err := store.Put(t.Context(), key, raw, ""); err != nil { t.Fatal(err) } } crash := func() { state := restartRequestProcessFixture{Unit: rollbackProcessFixture{Props: f.u.props, Exe: f.u.exe, Opt: f.u.opt, Bake: f.e.bake, Store: storeDir, Effects: f.u.effects}, Claim: f.claim, Installations: f.p.source.state.(*rollbackDisk).dir, Journal: f.p.journal.Store.(*rollbackDisk).dir} raw, err := json.Marshal(state) if err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(dir, "fixture.json"), raw, 0600); err != nil { t.Fatal(err) } os.Exit(74) } disk := f.p.journal.Store.(*rollbackDisk) classify := func(raw []byte) string { var r struct { Pending *release.RestartIntent ScopeID string `json:"scope_id"` } if json.Unmarshal(raw, &r) != nil { return "" } if r.Pending == nil { if r.ScopeID != release.RestartScopeNone { return "consumed" } return "baseline" } if r.Pending.Targets[0].After != "" { return "completed" } if r.Pending.Targets[0].Before != "" { return "intent" } return "pending" } disk.afterWrite = func(_ string, raw []byte) { if classify(raw) == boundary { crash() } } if boundary == "intent-visible" { disk.beforeWrite = func(name string, raw []byte) { if classify(raw) != "intent" { return } file, err := os.CreateTemp(disk.dir, "visible-") if err != nil { t.Fatal(err) } if _, err = file.Write(raw); err != nil { t.Fatal(err) } if err = file.Sync(); err != nil { t.Fatal(err) } if err = file.Close(); err != nil { t.Fatal(err) } if err = os.Rename(file.Name(), filepath.Join(disk.dir, name)); err != nil { t.Fatal(err) } // Exit before syncing the parent of the visible rename. crash() } } f.u.afterEffect = func() { if boundary == "effect" { crash() } } _ = f.run(t) t.Fatal("crash boundary not reached") } for _, boundary := range []string{"pending", "intent", "intent-visible", "effect", "completed", "consumed"} { t.Run(boundary, func(t *testing.T) { dir := t.TempDir() ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) defer cancel() cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestPlan14RootRestartProductionCrash$", "-test.count=1") cmd.Dir = dir cmd.Env = append(os.Environ(), "TMPDIR="+dir, "PLAN14_REQUEST_DIR="+dir, "PLAN14_REQUEST_CRASH="+boundary, "CARLOS_HOST_CLAIM=") out, err := cmd.CombinedOutput() var exit *exec.ExitError if !errors.As(err, &exit) || exit.ExitCode() != 74 { t.Fatalf("child: %v\n%s", err, out) } raw, err := os.ReadFile(filepath.Join(dir, "fixture.json")) if err != nil { t.Fatal(err) } var saved restartRequestProcessFixture if err = json.Unmarshal(raw, &saved); err != nil { t.Fatal(err) } u := &plan14RestartUnits{props: saved.Unit.Props, exe: saved.Unit.Exe, opt: saved.Unit.Opt, effects: saved.Unit.Effects} store := release.NewDirStore(saved.Unit.Store) state := &rollbackDisk{dir: saved.Installations} guard := hostguard.Guard{DataDir: t.TempDir(), LockDir: t.TempDir(), Root: hostguard.NewRootAuthority(state), Claims: rootViewClaimReader{obs: hostclaim.Observed{Host: observedHost, ETag: "claim", Claim: saved.Claim}}} source := &proofBindingSource{store: store, sys: u, optDir: u.opt, openFile: os.Open, unitDirs: []string{filepath.Dir(u.props.FragmentPath)}, healthy: func(acct, app, version, digest string) *release.HealthyBuild { for _, b := range release.ReadHealthy(saved.Unit.Bake, acct, app) { if b.Version == version && b.SHA256 == digest { return &b } } return nil }} now, sleep := settleClock() p := rootRestartRequests{journal: &release.RootRestarts{Store: &rollbackDisk{dir: saved.Journal}}, source: rootRestartRequestSource{state: state, store: store, census: func() (rootparticipation.Census, error) { return rootparticipation.Census{Box: "box", Enrollment: "en", Migration: 1, Complete: true}, nil }}, sys: u, optDir: u.opt, getenv: func(string) string { return "5s" }, checks: rootRestartChecks{host: source.forHost, ready: func(registry.Route) func() error { return func() error { return nil } }, now: now, sleep: sleep}, writes: hostwrite.Config{Enabled: true, Selector: hostbox.WorkSource{Guard: guard, Box: "box", Region: "ie", Now: time.Now, Policy: func(_ context.Context, c *hostclaim.Claim, s hostbox.Selection, _ hostwrite.Identity) error { return hostbox.Serving(c, s) }, Local: func(context.Context, *hostclaim.Claim, hostbox.Selection) error { return nil }}}} err = p.run(t.Context()) if boundary == "intent" || boundary == "intent-visible" { if err == nil || len(u.effects) != 0 { t.Fatalf("ambiguous replay: %v %v", err, u.effects) } u.props.InvocationID += "reconciled" u.props.MainPID++ if err = p.run(t.Context()); err != nil || len(u.effects) != 0 { t.Fatalf("reconcile: %v %v", err, u.effects) } } else if err != nil || len(u.effects) != 1 { t.Fatalf("resume: %v %v", err, u.effects) } count := len(u.effects) if err = p.run(t.Context()); err != nil || len(u.effects) != count { t.Fatalf("replay: %v %v", err, u.effects) } }) } }