carlos / platform Public

activator, provision: Task 10 review fixes, the changes

09ba5a257 carried only the test file's rename: its other paths were not
staged. This is the rest of that commit, as its message describes.

1. seedNotDB sets the terminal code only for a verdict on the contents
   (lease.CheckSaysDamaged). A check that could not run reports nothing
   and is retried.
2. The rollback's local proof (fleetSeedLocalLeft), PurgeSeedLocal and
   purgeSeedTarget list directories through
   instancefs.ReadDirNamesBeneathOrAbsent: no symlink followed at any
   component, names read from the opened descriptor, absence decided
   beneath an opened ancestor.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 1f49ce92f763ed9b32544208f7654132caf33b86 parent 09ba5a2
11 files changed, +544 −74
  • internal/activator/seedfleet_linux_test.go +74 −0
  • internal/activator/seedkey_linux_test.go +2 −2
  • internal/activator/seedplace.go +35 −8
  • internal/activator/seedpurge_linux_test.go +43 −5
  • internal/instancefs/instancefs_other.go +7 −0
  • internal/instancefs/readdir_linux.go +51 −0
  • internal/instancefs/readdir_linux_test.go +105 −0
  • internal/lease/check.go +11 −0
  • internal/lease/checkdamaged_test.go +59 −0
  • internal/provision/seedfleet.go +35 −26
  • internal/provision/seedfleet_linux_test.go +122 −33

CI failed — run details

