activator, provision: cleanup holds its directories (Task 10 R2)
Round 2 of the Task 10 review (Codex), one P1, in the family round 1 also hit. Paul's ruling: state the invariant, enforce it in one place, guard test. The invariant: the cleanup proof covers the same storage identity that held the seed. One function owns each location from purge through proof, instancefs.PurgeProven(root, rel, match): - it opens the data directory once, with no symlink at any component, and the location once beneath that descriptor, and holds both. Each one's identity (fstat dev and ino) is taken from its descriptor; - it lists, removes (unlinkat, and recursive removal relative to the held descriptor) and checks that nothing is left through the held descriptor of the location. Nothing is reopened by path; - last, it resolves the location again beneath the held data directory and the data directory again by its path, and each must be the directory first opened; - a location absent at open must still be absent at the end. Anything else is an error and no proof (ErrNotProven, ErrSymlink, ErrDirUnopened). The fleet rollback calls it once per location (fleetSeedPurgeProven) and no longer uses the path-based RemoveLocal hook or a separate scan. The activator's purge (purgeSeedTarget, PurgeSeedLocal) goes through it too, with the one list of names (provision.SeedLocalName), so a region purge removes what it did before. ReadDirNamesBeneathOrAbsent is replaced by it; its symlink tests are kept against PurgeProven. Guard tests: a populated directory renamed aside with an empty real directory in its place, between listing and removal and between removal and proof, at three depths, in instancefs and through the rollback.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+733
−414
internal/activator/seedplace.go+13 −37internal/instancefs/instancefs.go+19 −0internal/instancefs/instancefs_other.go+4 −4internal/instancefs/purge_linux.go+171 −0internal/instancefs/purge_linux_test.go+237 −0internal/instancefs/readdir_linux.go+0 −51internal/instancefs/readdir_linux_test.go+0 −105internal/provision/seedfleet.go+56 −66internal/provision/seedfleet_linux_test.go+233 −151
CI failed — run details
diff --git a/internal/activator/seedplace.go b/internal/activator/seedplace.go| index b667e47a6..af821f2be 100644 |
| --- a/internal/activator/seedplace.go |
| +++ b/internal/activator/seedplace.go |
| @@ -385,9 +385,11 @@ func seedTempName(base, id string) string { return ".seed-" + base + "-" + id + |
| // so only there may a purge remove an old-style ".seed-sd_*.tmp" name, |
| // which says no instance. |
| // |
| -// "Not there" is decided beneath an ancestor's own descriptor, with no |
| -// symlink followed at any component (instancefs.ReadDirNamesBeneathOrAbsent): |
| -// a component swapped for a link is an error, never "nothing to purge". The |
| +// The purge and its proof are instancefs.PurgeProven's: the directory and |
| +// an ancestor are opened once, with no symlink followed, and held; the |
| +// listing, the removals and the check that nothing is left go through |
| +// those descriptors; and nil means the path still names the directory that |
| +// was purged. "Not there" is decided beneath the ancestor's descriptor. The |
| // ancestor is dataDir, the box's data directory, for a database beneath it |
| // (every flat and nested row), so a nested directory never made on a flat |
| // box is simply absent. For any other path it is the directory's parent, |
| @@ -401,12 +403,7 @@ func PurgeSeedLocal(dataDir, dbPath string, layout Layout) error { |
| if r, err := filepath.Rel(dataDir, dir); dataDir != "" && err == nil && filepath.IsLocal(r) { |
| root, rel = dataDir, r |
| } |
| - if _, absent, err := instancefs.ReadDirNamesBeneathOrAbsent(root, rel); err != nil { |
| - return err |
| - } else if absent { |
| - return nil |
| - } |
| - return purgeSeedTarget(dir, base, layout == LayoutNested) |
| + return instancefs.PurgeProven(root, rel, provision.SeedLocalName(base, layout == LayoutNested)) |
| } |
| // PurgeSeedLocalFor is PurgeSeedLocal for rt's database, in the layout this |
| @@ -452,35 +449,14 @@ func splitDBPath(dbPath string) (dir, base string, err error) { |
| } |
| // purgeSeedTarget removes everything at and beside dir/base that could |
| -// stand in for a seed's database: what PurgeLocalDBArtifacts removes in its |
| -// full form, the marker, and any seed temp file of this database (any seed |
| -// id), through instancefs. legacyTemps also removes the old-style |
| -// ".seed-sd_*.tmp" names, which name no instance; the caller passes it only |
| -// for a nested directory, which holds one. |
| +// stand in for a seed's database (provision.SeedLocalName: what |
| +// PurgeLocalDBArtifacts removes in its full form, the marker, and any seed |
| +// temp file of this database, any seed id), and proves it gone, through |
| +// instancefs.PurgeProven on dir's own held descriptor. legacyTemps also |
| +// removes the old-style ".seed-sd_*.tmp" names, which name no instance; the |
| +// caller passes it only for a nested directory, which holds one. |
| func purgeSeedTarget(dir, base string, legacyTemps bool) error { |
| - names := []string{base, base + "-wal", base + "-shm", base + SeedMarkerSuffix, |
| - base + "-litestream", ".activator-" + base + "-litestream"} |
| - // Listed from dir's own descriptor, opened with no symlink followed, as |
| - // the removals below open it. |
| - ents, absent, err := instancefs.ReadDirNamesBeneathOrAbsent(dir, ".") |
| - if err != nil { |
| - return err |
| - } |
| - if absent { |
| - return &os.PathError{Op: "open", Path: dir, Err: os.ErrNotExist} |
| - } |
| - for _, n := range ents { |
| - own := strings.HasPrefix(n, ".seed-"+base+"-sd_") && strings.Contains(n, ".tmp") |
| - if own || (legacyTemps && strings.HasPrefix(n, ".seed-sd_") && strings.Contains(n, ".tmp")) { |
| - names = append(names, n) |
| - } |
| - } |
| - for _, n := range names { |
| - if err := instancefs.RemoveAllBeneath(dir, n); err != nil { |
| - return err |
| - } |
| - } |
| - return nil |
| + return instancefs.PurgeProven(dir, ".", provision.SeedLocalName(base, legacyTemps)) |
| } |
| // placeSeed fetches and checks the snapshot, then writes the marker and |
diff --git a/internal/instancefs/instancefs.go b/internal/instancefs/instancefs.go| index aca341bd0..5ea8c09e7 100644 |
| --- a/internal/instancefs/instancefs.go |
| +++ b/internal/instancefs/instancefs.go |
| @@ -44,6 +44,25 @@ var ErrNotRegular = errors.New("instancefs: not a regular file") |
| // directory: never evidence that the name is absent. |
| var ErrDirUnopened = errors.New("instancefs: the directory could not be opened") |
| +// ErrNotProven is returned by PurgeProven when its removals ran and it |
| +// still cannot say the storage it opened is empty of what it was asked to |
| +// remove and is what the path names: something is left, or a directory was |
| +// replaced, removed or created while it worked. |
| +var ErrNotProven = errors.New("instancefs: the purge is not proven") |
| + |
| +// purgeHook is PurgeProven's test seam: called with "listed" after the |
| +// directory is listed and before anything is removed, and with "removed" |
| +// after the removals and before the proof. |
| +var purgeHook = func(stage string) {} |
| + |
| +// SetPurgeHookForTest sets PurgeProven's seam for a test in another package |
| +// (the fleet rollback's guard tests swap a directory between the stages). |
| +func SetPurgeHookForTest(hook func(stage string)) (restore func()) { |
| + prev := purgeHook |
| + purgeHook = hook |
| + return func() { purgeHook = prev } |
| +} |
| + |
| // ErrNotDir is returned when OpenDirBeneath resolves to anything other |
| // than a directory: a file, or a FIFO, which it never waits on. |
| var ErrNotDir = errors.New("instancefs: not a directory") |
diff --git a/internal/instancefs/instancefs_other.go b/internal/instancefs/instancefs_other.go| index 7f05b14c4..aa0101a4a 100644 |
| --- a/internal/instancefs/instancefs_other.go |
| +++ b/internal/instancefs/instancefs_other.go |
| @@ -89,9 +89,9 @@ func RemoveAllBeneath(dir, name string) error { |
| return errors.ErrUnsupported |
| } |
| -func ReadDirNamesBeneathOrAbsent(dir, name string) ([]string, bool, error) { |
| - if _, err := cleanRel(name); err != nil { |
| - return nil, false, err |
| +func PurgeProven(root, rel string, match func(name string) bool) error { |
| + if _, err := cleanRel(rel); err != nil { |
| + return err |
| } |
| - return nil, false, errors.ErrUnsupported |
| + return errors.ErrUnsupported |
| } |
diff --git a/internal/instancefs/purge_linux.go b/internal/instancefs/purge_linux.go| new file mode 100644 |
| index 000000000..d842a69e4 |
| --- /dev/null |
| +++ b/internal/instancefs/purge_linux.go |
| @@ -0,0 +1,171 @@ |
| +//go:build linux |
| + |
| +package instancefs |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// dirID is a directory's storage identity: the device and inode fstat |
| +// reports for an open descriptor. |
| +type dirID struct{ dev, ino uint64 } |
| + |
| +func identityOf(fd int, path string) (dirID, error) { |
| + var st unix.Stat_t |
| + if err := unix.Fstat(fd, &st); err != nil { |
| + return dirID{}, &os.PathError{Op: "fstat", Path: path, Err: err} |
| + } |
| + return dirID{uint64(st.Dev), uint64(st.Ino)}, nil |
| +} |
| + |
| +// openHeld opens the directory rel beneath the held descriptor root (which |
| +// names rootPath, for errors) with openat2: no symlink at any component, |
| +// never leaving root. absent is true only when that lookup answers ENOENT. |
| +func openHeld(root int, rootPath, rel string) (fd int, id dirID, absent bool, err error) { |
| + path := filepath.Join(rootPath, rel) |
| + how := unix.OpenHow{Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_NONBLOCK | unix.O_CLOEXEC, Resolve: resolveFlags} |
| + fd, err = unix.Openat2(root, rel, &how) |
| + switch { |
| + case errors.Is(err, unix.ENOENT): |
| + return -1, dirID{}, true, nil |
| + case errors.Is(err, unix.ELOOP): |
| + return -1, dirID{}, false, fmt.Errorf("%w: %s", ErrSymlink, path) |
| + case errors.Is(err, unix.EXDEV): |
| + return -1, dirID{}, false, fmt.Errorf("%w: %s", ErrEscapes, path) |
| + case err != nil: |
| + return -1, dirID{}, false, &os.PathError{Op: "openat2", Path: path, Err: err} |
| + } |
| + if id, err = identityOf(fd, path); err != nil { |
| + unix.Close(fd) |
| + return -1, dirID{}, false, err |
| + } |
| + return fd, id, false, nil |
| +} |
| + |
| +// namesIn lists the directory the descriptor dir holds. It opens "." |
| +// relative to dir, which is that same directory whatever has been renamed |
| +// since, so each listing starts at the beginning and no path is resolved. |
| +func namesIn(dir int, path string) ([]string, error) { |
| + fd, err := unix.Openat(dir, ".", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + return nil, &os.PathError{Op: "openat", Path: path, Err: err} |
| + } |
| + f := os.NewFile(uintptr(fd), path) |
| + defer f.Close() |
| + return f.Readdirnames(-1) |
| +} |
| + |
| +// PurgeProven removes every entry that match selects from the directory |
| +// rel under root ("." is root itself), and returns nil only with proof |
| +// that the storage it began with holds none of them and is still what the |
| +// path names. It is the one place a purge of seed data is done and proved |
| +// (fleet seeded create, Task 10 review round 2): |
| +// |
| +// The invariant: the cleanup proof covers the same storage identity that |
| +// held the data. A purge that lists a directory, then reopens it by path to |
| +// remove and again to check, proves nothing if the directory is renamed |
| +// aside and an empty one put in its place between two of those steps: the |
| +// removals and the check then run on the empty replacement, and the data |
| +// sits untouched under another name. So nothing here is reopened by path. |
| +// |
| +// - root is opened once, with no symlink at any component, and rel once |
| +// beneath that descriptor, the same way. Both descriptors are held to |
| +// the end, and each directory's identity (device and inode) is taken |
| +// from its descriptor. |
| +// - The listing, every removal (unlinkat, and recursive removal, relative |
| +// to the held descriptor; no symlink followed, a link is unlinked and |
| +// never its target) and the check that nothing match selects is left |
| +// all go through the held descriptor of rel. |
| +// - Last, rel is resolved again beneath the held root descriptor and root |
| +// again by its path, and each must be the directory first opened. A |
| +// path that now names other storage, or a symlink, is ErrNotProven. |
| +// - A rel that was absent at open (its lookup beneath root answered "no |
| +// such entry") holds nothing; it must still be absent at the end. |
| +// |
| +// Every failure is an error, and none of them is proof: a root that will |
| +// not open (ErrDirUnopened), a symlink at any component (ErrSymlink), an |
| +// entry that cannot be removed, anything left or changed (ErrNotProven). |
| +func PurgeProven(root, rel string, match func(name string) bool) error { |
| + crel, err := cleanRel(rel) |
| + if err != nil { |
| + return err |
| + } |
| + rootFD, err := openDir(root) |
| + if err != nil { |
| + return fmt.Errorf("%w: %w", ErrDirUnopened, err) |
| + } |
| + defer unix.Close(rootFD) |
| + rootID, err := identityOf(rootFD, root) |
| + if err != nil { |
| + return err |
| + } |
| + betweenDirAndLookup() |
| + path := filepath.Join(root, crel) |
| + dirFD, id, absent, err := openHeld(rootFD, root, crel) |
| + if err != nil { |
| + return err |
| + } |
| + if !absent { |
| + defer unix.Close(dirFD) |
| + names, err := namesIn(dirFD, path) |
| + if err != nil { |
| + return err |
| + } |
| + purgeHook("listed") |
| + for _, n := range names { |
| + if match(n) { |
| + if err := removeAt(dirFD, n, filepath.Join(path, n), 0); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + } else { |
| + purgeHook("listed") |
| + } |
| + purgeHook("removed") |
| + if !absent { |
| + names, err := namesIn(dirFD, path) |
| + if err != nil { |
| + return err |
| + } |
| + var left []string |
| + for _, n := range names { |
| + if match(n) { |
| + left = append(left, n) |
| + } |
| + } |
| + if len(left) != 0 { |
| + return fmt.Errorf("%w: %s still holds %s", ErrNotProven, path, strings.Join(left, ", ")) |
| + } |
| + } |
| + // The paths must still name what was purged. |
| + nowFD, now, nowAbsent, err := openHeld(rootFD, root, crel) |
| + if err != nil { |
| + return fmt.Errorf("%w: %w", ErrNotProven, err) |
| + } |
| + if !nowAbsent { |
| + unix.Close(nowFD) |
| + } |
| + if nowAbsent != absent || now != id { |
| + return fmt.Errorf("%w: %s is not the directory this purge opened (it was replaced, removed or created meanwhile)", ErrNotProven, path) |
| + } |
| + againFD, err := openDir(root) |
| + if err != nil { |
| + return fmt.Errorf("%w: %w", ErrNotProven, err) |
| + } |
| + again, err := identityOf(againFD, root) |
| + unix.Close(againFD) |
| + if err != nil { |
| + return fmt.Errorf("%w: %w", ErrNotProven, err) |
| + } |
| + if again != rootID { |
| + return fmt.Errorf("%w: %s is not the directory this purge opened (it was replaced meanwhile)", ErrNotProven, root) |
| + } |
| + return nil |
| +} |
diff --git a/internal/instancefs/purge_linux_test.go b/internal/instancefs/purge_linux_test.go| new file mode 100644 |
| index 000000000..fc5a67d2d |
| --- /dev/null |
| +++ b/internal/instancefs/purge_linux_test.go |
| @@ -0,0 +1,237 @@ |
| +//go:build linux |
| + |
| +package instancefs |
| + |
| +import ( |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "sort" |
| + "strings" |
| + "syscall" |
| + "testing" |
| +) |
| + |
| +// purgeRig is a data directory with one instance directory in it, holding |
| +// two entries the purge selects (a file and a tree), a link it selects, and |
| +// one entry it does not. |
| +func purgeRig(t *testing.T) (tmp, root, inst string) { |
| + t.Helper() |
| + tmp = t.TempDir() |
| + root = filepath.Join(tmp, "data") |
| + inst = filepath.Join(root, "instances", "abc") |
| + if err := os.MkdirAll(filepath.Join(inst, "a.db-litestream", "generations"), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, n := range []string{"a.db", "a.db-litestream/generations/x", "uploads"} { |
| + if err := os.WriteFile(filepath.Join(inst, n), []byte("x"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + return tmp, root, inst |
| +} |
| + |
| +func seedish(name string) bool { return strings.HasPrefix(name, "a.db") } |
| + |
| +func entries(t *testing.T, dir string) []string { |
| + t.Helper() |
| + ents, err := os.ReadDir(dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var n []string |
| + for _, e := range ents { |
| + n = append(n, e.Name()) |
| + } |
| + sort.Strings(n) |
| + return n |
| +} |
| + |
| +// swapAside renames path to path+".real" and leaves replacement there: a |
| +// real empty directory (mkdir true) or a symlink to target. |
| +func swapAside(t *testing.T, path, target string) { |
| + t.Helper() |
| + if err := os.Rename(path, path+".real"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if target == "" { |
| + if err := os.Mkdir(path, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + return |
| + } |
| + if err := os.Symlink(target, path); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func hookAt(t *testing.T, stage string, f func()) { |
| + t.Helper() |
| + done := false |
| + t.Cleanup(SetPurgeHookForTest(func(s string) { |
| + if s == stage && !done { |
| + done = true |
| + f() |
| + } |
| + })) |
| +} |
| + |
| +func TestPurgeProvenRemovesWhatMatchesAndNothingElse(t *testing.T) { |
| + _, root, inst := purgeRig(t) |
| + outside := filepath.Join(t.TempDir(), "outside") |
| + os.WriteFile(outside, []byte("not the instance's"), 0o600) |
| + if err := os.Symlink(outside, filepath.Join(inst, "a.db-wal")); err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := 0; i < 2; i++ { // idempotent |
| + if err := PurgeProven(root, "instances/abc", seedish); err != nil { |
| + t.Fatalf("run %d: %v", i, err) |
| + } |
| + } |
| + if got := entries(t, inst); len(got) != 1 || got[0] != "uploads" { |
| + t.Fatalf("left %q, want only uploads", got) |
| + } |
| + if b, _ := os.ReadFile(outside); string(b) != "not the instance's" { |
| + t.Fatal("a link's target was touched") |
| + } |
| + // "." is the root itself. |
| + os.WriteFile(filepath.Join(inst, "a.db"), []byte("x"), 0o600) |
| + if err := PurgeProven(inst, ".", seedish); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := entries(t, inst); len(got) != 1 { |
| + t.Fatalf("dot: left %q", got) |
| + } |
| + // Absent beneath a root that opened, at any depth: nothing to purge. |
| + for _, rel := range []string{"instances/none", "none/abc"} { |
| + if err := PurgeProven(root, rel, seedish); err != nil { |
| + t.Fatalf("%s: %v; want an absent directory to be proven empty", rel, err) |
| + } |
| + } |
| + // A root that is not there, a location that is a file, a name that |
| + // escapes: errors, never "nothing there". |
| + if err := PurgeProven(filepath.Join(root, "gone"), ".", seedish); !errors.Is(err, ErrDirUnopened) { |
| + t.Fatalf("a missing root: %v", err) |
| + } |
| + if err := PurgeProven(root, "instances/abc/uploads", seedish); !errors.Is(err, syscall.ENOTDIR) { |
| + t.Fatalf("a file: %v", err) |
| + } |
| + if err := PurgeProven(root, "../x", seedish); !errors.Is(err, ErrEscapes) { |
| + t.Fatalf("an escaping name: %v", err) |
| + } |
| +} |
| + |
| +// Round 1: a component that is a symlink is refused wherever it is, so a |
| +// link to an empty place is never read as an empty directory. |
| +func TestPurgeProvenRefusesASymlinkedComponent(t *testing.T) { |
| + for name, swap := range map[string]func(t *testing.T, tmp, root, inst string){ |
| + "the leaf": func(t *testing.T, tmp, root, inst string) { swapAside(t, inst, filepath.Join(tmp, "empty", "abc")) }, |
| + "a middle component": func(t *testing.T, tmp, root, inst string) { |
| + swapAside(t, filepath.Join(root, "instances"), filepath.Join(tmp, "empty")) |
| + }, |
| + "the root": func(t *testing.T, tmp, root, inst string) { swapAside(t, root, tmp) }, |
| + } { |
| + for _, when := range []string{"before", "after the root opened"} { |
| + t.Run(name+", "+when, func(t *testing.T) { |
| + tmp, root, inst := purgeRig(t) |
| + if err := os.MkdirAll(filepath.Join(tmp, "empty", "abc"), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if when == "before" { |
| + swap(t, tmp, root, inst) |
| + } else { |
| + prev := betweenDirAndLookup |
| + betweenDirAndLookup = func() { swap(t, tmp, root, inst) } |
| + t.Cleanup(func() { betweenDirAndLookup = prev }) |
| + } |
| + err := PurgeProven(root, "instances/abc", seedish) |
| + if name == "the root" && when != "before" { |
| + // The held root is the real one: its data is purged, and |
| + // the path no longer naming it is still not proof. |
| + if !errors.Is(err, ErrNotProven) { |
| + t.Fatalf("err = %v, want ErrNotProven", err) |
| + } |
| + return |
| + } |
| + if !errors.Is(err, ErrSymlink) { |
| + t.Fatalf("err = %v, want ErrSymlink", err) |
| + } |
| + real := strings.Replace(inst, root, root+".real", 1) |
| + if name != "the root" { |
| + real = strings.Replace(inst, "instances", "instances.real", 1) |
| + } |
| + if name == "the leaf" { |
| + real = inst + ".real" |
| + } |
| + if got := entries(t, real); len(got) != 3 { |
| + t.Fatalf("the data behind the link: %q, want it untouched", got) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// Round 2, the invariant: the proof covers the storage that held the data. |
| +// The populated directory is renamed aside and an empty real directory put |
| +// in its place, between the listing and the removals, or between the |
| +// removals and the proof. Either way there is no proof. |
| +func TestPurgeProvenHoldsItsDirectories(t *testing.T) { |
| + for name, which := range map[string]func(root, inst string) string{ |
| + "the instance directory": func(root, inst string) string { return inst }, |
| + "the directory above it": func(root, inst string) string { return filepath.Join(root, "instances") }, |
| + "the data directory itself": func(root, inst string) string { return root }, |
| + } { |
| + for _, stage := range []string{"listed", "removed"} { |
| + t.Run(name+", after "+stage, func(t *testing.T) { |
| + _, root, inst := purgeRig(t) |
| + path := which(root, inst) |
| + hookAt(t, stage, func() { |
| + swapAside(t, path, "") |
| + if path != inst { // the replacement holds an empty directory of the right name |
| + if err := os.MkdirAll(inst, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + }) |
| + err := PurgeProven(root, "instances/abc", seedish) |
| + if !errors.Is(err, ErrNotProven) { |
| + t.Fatalf("err = %v, want ErrNotProven: the path names other storage now", err) |
| + } |
| + // The removals ran on the directory that was opened, wherever |
| + // it was moved to: its data is gone, not merely out of sight. |
| + real := strings.Replace(inst, path, path+".real", 1) |
| + if got := entries(t, real); len(got) != 1 || got[0] != "uploads" { |
| + t.Fatalf("the directory moved aside holds %q; want the removals to have followed it", got) |
| + } |
| + if got := entries(t, inst); len(got) != 0 { |
| + t.Fatalf("the replacement holds %q", got) |
| + } |
| + }) |
| + } |
| + } |
| + t.Run("an entry comes back before the proof", func(t *testing.T) { |
| + _, root, inst := purgeRig(t) |
| + hookAt(t, "removed", func() { os.WriteFile(filepath.Join(inst, "a.db.seed"), []byte("x"), 0o600) }) |
| + if err := PurgeProven(root, "instances/abc", seedish); !errors.Is(err, ErrNotProven) { |
| + t.Fatalf("err = %v, want ErrNotProven", err) |
| + } |
| + }) |
| + t.Run("an absent directory appears", func(t *testing.T) { |
| + _, root, _ := purgeRig(t) |
| + hookAt(t, "listed", func() { |
| + d := filepath.Join(root, "instances", "new") |
| + os.MkdirAll(d, 0o700) |
| + os.WriteFile(filepath.Join(d, "a.db"), []byte("x"), 0o600) |
| + }) |
| + if err := PurgeProven(root, "instances/new", seedish); !errors.Is(err, ErrNotProven) { |
| + t.Fatalf("err = %v, want ErrNotProven: absent at open must be absent at proof", err) |
| + } |
| + }) |
| + t.Run("the directory is removed", func(t *testing.T) { |
| + _, root, inst := purgeRig(t) |
| + hookAt(t, "removed", func() { os.Rename(inst, inst+".real") }) |
| + if err := PurgeProven(root, "instances/abc", seedish); !errors.Is(err, ErrNotProven) { |
| + t.Fatalf("err = %v, want ErrNotProven", err) |
| + } |
| + }) |
| +} |
diff --git a/internal/instancefs/readdir_linux.go b/internal/instancefs/readdir_linux.go| deleted file mode 100644 |
| index cc1c97675..000000000 |
| --- a/internal/instancefs/readdir_linux.go |
| +++ /dev/null |
| @@ -1,51 +0,0 @@ |
| -//go:build linux |
| - |
| -package instancefs |
| - |
| -import ( |
| - "errors" |
| - "fmt" |
| - "os" |
| - |
| - "golang.org/x/sys/unix" |
| -) |
| - |
| -// ReadDirNamesBeneathOrAbsent names every entry of the directory name |
| -// under dir ("." is dir itself), and is where "that directory holds |
| -// nothing" and "that directory is not there" are decided on ground someone |
| -// else can write. Like OpenBeneathOrAbsent, it opens dir once, following no |
| -// symlink at any component, and keeps that descriptor. name is then opened |
| -// beneath it with openat2 (no symlink at any component, never leaving dir), |
| -// and the names are read from that descriptor, so no path is resolved a |
| -// second time: a component swapped for a link to an empty directory is |
| -// ErrSymlink, never an empty listing. |
| -// |
| -// absent is true only when the lookup of name beneath that very descriptor |
| -// answers ENOENT. A dir that cannot be opened (missing, a symlink, not a |
| -// directory) is an error wrapped in ErrDirUnopened, never absence. A name |
| -// that is not a directory is an error too (ENOTDIR). |
| -func ReadDirNamesBeneathOrAbsent(dir, name string) (names []string, absent bool, err error) { |
| - rel, err := cleanRel(name) |
| - if err != nil { |
| - return nil, false, err |
| - } |
| - dfd, err := openDir(dir) |
| - if err != nil { |
| - return nil, false, fmt.Errorf("%w: %w", ErrDirUnopened, err) |
| - } |
| - defer unix.Close(dfd) |
| - betweenDirAndLookup() |
| - f, err := openAt(dfd, dir, rel, os.O_RDONLY|unix.O_DIRECTORY, 0, unix.S_IFDIR) |
| - if errors.Is(err, unix.ENOENT) { |
| - return nil, true, nil |
| - } |
| - if err != nil { |
| - return nil, false, err |
| - } |
| - defer f.Close() |
| - names, err = f.Readdirnames(-1) |
| - if err != nil { |
| - return nil, false, err |
| - } |
| - return names, false, nil |
| -} |
diff --git a/internal/instancefs/readdir_linux_test.go b/internal/instancefs/readdir_linux_test.go| deleted file mode 100644 |
| index ccdc3efa6..000000000 |
| --- a/internal/instancefs/readdir_linux_test.go |
| +++ /dev/null |
| @@ -1,105 +0,0 @@ |
| -//go:build linux |
| - |
| -package instancefs |
| - |
| -import ( |
| - "errors" |
| - "os" |
| - "path/filepath" |
| - "sort" |
| - "syscall" |
| - "testing" |
| -) |
| - |
| -func TestReadDirNamesBeneathOrAbsent(t *testing.T) { |
| - root := filepath.Join(t.TempDir(), "data") |
| - inst := filepath.Join(root, "instances", "abc") |
| - if err := os.MkdirAll(inst, 0o700); err != nil { |
| - t.Fatal(err) |
| - } |
| - for _, n := range []string{"a.db", "a.db.seed"} { |
| - if err := os.WriteFile(filepath.Join(inst, n), []byte("x"), 0o600); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - if err := os.Symlink("/etc", filepath.Join(inst, "link")); err != nil { |
| - t.Fatal(err) |
| - } |
| - names, absent, err := ReadDirNamesBeneathOrAbsent(root, "instances/abc") |
| - sort.Strings(names) |
| - if err != nil || absent || len(names) != 3 || names[0] != "a.db" || names[1] != "a.db.seed" || names[2] != "link" { |
| - t.Fatalf("names %q absent %v err %v; want the three entries, a link named and not followed", names, absent, err) |
| - } |
| - if names, absent, err := ReadDirNamesBeneathOrAbsent(inst, "."); err != nil || absent || len(names) != 3 { |
| - t.Fatalf("dot: names %q absent %v err %v", names, absent, err) |
| - } |
| - // Absent only beneath a directory that opened, at any depth. |
| - for _, rel := range []string{"instances/none", "none/abc"} { |
| - if names, absent, err := ReadDirNamesBeneathOrAbsent(root, rel); err != nil || !absent || names != nil { |
| - t.Fatalf("%s: names %q absent %v err %v; want absent", rel, names, absent, err) |
| - } |
| - } |
| - if _, absent, err := ReadDirNamesBeneathOrAbsent(filepath.Join(root, "gone"), "."); absent || !errors.Is(err, ErrDirUnopened) { |
| - t.Fatalf("a missing dir: absent %v err %v; want ErrDirUnopened, never absence", absent, err) |
| - } |
| - if _, absent, err := ReadDirNamesBeneathOrAbsent(root, "instances/abc/a.db"); absent || !errors.Is(err, syscall.ENOTDIR) { |
| - t.Fatalf("a file: absent %v err %v; want ENOTDIR, never absence", absent, err) |
| - } |
| - if _, _, err := ReadDirNamesBeneathOrAbsent(root, "../x"); !errors.Is(err, ErrEscapes) { |
| - t.Fatalf("an escaping name: %v", err) |
| - } |
| -} |
| - |
| -// A component swapped for a link to an empty directory is refused: it is |
| -// never read as an empty, or an absent, directory. |
| -func TestReadDirNamesBeneathOrAbsentRefusesASwappedComponent(t *testing.T) { |
| - tmp := t.TempDir() |
| - root := filepath.Join(tmp, "data") |
| - inst := filepath.Join(root, "instances", "abc") |
| - if err := os.MkdirAll(inst, 0o700); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.WriteFile(filepath.Join(inst, "a.db"), []byte("x"), 0o600); err != nil { |
| - t.Fatal(err) |
| - } |
| - empty := filepath.Join(tmp, "empty") |
| - if err := os.MkdirAll(filepath.Join(empty, "abc"), 0o700); err != nil { |
| - t.Fatal(err) |
| - } |
| - swap := func(t *testing.T, path, target string) { |
| - t.Helper() |
| - if err := os.Rename(path, path+".real"); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.Symlink(target, path); err != nil { |
| - t.Fatal(err) |
| - } |
| - t.Cleanup(func() { os.Remove(path); os.Rename(path+".real", path) }) |
| - } |
| - t.Run("the leaf", func(t *testing.T) { |
| - swap(t, inst, filepath.Join(empty, "abc")) |
| - if names, absent, err := ReadDirNamesBeneathOrAbsent(root, "instances/abc"); absent || !errors.Is(err, ErrSymlink) { |
| - t.Fatalf("names %q absent %v err %v; want ErrSymlink", names, absent, err) |
| - } |
| - }) |
| - t.Run("a middle component", func(t *testing.T) { |
| - swap(t, filepath.Join(root, "instances"), empty) |
| - if names, absent, err := ReadDirNamesBeneathOrAbsent(root, "instances/abc"); absent || !errors.Is(err, ErrSymlink) { |
| - t.Fatalf("names %q absent %v err %v; want ErrSymlink", names, absent, err) |
| - } |
| - }) |
| - t.Run("the root", func(t *testing.T) { |
| - swap(t, root, tmp) |
| - if names, absent, err := ReadDirNamesBeneathOrAbsent(root, "instances/abc"); absent || !errors.Is(err, ErrDirUnopened) || !errors.Is(err, ErrSymlink) { |
| - t.Fatalf("names %q absent %v err %v; want ErrDirUnopened and ErrSymlink", names, absent, err) |
| - } |
| - }) |
| - t.Run("after the directory opened", func(t *testing.T) { |
| - prev := betweenDirAndLookup |
| - betweenDirAndLookup = func() { swap(t, filepath.Join(root, "instances"), empty) } |
| - t.Cleanup(func() { betweenDirAndLookup = prev }) |
| - if names, absent, err := ReadDirNamesBeneathOrAbsent(root, "instances/abc"); absent || !errors.Is(err, ErrSymlink) { |
| - t.Fatalf("names %q absent %v err %v; want ErrSymlink", names, absent, err) |
| - } |
| - }) |
| -} |
diff --git a/internal/provision/seedfleet.go b/internal/provision/seedfleet.go| index e701fcb09..eb443731c 100644 |
| --- a/internal/provision/seedfleet.go |
| +++ b/internal/provision/seedfleet.go |
| @@ -94,9 +94,46 @@ func fleetRollbackArmed(h *SeedHooks) bool { |
| return rollbackArmed(h) && h.Fleet != nil && h.Fleet.Report != nil && h.Fleet.ListPrefix != nil |
| } |
| -// fleetSeedListDir lists a directory beneath the data directory for the |
| -// local half of the proof. A seam for the tests. |
| -var fleetSeedListDir = instancefs.ReadDirNamesBeneathOrAbsent |
| +// SeedLocalName selects, among the entries of a database's directory, what |
| +// could stand in for a seed's database named base: the database, its WAL |
| +// and SHM, its <db>.seed marker, litestream's metadata, and any fetch temp |
| +// of this database (".seed-<base>-sd_….tmp…", any seed id). legacyTemps also |
| +// selects the old-style ".seed-sd_*.tmp" names, which name no instance, so |
| +// it is only for a nested directory, which holds one. It is the one list |
| +// of those names: the activator's purge and the fleet rollback's proof |
| +// both hand it to instancefs.PurgeProven. |
| +func SeedLocalName(base string, legacyTemps bool) func(name string) bool { |
| + return func(n string) bool { |
| + switch n { |
| + case base, base + "-wal", base + "-shm", base + ".seed", base + "-litestream", ".activator-" + base + "-litestream": |
| + return true |
| + } |
| + // "-sd_" and not just "-": a seed id starts sd_, and no host name |
| + // holds an underscore, so in a flat directory this never selects |
| + // the temp of a host whose name begins "<base>-". |
| + if strings.HasPrefix(n, ".seed-"+base+"-sd_") && strings.Contains(n, ".tmp") { |
| + return true |
| + } |
| + return legacyTemps && strings.HasPrefix(n, ".seed-sd_") && strings.Contains(n, ".tmp") |
| + } |
| +} |
| + |
| +// fleetSeedPurge is the local half of the fleet rollback's proof. A seam |
| +// for the tests. |
| +var fleetSeedPurge = instancefs.PurgeProven |
| + |
| +// fleetSeedPurgeProven purges one supported location of host's seed data |
| +// and proves it empty, in one call that holds its directories throughout |
| +// (instancefs.PurgeProven): nil only when the storage that was at the |
| +// location holds none of the seed's names and the path still names it. |
| +// nested is the nested location, which holds one instance. |
| +func fleetSeedPurgeProven(dataDir, dbPath string, nested bool) error { |
| + rel, err := filepath.Rel(dataDir, filepath.Dir(dbPath)) |
| + if err != nil { |
| + return err |
| + } |
| + return fleetSeedPurge(dataDir, rel, SeedLocalName(filepath.Base(dbPath), nested)) |
| +} |
| // rollbackFleetFileSeed is design §3.6 steps 1 to 4 for an aborted file seed |
| // on a customer-fleet box, and the only code that may report rolledback. It |
| @@ -107,11 +144,16 @@ var fleetSeedListDir = instancefs.ReadDirNamesBeneathOrAbsent |
| // that nothing of the seed is left. It reports rolledback only after, under |
| // one fence, with the host still rowless: |
| // |
| -// - both supported local locations, nested and flat, were purged and then |
| -// seen empty (fleetSeedLocalLeft), each listed from a descriptor opened |
| -// beneath the data directory with no symlink followed, so a path |
| -// component swapped for a link to an empty place is "not proven" and |
| -// never "empty". Both, whatever the layout reader |
| +// - both supported local locations, nested and flat, were purged and |
| +// proved empty (fleetSeedPurgeProven). Each is one call that opens the |
| +// data directory and the location once, with no symlink followed, and |
| +// holds both: it lists, removes and checks through those descriptors |
| +// and then confirms the path still names the same directory. So the |
| +// proof covers the storage that held the seed, and a component swapped |
| +// for a link, or renamed aside with an empty directory put in its |
| +// place, is "not proven", never "empty" (review rounds 1 and 2). No |
| +// path is reopened, and the path-based RemoveLocal hook is not used |
| +// here. Both locations, whatever the layout reader |
| // says now: the layout intent can change between retirement and |
| // rollback, and layout migration moves only rows that still exist, so |
| // the current layout is no evidence of where the seed's data is (plan |
| @@ -175,24 +217,12 @@ func rollbackFleetFileSeed(ctx context.Context, reg *registry.Registry, cfg Reco |
| held("a route appeared at the host, so nothing local is removed") |
| return |
| } |
| - locations := []registry.Route{ |
| - {Host: host, Kind: "instance", DBPath: NestedDBPath(cfg.DataDir, host), Socket: NestedSocket(host)}, |
| - {Host: host, Kind: "instance", DBPath: DefaultDBPath(cfg.DataDir, host), Socket: DefaultSocket(host)}, |
| - } |
| - for _, rt := range locations { |
| - if err := h.RemoveLocal(rt); err != nil { |
| - held("remove its local data at %s: %v", rt.DBPath, err) |
| - return |
| - } |
| - } |
| - for _, rt := range locations { |
| - left, err := fleetSeedLocalLeft(cfg.DataDir, rt.DBPath) |
| - if err != nil { |
| - held("cannot tell whether %s is empty: %v", rt.DBPath, err) |
| - return |
| - } |
| - if len(left) != 0 { |
| - held("%s is still on this box after the purge", strings.Join(left, ", ")) |
| + for _, loc := range []struct { |
| + db string |
| + nested bool |
| + }{{NestedDBPath(cfg.DataDir, host), true}, {DefaultDBPath(cfg.DataDir, host), false}} { |
| + if err := fleetSeedPurgeProven(cfg.DataDir, loc.db, loc.nested); err != nil { |
| + held("its local data at %s is not proven gone: %v", loc.db, err) |
| return |
| } |
| } |
| @@ -227,43 +257,3 @@ func rollbackFleetFileSeed(ctx context.Context, reg *registry.Registry, cfg Reco |
| } |
| log.Printf("provision: %s: aborted seed %s: nothing of it is left on this box or in the fleet's storage; reported rolled back", host, id) |
| } |
| - |
| -// fleetSeedLocalLeft names what could stand in for a seed's database at |
| -// dbPath: the database, its WAL and SHM, its <db>.seed marker, litestream's |
| -// metadata, and any fetch temp of this database (".seed-<base>-", any seed |
| -// id). It is the purge's own list (the activator's purgeSeedTarget), read |
| -// back. |
| -// |
| -// The scan follows no symlink and resolves no path twice. dataDir is opened |
| -// once, with no symlink at any component, and the database's directory is |
| -// opened beneath that descriptor the same way; the entries are read from |
| -// the descriptor it got. An entry of any kind under one of those names |
| -// counts, a symlink included. The directory counts as holding nothing only |
| -// when its lookup beneath the opened data directory answers "no such |
| -// entry". Anything else is an error, and the caller has no proof: a data |
| -// directory that will not open, a symlink at any component (which could |
| -// point the scan at an empty place while the data sits elsewhere), a |
| -// component that is not a directory, a listing that fails. |
| -func fleetSeedLocalLeft(dataDir, dbPath string) ([]string, error) { |
| - dir, base := filepath.Dir(dbPath), filepath.Base(dbPath) |
| - rel, err := filepath.Rel(dataDir, dir) |
| - if err != nil { |
| - return nil, err |
| - } |
| - names, absent, err := fleetSeedListDir(dataDir, rel) |
| - if err != nil { |
| - return nil, err |
| - } |
| - if absent { |
| - return nil, nil |
| - } |
| - own := map[string]bool{base: true, base + "-wal": true, base + "-shm": true, base + ".seed": true, |
| - base + "-litestream": true, ".activator-" + base + "-litestream": true} |
| - var left []string |
| - for _, n := range names { |
| - if own[n] || strings.HasPrefix(n, ".seed-"+base+"-") { |
| - left = append(left, filepath.Join(dir, n)) |
| - } |
| - } |
| - return left, nil |
| -} |
diff --git a/internal/provision/seedfleet_linux_test.go b/internal/provision/seedfleet_linux_test.go| index 2bbe478d5..554953e6c 100644 |
| --- a/internal/provision/seedfleet_linux_test.go |
| +++ b/internal/provision/seedfleet_linux_test.go |
| @@ -14,6 +14,7 @@ import ( |
| "testing" |
| "time" |
| + "github.com/carlosframework/platform/internal/instancefs" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/seeds" |
| @@ -24,26 +25,26 @@ import ( |
| // and its Report refuses to hear rolledback while either local location |
| // still holds seed data: the invariant, checked where it is reported. |
| type fleetSeedBox struct { |
| - t *testing.T |
| - dataDir string |
| - host string |
| - steps []string |
| - proceed bool |
| - fenceErr error |
| - onFence func() |
| - gen uint64 |
| - fenced map[string]uint64 |
| - removeErr map[string]error // by database path |
| - keepLocal bool // RemoveLocal answers nil and removes nothing |
| - keys map[string][]string |
| - listErr map[string]error |
| - reports []string |
| - reportErr error |
| + t *testing.T |
| + dataDir string |
| + host string |
| + steps []string |
| + proceed bool |
| + fenceErr error |
| + onFence func() |
| + gen uint64 |
| + fenced map[string]uint64 |
| + purgeErr map[string]error // by the location's directory |
| + beforePurge func(dir string) // runs before a location's purge-and-prove |
| + keys map[string][]string |
| + listErr map[string]error |
| + reports []string |
| + reportErr error |
| } |
| func newFleetSeedBox(t *testing.T, host string) *fleetSeedBox { |
| return &fleetSeedBox{t: t, host: host, proceed: true, fenced: map[string]uint64{}, |
| - removeErr: map[string]error{}, keys: map[string][]string{}, listErr: map[string]error{}} |
| + purgeErr: map[string]error{}, keys: map[string][]string{}, listErr: map[string]error{}} |
| } |
| func (b *fleetSeedBox) replicaPrefix() string { return "instances/" + b.host + "/" } |
| @@ -81,22 +82,25 @@ func (b *fleetSeedBox) hooks(h *SeedHooks) { |
| return nil |
| } |
| h.RemoveLocal = func(rt registry.Route) error { |
| - b.steps = append(b.steps, "purge "+rt.DBPath) |
| - if _, ok := b.fenced[rt.Host]; !ok { |
| - b.t.Errorf("purged %s while the host was not fenced and stopped", rt.DBPath) |
| + b.t.Errorf("the fleet rollback used the path-based purge hook for %s", rt.DBPath) |
| + return nil |
| + } |
| + // The real purge-and-prove, recorded, and failing where a test says. |
| + real := fleetSeedPurge |
| + b.t.Cleanup(func() { fleetSeedPurge = real }) |
| + fleetSeedPurge = func(root, rel string, match func(string) bool) error { |
| + dir := filepath.Join(root, rel) |
| + b.steps = append(b.steps, "purge "+dir) |
| + if len(b.fenced) == 0 { |
| + b.t.Errorf("purged %s while the host was not fenced and stopped", dir) |
| } |
| - if err := b.removeErr[rt.DBPath]; err != nil { |
| + if err := b.purgeErr[dir]; err != nil { |
| return err |
| } |
| - if b.keepLocal { |
| - return nil |
| - } |
| - for _, p := range seedDataAt(rt.DBPath) { |
| - if err := os.RemoveAll(p); err != nil { |
| - return err |
| - } |
| + if b.beforePurge != nil { |
| + b.beforePurge(dir) |
| } |
| - return nil |
| + return real(root, rel, match) |
| } |
| h.Fleet = &FleetSeedHooks{ |
| ReplicaPrefix: "instances", |
| @@ -144,7 +148,7 @@ func seedDataAt(db string) []string { |
| got = append(got, p) |
| } |
| } |
| - temps, _ := filepath.Glob(filepath.Join(filepath.Dir(db), ".seed-"+filepath.Base(db)+"-*")) |
| + temps, _ := filepath.Glob(filepath.Join(filepath.Dir(db), ".seed-"+filepath.Base(db)+"-sd_*")) |
| return append(got, temps...) |
| } |
| @@ -156,6 +160,9 @@ func placeFleetSeedData(t *testing.T, db, id string) { |
| t.Fatal(err) |
| } |
| temp := filepath.Join(filepath.Dir(db), ".seed-"+filepath.Base(db)+"-"+id+".tmp") |
| + if !strings.HasPrefix(id, "sd_") { |
| + t.Fatalf("seed id %q", id) |
| + } |
| for p, body := range map[string]string{db: "the seed's data", db + "-wal": "wal", db + "-shm": "shm", db + ".seed": id, temp: "half a fetch"} { |
| if err := os.WriteFile(p, []byte(body), 0o600); err != nil { |
| t.Fatal(err) |
| @@ -226,8 +233,8 @@ func requireUntouchedByBox(t *testing.T, s release.Store, cfg ReconcileConfig, r |
| func TestFleetFileSeedRollbackReportsRolledBackWhenEmpty(t *testing.T) { |
| s, rec, box, cfg, reg := abortedFleetSeed(t, layoutFlat) |
| - nested, flat := NestedDBPath(cfg.DataDir, rec.Host), DefaultDBPath(cfg.DataDir, rec.Host) |
| - placeFleetSeedData(t, flat, rec.Seed.ID) |
| + nested, flat := InstanceDir(cfg.DataDir, rec.Host), cfg.DataDir |
| + placeFleetSeedData(t, DefaultDBPath(cfg.DataDir, rec.Host), rec.Seed.ID) |
| if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| t.Fatal(err) |
| } |
| @@ -376,18 +383,26 @@ func TestFleetFileSeedRollbackPurgesFlatPath(t *testing.T) { |
| other := DefaultDBPath(cfg.DataDir, "other.go.tito.io") |
| otherID, _ := seeds.NewID() |
| placeFleetSeedData(t, other, otherID) |
| - var purged []registry.Route |
| - inner := cfg.Seeds.RemoveLocal |
| - cfg.Seeds.RemoveLocal = func(rt registry.Route) error { purged = append(purged, rt); return inner(rt) } |
| + // An old-style temp names no instance: in a flat directory it may be |
| + // another instance's, so it is left and holds nothing. |
| + legacy := filepath.Join(cfg.DataDir, ".seed-sd_aaaaaaaaaaaaaaaaaaaaaaaaaa.tmp") |
| + // And a host whose name begins with this database's name is another's. |
| + lookalike := filepath.Join(cfg.DataDir, ".seed-"+filepath.Base(flat)+"-x.go.tito.io.db-sd_aaaaaaaaaaaaaaaaaaaaaaaaaa.tmp") |
| + for _, p := range []string{legacy, lookalike} { |
| + if err := os.WriteFile(p, []byte("x"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| t.Fatal(err) |
| } |
| - want := []registry.Route{ |
| - {Host: rec.Host, Kind: "instance", DBPath: NestedDBPath(cfg.DataDir, rec.Host), Socket: NestedSocket(rec.Host)}, |
| - {Host: rec.Host, Kind: "instance", DBPath: flat, Socket: DefaultSocket(rec.Host)}, |
| + if want := []string{"purge " + InstanceDir(cfg.DataDir, rec.Host), "purge " + cfg.DataDir}; !reflect.DeepEqual(box.steps[1:3], want) { |
| + t.Fatalf("purged %q, want %q", box.steps[1:3], want) |
| } |
| - if !reflect.DeepEqual(purged, want) { |
| - t.Fatalf("purged %+v\n want %+v", purged, want) |
| + for _, p := range []string{legacy, lookalike} { |
| + if _, err := os.Lstat(p); err != nil { |
| + t.Fatalf("%s went with the rollback: %v", p, err) |
| + } |
| } |
| if !reflect.DeepEqual(box.reports, []string{"rolledback"}) { |
| t.Fatalf("reports = %q; another instance's files must not hold this hostname", box.reports) |
| @@ -464,29 +479,31 @@ func TestFleetFileSeedRollbackLayoutChangedHolds(t *testing.T) { |
| {name: "left nested, reader now says flat", layout: layoutFlat, at: "nested"}, |
| {name: "left in both, reader cannot be read", layout: "!", at: "both"}, |
| {name: "left flat, no layout intent", layout: release.LayoutModeNone, at: "flat"}, |
| - {name: "purge of the flat location fails", layout: layoutNested, at: "both", held: true, |
| + {name: "the flat location's purge fails", layout: layoutNested, at: "both", held: true, |
| fault: func(t *testing.T, f fix) func() { |
| - f.box.removeErr[f.flat] = errors.New("read-only file system") |
| - return func() { delete(f.box.removeErr, f.flat) } |
| + f.box.purgeErr[f.cfg.DataDir] = &fs.PathError{Op: "unlinkat", Path: f.flat, Err: syscall.EROFS} |
| + return func() { delete(f.box.purgeErr, f.cfg.DataDir) } |
| }}, |
| - {name: "purge of the nested location fails", layout: layoutFlat, at: "both", held: true, |
| + {name: "the nested location's purge fails", layout: layoutFlat, at: "both", held: true, |
| fault: func(t *testing.T, f fix) func() { |
| - f.box.removeErr[f.nest] = errors.New("read-only file system") |
| - return func() { delete(f.box.removeErr, f.nest) } |
| + f.box.purgeErr[filepath.Dir(f.nest)] = &fs.PathError{Op: "openat2", Path: f.nest, Err: syscall.EACCES} |
| + return func() { delete(f.box.purgeErr, filepath.Dir(f.nest)) } |
| }}, |
| - {name: "purge answers done and leaves the data", layout: layoutFlat, at: "flat", held: true, |
| + {name: "the flat marker is back before the proof", layout: layoutFlat, at: "flat", held: true, |
| fault: func(t *testing.T, f fix) func() { |
| - f.box.keepLocal = true |
| - return func() { f.box.keepLocal = false } |
| - }}, |
| - {name: "the flat location cannot be listed", layout: layoutNested, at: "nested", held: true, |
| - fault: func(t *testing.T, f fix) func() { |
| - return failFleetSeedListing(t, ".", &fs.PathError{Op: "openat2", Path: f.cfg.DataDir, Err: syscall.EIO}) |
| - }}, |
| - {name: "the nested location cannot be listed", layout: layoutFlat, at: "flat", held: true, |
| - fault: func(t *testing.T, f fix) func() { |
| - rel, _ := filepath.Rel(f.cfg.DataDir, filepath.Dir(f.nest)) |
| - return failFleetSeedListing(t, rel, &fs.PathError{Op: "openat2", Path: f.nest, Err: syscall.EACCES}) |
| + calls := 0 |
| + restore := instancefs.SetPurgeHookForTest(func(stage string) { |
| + if stage != "removed" { |
| + return |
| + } |
| + if calls++; calls == 2 { // the flat location is the second |
| + if err := os.WriteFile(f.flat+".seed", []byte(f.rec.Seed.ID), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + }) |
| + t.Cleanup(restore) |
| + return restore |
| }}, |
| } { |
| t.Run(c.name, func(t *testing.T) { |
| @@ -528,116 +545,103 @@ func TestFleetFileSeedRollbackLayoutChangedHolds(t *testing.T) { |
| } |
| } |
| -// failFleetSeedListing makes the local proof's listing of rel fail with |
| -// err, and returns the undo. |
| -func failFleetSeedListing(t *testing.T, rel string, err error) (clear func()) { |
| +// swapAside renames path to path+".real" and leaves in its place a symlink |
| +// to target, or (target "") an empty real directory. |
| +func swapAside(t *testing.T, path, target string) { |
| t.Helper() |
| - real := fleetSeedListDir |
| - t.Cleanup(func() { fleetSeedListDir = real }) |
| - fleetSeedListDir = func(dir, name string) ([]string, bool, error) { |
| - if name == rel { |
| - return nil, false, err |
| + if err := os.Rename(path, path+".real"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if target == "" { |
| + if err := os.Mkdir(path, 0o700); err != nil { |
| + t.Fatal(err) |
| } |
| - return real(dir, name) |
| + return |
| + } |
| + if err := os.Symlink(target, path); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// putBack undoes swapAside. |
| +func putBack(t *testing.T, path string) { |
| + t.Helper() |
| + if err := os.RemoveAll(path); err != nil { |
| + t.Fatal(err) |
| } |
| - return func() { fleetSeedListDir = real } |
| + if err := os.Rename(path+".real", path); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// swapCases are the directories a same-uid process can replace: the |
| +// location that holds the seed's data, and each component above it. real |
| +// is where the data is once path is renamed aside. |
| +type swapCase struct { |
| + name string |
| + at func(dataDir, host string) string // the database's path |
| + path func(dataDir, host string) string // the component replaced |
| +} |
| + |
| +var swapCases = []swapCase{ |
| + {"the instance directory", NestedDBPath, InstanceDir}, |
| + {"the instances directory above it", NestedDBPath, func(dataDir, _ string) string { return filepath.Join(dataDir, "instances") }}, |
| + {"the data directory itself", DefaultDBPath, func(dataDir, _ string) string { return dataDir }}, |
| } |
| // Round 1 review, P1: the local proof must not follow a symlinked directory |
| -// component. The purge runs, and then a component of a location that still |
| -// holds the seed's data is swapped for a link to an empty directory (a |
| -// same-uid process, or the tenant's own). A scan by path would walk the |
| -// link, find nothing and call it proof. The scan reads from descriptors |
| -// opened with no symlink followed, so the swap holds the hostname: nothing |
| -// is listed in the bucket and nothing is reported. With the real directory |
| -// back, the next pass purges it and reports rolledback. |
| +// component. Under the fence, before the location that holds the seed's |
| +// data is purged, one of its components is swapped for a link to an empty |
| +// directory (a same-uid process, or the tenant's own). By path, through the |
| +// link, the location looks empty. The purge and proof open with no symlink |
| +// followed, so the hostname is held: the bucket is not listed, nothing is |
| +// reported, and the data behind the link is untouched. With the real |
| +// directory back, the next pass purges it and reports rolledback. |
| func TestFleetFileSeedRollbackSwappedDirectoryHolds(t *testing.T) { |
| - for _, c := range []struct { |
| - name string |
| - at func(dataDir, host string) string // the location holding the data |
| - // swap is the component replaced, and what the link points at. |
| - swap func(dataDir, host, empty string) (path, target string) |
| - }{ |
| - {name: "the instance directory", |
| - at: NestedDBPath, |
| - swap: func(dataDir, host, empty string) (string, string) { |
| - return InstanceDir(dataDir, host), empty |
| - }}, |
| - {name: "the instances directory above it", |
| - at: NestedDBPath, |
| - swap: func(dataDir, host, empty string) (string, string) { |
| - // The link's target holds an empty directory of the right name. |
| - if err := os.MkdirAll(filepath.Join(empty, InstanceID(host)), 0o700); err != nil { |
| - panic(err) |
| - } |
| - return filepath.Join(dataDir, "instances"), empty |
| - }}, |
| - {name: "the data directory itself", |
| - at: DefaultDBPath, |
| - swap: func(dataDir, host, empty string) (string, string) { return dataDir, empty }}, |
| - } { |
| + for _, c := range swapCases { |
| t.Run(c.name, func(t *testing.T) { |
| s, rec, box, cfg, reg := abortedFleetSeed(t, layoutFlat) |
| - db := c.at(cfg.DataDir, rec.Host) |
| + db, path := c.at(cfg.DataDir, rec.Host), c.path(cfg.DataDir, rec.Host) |
| placeFleetSeedData(t, db, rec.Seed.ID) |
| - path, target := c.swap(cfg.DataDir, rec.Host, t.TempDir()) |
| - // The purge of the last location is where the swap lands: after |
| - // it, before the proof. This purge removes nothing, so the data |
| - // is still on the box, behind the link. |
| - purge := cfg.Seeds.RemoveLocal |
| - swapped := false |
| - cfg.Seeds.RemoveLocal = func(rt registry.Route) error { |
| - if swapped { |
| - return purge(rt) |
| - } |
| - box.steps = append(box.steps, "purge "+rt.DBPath) |
| - if rt.DBPath == DefaultDBPath(cfg.DataDir, rec.Host) { |
| - swapped = true |
| - if err := os.Rename(path, path+".real"); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.Symlink(target, path); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - return nil |
| - } |
| - if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + empty := t.TempDir() |
| + if err := os.MkdirAll(filepath.Join(empty, InstanceID(rec.Host)), 0o700); err != nil { |
| t.Fatal(err) |
| } |
| - if !swapped { |
| - t.Fatal("the swap never ran") |
| - } |
| - // By path, through the link, the location now looks empty. |
| - if left := seedDataAt(db); len(left) != 0 { |
| - t.Fatalf("the swap did not hide the data: %v", left) |
| - } |
| - if len(box.reports) != 0 { |
| - t.Fatalf("with a component swapped for a link: reports = %q, want none", box.reports) |
| + target := empty |
| + if path == filepath.Dir(db) && path != cfg.DataDir { |
| + target = filepath.Join(empty, InstanceID(rec.Host)) |
| } |
| - for _, st := range box.steps { |
| - if strings.HasPrefix(st, "list ") { |
| - t.Fatalf("the bucket was listed without a local proof: %q", box.steps) |
| + swapped := false |
| + box.beforePurge = func(dir string) { |
| + if dir == filepath.Dir(db) && !swapped { |
| + swapped = true |
| + swapAside(t, path, target) |
| } |
| } |
| - real := strings.Replace(db, path, path+".real", 1) |
| - if len(seedDataAt(real)) != 5 { |
| - t.Fatalf("the hidden data at %s: %v", real, seedDataAt(real)) |
| - } |
| - // The same on the next pass, while the link stays. |
| - if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| - t.Fatal(err) |
| - } |
| - if len(box.reports) != 0 { |
| - t.Fatalf("second pass behind the link: reports = %q", box.reports) |
| - } |
| - // The directory is put back: purged for real, proved, reported. |
| - if err := os.Remove(path); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.Rename(path+".real", path); err != nil { |
| - t.Fatal(err) |
| + for pass := 0; pass < 2; pass++ { // and the same while the link stays |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !swapped { |
| + t.Fatal("the swap never ran") |
| + } |
| + if left := seedDataAt(db); len(left) != 0 { |
| + t.Fatalf("the swap did not hide the data: %v", left) |
| + } |
| + if len(box.reports) != 0 { |
| + t.Fatalf("with a component swapped for a link: reports = %q, want none", box.reports) |
| + } |
| + for _, st := range box.steps { |
| + if strings.HasPrefix(st, "list ") { |
| + t.Fatalf("the bucket was listed without a local proof: %q", box.steps) |
| + } |
| + } |
| + real := strings.Replace(db, path, path+".real", 1) |
| + if len(seedDataAt(real)) != 5 { |
| + t.Fatalf("the hidden data at %s: %v", real, seedDataAt(real)) |
| + } |
| } |
| + putBack(t, path) |
| if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| t.Fatal(err) |
| } |
| @@ -648,6 +652,84 @@ func TestFleetFileSeedRollbackSwappedDirectoryHolds(t *testing.T) { |
| } |
| } |
| +// Round 2 review, the invariant: the cleanup proof covers the same storage |
| +// identity that held the seed. While the rollback works on the location |
| +// that holds the data, a same-uid process renames a directory aside and |
| +// puts an empty real directory in its place: between the listing and the |
| +// removals, or between the removals and the proof. A purge or a proof that |
| +// reopened by path would then find the empty replacement and call it |
| +// clean. The one function that owns the location (instancefs.PurgeProven) |
| +// holds its descriptors, so its removals follow the directory it opened, |
| +// and it refuses to prove a path that no longer names that directory: |
| +// nothing is reported. The data moved aside is never counted as gone while |
| +// it exists: by the time anything is reported, it has been removed. |
| +func TestFleetFileSeedRollbackHoldsItsDirectories(t *testing.T) { |
| + for _, c := range swapCases { |
| + for _, stage := range []string{"listed", "removed"} { |
| + t.Run(c.name+", after "+stage, func(t *testing.T) { |
| + s, rec, box, cfg, reg := abortedFleetSeed(t, layoutFlat) |
| + db, path := c.at(cfg.DataDir, rec.Host), c.path(cfg.DataDir, rec.Host) |
| + placeFleetSeedData(t, db, rec.Seed.ID) |
| + aside := strings.Replace(db, path, path+".real", 1) |
| + // The hook fires in both locations' calls; the swap is for |
| + // the one the rollback is in when it holds the data. |
| + in, swapped := "", false |
| + box.beforePurge = func(dir string) { in = dir } |
| + restore := instancefs.SetPurgeHookForTest(func(got string) { |
| + if got != stage || in != filepath.Dir(db) || swapped { |
| + return |
| + } |
| + swapped = true |
| + if stage == "listed" && len(seedDataAt(db)) != 5 { |
| + t.Errorf("at the swap the data was already gone: %v", seedDataAt(db)) |
| + } |
| + swapAside(t, path, "") |
| + if err := os.MkdirAll(filepath.Dir(db), 0o700); err != nil { |
| + t.Error(err) |
| + } |
| + }) |
| + defer restore() |
| + // The invariant, checked at the report: no rolledback while |
| + // the storage that held the seed still holds any of it. |
| + report := cfg.Seeds.Fleet.Report |
| + cfg.Seeds.Fleet.Report = func(ctx context.Context, acct, app, host, id, op, code, held string) error { |
| + if left := seedDataAt(aside); op == FleetSeedRolledBack && len(left) != 0 { |
| + t.Errorf("rolledback was reported while the directory moved aside holds %v", left) |
| + } |
| + return report(ctx, acct, app, host, id, op, code, held) |
| + } |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !swapped { |
| + t.Fatal("the swap never ran") |
| + } |
| + if len(box.reports) != 0 { |
| + t.Fatalf("with the directory replaced after %s: reports = %q, want none", stage, box.reports) |
| + } |
| + for _, st := range box.steps { |
| + if strings.HasPrefix(st, "list ") { |
| + t.Fatalf("the bucket was listed without a local proof: %q", box.steps) |
| + } |
| + } |
| + // The removals followed the directory that was opened. |
| + if left := seedDataAt(aside); len(left) != 0 { |
| + t.Fatalf("the directory moved aside still holds %v: the removals ran on the replacement", left) |
| + } |
| + requireUntouchedByBox(t, s, cfg, rec) |
| + // The next pass opens what the path names now, purges and |
| + // proves that, and reports. |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !reflect.DeepEqual(box.reports, []string{"rolledback"}) { |
| + t.Fatalf("the next pass: reports = %q", box.reports) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| // The row goes first, as for --from: the pass that finds a row retires it |
| // and leaves everything else, and a later pass with no row rolls back. |
| func TestFleetFileSeedRowRetiredBeforeRollback(t *testing.T) { |