diff --git a/internal/activator/seedfleet_linux_test.go b/internal/activator/seedfleet_linux_test.go
index ea86d1f6b..dfe193ab1 100644
--- a/internal/activator/seedfleet_linux_test.go
+++ b/internal/activator/seedfleet_linux_test.go
@@ -15,6 +15,7 @@ import (
"path/filepath"
"reflect"
"strings"
+ "syscall"
"testing"
"time"
@@ -190,6 +191,67 @@ func TestFleetFileSeedMismatchReportsFailed(t *testing.T) {
requireRefusal(t, fresh, err, "length or sha256")
}
+// Round 1 review, P1: the integrity check can fail without saying anything
+// about the snapshot (a disk error, permissions, a busy database). That is
+// not "not a database": nothing is reported, the seed stays ready, and the
+// next wake checks again and places it. Only a verdict on the contents is
+// terminal (TestFleetFileSeedCheckFailureReportsFailed, a real corrupt
+// file through the real check).
+func TestFleetFileSeedCheckCouldNotRunReportsNothing(t *testing.T) {
+ real := checkSeedDB
+ for name, transient := range map[string]error{
+ "disk": &os.PathError{Op: "read", Path: "snapshot", Err: syscall.EIO},
+ "permissions": fmt.Errorf("open: %w", os.ErrPermission),
+ "cancelled": fmt.Errorf("integrity_check: %w", context.DeadlineExceeded),
+ } {
+ t.Run(name, func(t *testing.T) {
+ r := fleetFileSeedRig(t, true)
+ checks := 0
+ setKnob(t, &checkSeedDB, func(ctx context.Context, path string) error {
+ if checks++; checks == 1 {
+ return transient
+ }
+ return real(ctx, path)
+ })
+ fresh, err := r.b.Restore(context.Background(), r.rt)
+ if err == nil || fresh {
+ t.Fatalf("Restore = fresh %v, %v; want a failed wake", fresh, err)
+ }
+ if len(r.failed) != 0 {
+ t.Fatalf("a check that could not run was reported as %q", r.failed)
+ }
+ if _, err := os.Lstat(r.rt.DBPath); !os.IsNotExist(err) {
+ t.Fatalf("an unchecked snapshot is at the row's path: %v", err)
+ }
+ if fresh, err := r.b.Restore(context.Background(), r.rt); err != nil || fresh {
+ t.Fatalf("the retry = fresh %v, %v; want the seed placed", fresh, err)
+ }
+ if got, _ := os.ReadFile(r.rt.DBPath); !bytes.Equal(got, r.objs.body[r.id]) || len(r.failed) != 0 {
+ t.Fatalf("after the retry: failed %q, and the database is the snapshot: %v", r.failed, bytes.Equal(got, r.objs.body[r.id]))
+ }
+ })
+ }
+ // The mark the real check puts on damage is terminal, as is damage
+ // SQLite names itself; an unmarked error with the same words is not.
+ for name, c := range map[string]struct {
+ err error
+ want []string
+ }{
+ "marked damage": {fmt.Errorf("check: %w", lease.ErrCheckFailed), []string{provision.SeedCodeNotADatabase}},
+ "unmarked, same words": {errors.New("file is not a database"), nil},
+ } {
+ t.Run(name, func(t *testing.T) {
+ r := fleetFileSeedRig(t, true)
+ setKnob(t, &checkSeedDB, func(context.Context, string) error { return c.err })
+ fresh, err := r.b.Restore(context.Background(), r.rt)
+ requireRefusal(t, fresh, err, "integrity check")
+ if !reflect.DeepEqual(r.failed, c.want) {
+ t.Fatalf("failed = %q, want %q", r.failed, c.want)
+ }
+ })
+ }
+}
+
// A read that fails, a disk that fails: the wake fails, nothing is
// reported, and the next wake places the seed.
func TestFleetFileSeedUnreadReportsNothing(t *testing.T) {
@@ -438,6 +500,18 @@ func TestRegionFileSeedPlacementUnchanged(t *testing.T) {
if len(m.failed) != 0 || len(m.mirror.lists) != 0 {
t.Fatalf("a region box reported %q and listed %q", m.failed, m.mirror.lists)
}
+ // A check that fails, for any cause, is the same sentence and the same
+ // retried wake it always was.
+ for _, cause := range []error{&os.PathError{Op: "read", Path: "snapshot", Err: syscall.EIO}, fmt.Errorf("check: %w", lease.ErrCheckFailed)} {
+ c := fleetFileSeedRig(t, false)
+ c.b.CustomerFleet = false
+ setKnob(t, &checkSeedDB, func(context.Context, string) error { return cause })
+ fresh, err = c.b.Restore(context.Background(), c.rt)
+ requireRefusal(t, fresh, err, "the snapshot is not a database that passes an integrity check.")
+ if len(c.failed) != 0 {
+ t.Fatalf("a region box reported %q", c.failed)
+ }
+ }
}
// snapshotWith is a small valid database holding one table named table, so
diff --git a/internal/activator/seedkey_linux_test.go b/internal/activator/seedkey_linux_test.go
index 658a40a13..f824747d0 100644
--- a/internal/activator/seedkey_linux_test.go
+++ b/internal/activator/seedkey_linux_test.go
@@ -87,7 +87,7 @@ func TestAnAbortedImportsKeyDoesNotOutliveItsRollback(t *testing.T) {
if err := RetireSeedKey(rt.DBPath, rt.Host, before); err != nil {
t.Fatalf("RetireSeedKey: %v", err)
}
- if err := PurgeSeedLocal(rt.DBPath, LayoutNested); err != nil {
+ if err := PurgeSeedLocal(filepath.Dir(rt.DBPath), rt.DBPath, LayoutNested); err != nil {
t.Fatal(err)
}
for _, n := range []string{rt.Host + ".env", rt.Host + instancekey.AdoptionSuffix} {
@@ -156,7 +156,7 @@ func TestRetireSeedKeyLeavesWhatPredatesTheImport(t *testing.T) {
if err := RetireSeedKey(rt.DBPath, rt.Host, before); err != nil {
t.Fatal(err)
}
- if err := PurgeSeedLocal(rt.DBPath, LayoutNested); err != nil {
+ if err := PurgeSeedLocal(filepath.Dir(rt.DBPath), rt.DBPath, LayoutNested); err != nil {
t.Fatal(err)
}
if got, err := os.ReadFile(envPath); err != nil || string(got) != string(predating) {
diff --git a/internal/activator/seedplace.go b/internal/activator/seedplace.go
index 4a58c335a..b667e47a6 100644
--- a/internal/activator/seedplace.go
+++ b/internal/activator/seedplace.go
@@ -64,9 +64,18 @@ func seedMismatch(host string) error {
code: provision.SeedCodeMismatch}
}
+// seedNotDB is a snapshot the integrity check did not pass. The sentence is
+// the same whatever the cause, as it always was. The code, which makes a
+// fleet box report the seed as failed for good, is set only when the check
+// gave a verdict on the contents (lease.CheckSaysDamaged). A check that
+// could not run to an answer (I/O, permissions, a busy database) carries no
+// code: the wake fails and the next one checks again.
func seedNotDB(host string, err error) error {
- return &SeedPlacementError{Sentence: fmt.Sprintf("%s could not start from its seed: the snapshot is not a database that passes an integrity check.", host), Err: err,
- code: provision.SeedCodeNotADatabase}
+ e := &SeedPlacementError{Sentence: fmt.Sprintf("%s could not start from its seed: the snapshot is not a database that passes an integrity check.", host), Err: err}
+ if lease.CheckSaysDamaged(err) {
+ e.code = provision.SeedCodeNotADatabase
+ }
+ return e
}
func seedUnread(host string, err error) error {
@@ -375,12 +384,26 @@ func seedTempName(base, id string) string { return ".seed-" + base + "-" + id +
// layout is the instance's: only a nested directory holds a single instance,
// so only there may a purge remove an old-style ".seed-sd_*.tmp" name,
// which says no instance.
-func PurgeSeedLocal(dbPath string, layout Layout) error {
+//
+// "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
+// 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,
+// which must then exist.
+func PurgeSeedLocal(dataDir, dbPath string, layout Layout) error {
dir, base, err := splitDBPath(dbPath)
if err != nil {
return err
}
- if _, err := os.Lstat(dir); errors.Is(err, os.ErrNotExist) {
+ root, rel := filepath.Dir(dir), filepath.Base(dir)
+ 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)
@@ -389,7 +412,7 @@ func PurgeSeedLocal(dbPath string, layout Layout) error {
// PurgeSeedLocalFor is PurgeSeedLocal for rt's database, in the layout this
// backend finds rt in.
func (b *ExecBackend) PurgeSeedLocalFor(rt registry.Route) error {
- return PurgeSeedLocal(rt.DBPath, b.pathsFor(rt).layout)
+ return PurgeSeedLocal(b.DataDir, rt.DBPath, b.pathsFor(rt).layout)
}
// ReadSeedMarker is the seed id the <db>.seed marker beside dbPath names,
@@ -437,12 +460,16 @@ func splitDBPath(dbPath string) (dir, base string, err error) {
func purgeSeedTarget(dir, base string, legacyTemps bool) error {
names := []string{base, base + "-wal", base + "-shm", base + SeedMarkerSuffix,
base + "-litestream", ".activator-" + base + "-litestream"}
- ents, err := os.ReadDir(dir)
+ // 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
}
- for _, e := range ents {
- n := e.Name()
+ 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)
diff --git a/internal/activator/seedpurge_linux_test.go b/internal/activator/seedpurge_linux_test.go
index 6f472fd43..d66f777fb 100644
--- a/internal/activator/seedpurge_linux_test.go
+++ b/internal/activator/seedpurge_linux_test.go
@@ -4,9 +4,12 @@ package activator
import (
"context"
+ "errors"
"os"
"path/filepath"
"testing"
+
+ "github.com/carlosframework/platform/internal/instancefs"
)
// PurgeSeedLocal is the import rollback's local removal (preflight M12):
@@ -38,7 +41,7 @@ func TestPurgeSeedLocalRemovesTheDatabaseAndEverythingThatStandsInForIt(t *testi
t.Fatal(err)
}
for i := 0; i < 2; i++ {
- if err := PurgeSeedLocal(db, LayoutNested); err != nil {
+ if err := PurgeSeedLocal(filepath.Dir(db), db, LayoutNested); err != nil {
t.Fatalf("run %d: %v", i, err)
}
}
@@ -50,11 +53,46 @@ func TestPurgeSeedLocalRemovesTheDatabaseAndEverythingThatStandsInForIt(t *testi
if _, err := os.Stat(kept); err != nil {
t.Fatalf("an unrelated file went: %v", err)
}
- if err := PurgeSeedLocal(filepath.Join(t.TempDir(), "missing", "a.shop.example.com.db"), LayoutNested); err != nil {
+ box := t.TempDir()
+ if err := PurgeSeedLocal(box, filepath.Join(box, "missing", "a.shop.example.com.db"), LayoutNested); err != nil {
t.Fatalf("a missing directory: %v", err)
}
+ // A database outside the data directory is purged from its own
+ // directory, as before.
+ out := filepath.Join(t.TempDir(), "o", "a.shop.example.com.db")
+ os.MkdirAll(filepath.Dir(out), 0o700)
+ os.WriteFile(out, []byte("data"), 0o600)
+ if err := PurgeSeedLocal(box, out, LayoutNested); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Lstat(out); !os.IsNotExist(err) {
+ t.Fatalf("a database outside the data directory survived: %v", err)
+ }
+ // A data directory that is not there is an error, not "nothing to purge".
+ if err := PurgeSeedLocal(filepath.Join(box, "gone"), filepath.Join(box, "gone", "a.shop.example.com.db"), LayoutNested); err == nil {
+ t.Fatal("a missing data directory: no error")
+ }
+ // A component swapped for a link to an empty directory is refused, and
+ // the data it hid is not reported purged.
+ real := filepath.Join(box, "instances", "x")
+ if err := os.MkdirAll(real, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ hidden := filepath.Join(real, "a.shop.example.com.db")
+ if err := os.WriteFile(hidden, []byte("data"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Rename(filepath.Join(box, "instances"), filepath.Join(box, "instances.real")); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(t.TempDir(), filepath.Join(box, "instances")); err != nil {
+ t.Fatal(err)
+ }
+ if err := PurgeSeedLocal(box, hidden, LayoutNested); !errors.Is(err, instancefs.ErrSymlink) {
+ t.Fatalf("a swapped component: %v, want ErrSymlink", err)
+ }
for _, bad := range []string{"a.shop.example.com.db", "/data/instances/x/../a.db", "/data/instances/x/"} {
- if err := PurgeSeedLocal(bad, LayoutNested); err == nil {
+ if err := PurgeSeedLocal("/data", bad, LayoutNested); err == nil {
t.Errorf("%q: no error", bad)
}
}
@@ -75,7 +113,7 @@ func TestPurgeSeedLocalNeverFollowsASymlink(t *testing.T) {
if err := os.Symlink(target, db); err != nil {
t.Fatal(err)
}
- if err := PurgeSeedLocal(db, LayoutNested); err != nil {
+ if err := PurgeSeedLocal(filepath.Dir(db), db, LayoutNested); err != nil {
t.Fatal(err)
}
if _, err := os.Lstat(db); !os.IsNotExist(err) {
@@ -103,7 +141,7 @@ func TestAPlainWakeAfterPurgeSeedLocalFindsNoDatabase(t *testing.T) {
}
}
if purge {
- if err := PurgeSeedLocal(rt.DBPath, LayoutNested); err != nil {
+ if err := PurgeSeedLocal(filepath.Dir(rt.DBPath), rt.DBPath, LayoutNested); err != nil {
t.Fatal(err)
}
}
diff --git a/internal/instancefs/instancefs_other.go b/internal/instancefs/instancefs_other.go
index e8c068da1..7f05b14c4 100644
--- a/internal/instancefs/instancefs_other.go
+++ b/internal/instancefs/instancefs_other.go
@@ -88,3 +88,10 @@ 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
+ }
+ return nil, false, errors.ErrUnsupported
+}
diff --git a/internal/instancefs/readdir_linux.go b/internal/instancefs/readdir_linux.go
new file mode 100644
index 000000000..cc1c97675
--- /dev/null
+++ b/internal/instancefs/readdir_linux.go
@@ -0,0 +1,51 @@
+//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
new file mode 100644
index 000000000..ccdc3efa6
--- /dev/null
+++ b/internal/instancefs/readdir_linux_test.go
@@ -0,0 +1,105 @@
+//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/lease/check.go b/internal/lease/check.go
index 46c6205bb..1afc2a414 100644
--- a/internal/lease/check.go
+++ b/internal/lease/check.go
@@ -202,6 +202,17 @@ func sqliteSaysDamaged(err error) bool {
return false
}
+// CheckSaysDamaged reports whether err, a CheckDB or CheckDBContext error,
+// is a verdict on the file's contents: it carries ErrCheckFailed, or it is
+// SQLite's own SQLITE_CORRUPT or SQLITE_NOTADB from any statement of the
+// check, the first PRAGMA included (which CheckDBContext returns unmarked).
+// Every other error (the open, I/O, a full disk, permissions, a busy or
+// cancelled statement) says nothing about the contents, and a caller that
+// can retry should.
+func CheckSaysDamaged(err error) bool {
+ return errors.Is(err, ErrCheckFailed) || sqliteSaysDamaged(err)
+}
+
// damagedIf marks err as damage (ErrCheckFailed) when damaged is true.
func damagedIf(damaged bool, err error) error {
if damaged {
diff --git a/internal/lease/checkdamaged_test.go b/internal/lease/checkdamaged_test.go
new file mode 100644
index 000000000..70794579a
--- /dev/null
+++ b/internal/lease/checkdamaged_test.go
@@ -0,0 +1,59 @@
+package lease
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// CheckSaysDamaged separates a verdict on the file from a check that could
+// not run: a seed file's placement on a fleet box reports only the first as
+// final (fleet seeded create, Task 10 review).
+func TestCheckSaysDamaged(t *testing.T) {
+ dir := t.TempDir()
+ garbage := filepath.Join(dir, "garbage.db")
+ if err := os.WriteFile(garbage, []byte("not sqlite at all, but long enough to be read as a header and refused"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ empty := filepath.Join(dir, "empty.db")
+ db, err := sql.Open("sqlite", empty)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := db.Exec("PRAGMA user_version=1"); err != nil {
+ t.Fatal(err)
+ }
+ db.Close()
+ for name, path := range map[string]string{"not a database": garbage, "no tables": empty} {
+ if err := CheckDB(path); err == nil || !CheckSaysDamaged(err) {
+ t.Errorf("%s: CheckDB = %v; want an error that says damaged", name, err)
+ }
+ }
+ // The check could not run: nothing is known about the contents.
+ if err := CheckDB(filepath.Join(dir, "missing.db")); err == nil || CheckSaysDamaged(err) {
+ t.Errorf("a missing file: CheckDB = %v; want an error that does not say damaged", err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ good := filepath.Join(dir, "good.db")
+ db, _ = sql.Open("sqlite", good)
+ if _, err := db.Exec("create table t(x)"); err != nil {
+ t.Fatal(err)
+ }
+ db.Close()
+ if err := CheckDBContext(ctx, good); err == nil || CheckSaysDamaged(err) {
+ t.Errorf("a cancelled check: %v; want an error that does not say damaged", err)
+ }
+ for _, err := range []error{nil, os.ErrPermission, errors.New("file is not a database"), fmt.Errorf("open: %w", os.ErrNotExist)} {
+ if CheckSaysDamaged(err) {
+ t.Errorf("CheckSaysDamaged(%v) = true", err)
+ }
+ }
+ if !CheckSaysDamaged(fmt.Errorf("wrapped: %w", ErrCheckFailed)) {
+ t.Error("an error carrying ErrCheckFailed does not say damaged")
+ }
+}
diff --git a/internal/provision/seedfleet.go b/internal/provision/seedfleet.go
index a9590f4e9..e701fcb09 100644
--- a/internal/provision/seedfleet.go
+++ b/internal/provision/seedfleet.go
@@ -5,11 +5,11 @@ import (
"errors"
"fmt"
"log"
- "os"
"path"
"path/filepath"
"strings"
+ "github.com/carlosframework/platform/internal/instancefs"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/seeds"
)
@@ -94,11 +94,9 @@ func fleetRollbackArmed(h *SeedHooks) bool {
return rollbackArmed(h) && h.Fleet != nil && h.Fleet.Report != nil && h.Fleet.ListPrefix != nil
}
-// fleetSeedLstat and fleetSeedReadDir are seams for the tests.
-var (
- fleetSeedLstat = os.Lstat
- fleetSeedReadDir = os.ReadDir
-)
+// fleetSeedListDir lists a directory beneath the data directory for the
+// local half of the proof. A seam for the tests.
+var fleetSeedListDir = instancefs.ReadDirNamesBeneathOrAbsent
// 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
@@ -110,7 +108,10 @@ var (
// one fence, with the host still rowless:
//
// - both supported local locations, nested and flat, were purged and then
-// seen empty (fleetSeedLocalLeft). Both, whatever the layout reader
+// 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
// 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
@@ -185,7 +186,7 @@ func rollbackFleetFileSeed(ctx context.Context, reg *registry.Registry, cfg Reco
}
}
for _, rt := range locations {
- left, err := fleetSeedLocalLeft(rt.DBPath)
+ left, err := fleetSeedLocalLeft(cfg.DataDir, rt.DBPath)
if err != nil {
held("cannot tell whether %s is empty: %v", rt.DBPath, err)
return
@@ -231,29 +232,37 @@ func rollbackFleetFileSeed(ctx context.Context, reg *registry.Registry, cfg Reco
// 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. Lstat, so a symlink there counts as there. Only "does not exist"
-// is absence: any other error is returned, and the caller has no proof.
-func fleetSeedLocalLeft(dbPath string) ([]string, error) {
+// 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)
- var left []string
- for _, n := range []string{base, base + "-wal", base + "-shm", base + ".seed", base + "-litestream", ".activator-" + base + "-litestream"} {
- p := filepath.Join(dir, n)
- if _, err := fleetSeedLstat(p); err == nil {
- left = append(left, p)
- } else if !errors.Is(err, os.ErrNotExist) {
- return nil, err
- }
- }
- ents, err := fleetSeedReadDir(dir)
- if errors.Is(err, os.ErrNotExist) {
- return left, nil // no directory: no temp in it
+ rel, err := filepath.Rel(dataDir, dir)
+ if err != nil {
+ return nil, err
}
+ names, absent, err := fleetSeedListDir(dataDir, rel)
if err != nil {
return nil, err
}
- for _, e := range ents {
- if strings.HasPrefix(e.Name(), ".seed-"+base+"-") {
- left = append(left, filepath.Join(dir, e.Name()))
+ 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 2bd3c236e..2bbe478d5 100644
--- a/internal/provision/seedfleet_linux_test.go
+++ b/internal/provision/seedfleet_linux_test.go
@@ -1,3 +1,5 @@
+//go:build linux
+
package provision
import (
@@ -477,35 +479,14 @@ func TestFleetFileSeedRollbackLayoutChangedHolds(t *testing.T) {
f.box.keepLocal = true
return func() { f.box.keepLocal = false }
}},
- {name: "stat of the flat database errors", layout: layoutNested, at: "nested", held: true,
- fault: func(t *testing.T, f fix) func() {
- setFleetSeedStat(t, func(p string) (fs.FileInfo, error) {
- if p == f.flat {
- return nil, &fs.PathError{Op: "lstat", Path: p, Err: syscall.EIO}
- }
- return os.Lstat(p)
- }, nil)
- return func() { fleetSeedLstat = os.Lstat }
- }},
- {name: "stat of the nested marker errors", layout: layoutFlat, at: "flat", held: true,
+ {name: "the flat location cannot be listed", layout: layoutNested, at: "nested", held: true,
fault: func(t *testing.T, f fix) func() {
- setFleetSeedStat(t, func(p string) (fs.FileInfo, error) {
- if p == f.nest+".seed" {
- return nil, &fs.PathError{Op: "lstat", Path: p, Err: syscall.EACCES}
- }
- return os.Lstat(p)
- }, nil)
- return func() { fleetSeedLstat = os.Lstat }
+ return failFleetSeedListing(t, ".", &fs.PathError{Op: "openat2", Path: f.cfg.DataDir, Err: syscall.EIO})
}},
- {name: "the flat directory cannot be read for temps", layout: layoutNested, at: "nested", held: true,
+ {name: "the nested location cannot be listed", layout: layoutFlat, at: "flat", held: true,
fault: func(t *testing.T, f fix) func() {
- setFleetSeedStat(t, nil, func(dir string) ([]os.DirEntry, error) {
- if dir == filepath.Dir(f.flat) {
- return nil, &fs.PathError{Op: "open", Path: dir, Err: syscall.EIO}
- }
- return os.ReadDir(dir)
- })
- return func() { fleetSeedReadDir = os.ReadDir }
+ rel, _ := filepath.Rel(f.cfg.DataDir, filepath.Dir(f.nest))
+ return failFleetSeedListing(t, rel, &fs.PathError{Op: "openat2", Path: f.nest, Err: syscall.EACCES})
}},
} {
t.Run(c.name, func(t *testing.T) {
@@ -547,15 +528,123 @@ func TestFleetFileSeedRollbackLayoutChangedHolds(t *testing.T) {
}
}
-func setFleetSeedStat(t *testing.T, lstat func(string) (fs.FileInfo, error), readDir func(string) ([]os.DirEntry, error)) {
+// 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()) {
t.Helper()
- oldL, oldR := fleetSeedLstat, fleetSeedReadDir
- t.Cleanup(func() { fleetSeedLstat, fleetSeedReadDir = oldL, oldR })
- if lstat != nil {
- fleetSeedLstat = lstat
+ real := fleetSeedListDir
+ t.Cleanup(func() { fleetSeedListDir = real })
+ fleetSeedListDir = func(dir, name string) ([]string, bool, error) {
+ if name == rel {
+ return nil, false, err
+ }
+ return real(dir, name)
}
- if readDir != nil {
- fleetSeedReadDir = readDir
+ return func() { fleetSeedListDir = real }
+}
+
+// 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.
+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 }},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ s, rec, box, cfg, reg := abortedFleetSeed(t, layoutFlat)
+ db := c.at(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 {
+ 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)
+ }
+ 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))
+ }
+ // 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)
+ }
+ if err := Reconcile(ctx, s, reg, cfg); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(box.reports, []string{"rolledback"}) {
+ t.Fatalf("with the directory back: reports = %q", box.reports)
+ }
+ })
}
}