carlos / platform Public

boxself: reap crashed writes' stages; census accepts them meanwhile

A crash between staging and rename left a .carlos-write-<hex> directory
in <data>/monitor that the claim census refused until removed by hand.
safefile.ReapStages applies Reap's checks to one directory's own entries
(exact name, this euid, 0700, at most one regular data file, nothing
followed or descended into) with a caller's age. boxself runs it with
10 minutes before every write and the agent once at start. hostbox gains
CensusStages: such a stage directly in the named directory, empty or
holding one regular data file, listed no-follow, is accepted by the
claim and migration censuses. claimBoxDataCensus names <data>/monitor.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 7eb8d64f8928fb0aa0ae466d4fa1bdb34b48e825 parent 8a79cf1
14 files changed, +397 −18
  • internal/boxself/boxself.go +14 −0
  • internal/boxself/io_linux.go +12 −0
  • internal/boxself/io_linux_test.go +63 −0
  • internal/boxself/io_other.go +2 −0
  • internal/host/agententry.go +5 −0
  • internal/host/boxself_census_linux_test.go +93 −0
  • internal/host/claimcensus.go +7 −4
  • internal/hostbox/empty_census.go +52 −5
  • internal/hostbox/empty_census_classes_test.go +17 −1
  • internal/hostbox/migration_census_linux.go +7 −0
  • internal/safefile/file.go +19 −0
  • internal/safefile/reap_linux.go +49 −8
  • internal/safefile/reap_linux_test.go +52 −0
  • internal/safefile/reap_other.go +5 −0
diff --git a/internal/boxself/boxself.go b/internal/boxself/boxself.go
index 004f8d9df..98d3d6366 100644
--- a/internal/boxself/boxself.go
+++ b/internal/boxself/boxself.go
@@ -44,6 +44,20 @@ const (
maxAssign = 1 << 20
)
+// staleStage is how old a write's staging directory must be before a
+// later write, or the agent at start, removes it as a crashed write's
+// leftover. A write takes milliseconds; ten minutes leaves any write in
+// progress, the agent's or the drill's, alone.
+const staleStage = 10 * time.Minute
+
+// ReapStaging removes the staging directories crashed writes left in
+// <data>/monitor (WriteFile also does before every write). The agent calls
+// it at start. Only this process's euid's stages older than ten minutes
+// go; nothing outside <data>/monitor is looked at.
+func ReapStaging(dataDir string) error {
+ return reapStaging(filepath.Dir(SelfPath(dataDir)))
+}
+
// ErrUnsafe refuses a monitor file that is not a regular file with one
// link reached without following a symlink, a write over anything but a
// regular file, and a read over its cap.
diff --git a/internal/boxself/io_linux.go b/internal/boxself/io_linux.go
index 144ea4bac..52755043a 100644
--- a/internal/boxself/io_linux.go
+++ b/internal/boxself/io_linux.go
@@ -51,6 +51,9 @@ func writeFile(path string, body []byte) error {
if err := safefile.MkdirAll(dir, 0o755); err != nil {
return unsafeOr(path, err)
}
+ // Best effort: a failed reap leaves the stale stage for the next write
+ // and for the claim census, which accepts it; it never blocks this write.
+ _ = reapStaging(dir)
d, err := safefile.OpenDir(dir)
if err != nil {
return unsafeOr(path, err)
@@ -74,6 +77,15 @@ func removeFile(path string) error {
return safefile.Remove(path)
}
+// reapStaging removes this euid's abandoned staging directories directly in
+// dir: safefile.ReapStages, the exact .carlos-write-<32 hex> name, mode 0700,
+// at most the one regular data file, nothing followed or descended into,
+// and older than staleStage so another process's write in progress is left
+// alone.
+func reapStaging(dir string) error {
+ return safefile.ReapStages(dir, staleStage)
+}
+
// unsafeOr marks a symlinked or non-directory component as ErrUnsafe and
// passes any other error through.
func unsafeOr(path string, err error) error {
diff --git a/internal/boxself/io_linux_test.go b/internal/boxself/io_linux_test.go
index d9cf6d8d3..c0575e3e1 100644
--- a/internal/boxself/io_linux_test.go
+++ b/internal/boxself/io_linux_test.go
@@ -4,6 +4,7 @@ package boxself
import (
"bytes"
+ "crypto/rand"
"errors"
"fmt"
"os"
@@ -12,6 +13,8 @@ import (
"syscall"
"testing"
"time"
+
+ "github.com/carlosframework/platform/internal/safefile"
)
// The monitor files' I/O follows no symlink and touches nothing but a
@@ -295,3 +298,63 @@ func plantNonRegular(t *testing.T, kind, path string) {
t.Fatal(err)
}
}
+
+// crashedStage leaves what a write that crashed between staging and rename
+// leaves in <data>/monitor: safefile's staging directory with its data
+// file, aged by age.
+func crashedStage(t *testing.T, dataDir string, age time.Duration) string {
+ t.Helper()
+ var nonce [16]byte
+ if _, err := rand.Read(nonce[:]); err != nil {
+ t.Fatal(err)
+ }
+ stage := filepath.Join(dataDir, "monitor", fmt.Sprintf("%s%x", safefile.StagePrefix, nonce))
+ if err := os.MkdirAll(stage, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(stage, "data"), []byte(`{"v":1`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ at := time.Now().Add(-age)
+ for _, p := range []string{filepath.Join(stage, "data"), stage} {
+ if err := os.Chtimes(p, at, at); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return stage
+}
+
+// TestCrashedWriteIsCleanedOnTheNextWrite: a stage a crashed write left is
+// removed by the next write of any monitor file once it is older than
+// staleStage, and by ReapStaging at the agent's start; a younger one (a
+// write in progress, perhaps another process's) is left alone.
+func TestCrashedWriteIsCleanedOnTheNextWrite(t *testing.T) {
+ dir := t.TempDir()
+ stale := crashedStage(t, dir, staleStage+time.Minute)
+ young := crashedStage(t, dir, time.Minute)
+ if err := Write(dir, Self{Ref: "jolly-otter", At: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Lstat(stale); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("the crashed write's stage survived the next write: %v", err)
+ }
+ if _, err := os.Stat(filepath.Join(young, "data")); err != nil {
+ t.Fatalf("a young stage was removed: %v", err)
+ }
+ if s, err := Read(dir); err != nil || s.Ref != "jolly-otter" {
+ t.Fatalf("Read after the write: %+v, %v", s, err)
+ }
+
+ // At the agent's start, before any write.
+ dir = t.TempDir()
+ stale = crashedStage(t, dir, staleStage+time.Minute)
+ if err := ReapStaging(dir); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Lstat(stale); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("ReapStaging left the crashed write's stage: %v", err)
+ }
+ if err := ReapStaging(t.TempDir()); err != nil {
+ t.Fatalf("ReapStaging with no monitor dir: %v", err)
+ }
+}
diff --git a/internal/boxself/io_other.go b/internal/boxself/io_other.go
index 7eb5572a5..a8e20fa68 100644
--- a/internal/boxself/io_other.go
+++ b/internal/boxself/io_other.go
@@ -11,3 +11,5 @@ func readFile(string, int) ([]byte, error) { return nil, ErrUnsupported }
func writeFile(string, []byte) error { return ErrUnsupported }
func removeFile(string) error { return ErrUnsupported }
+
+func reapStaging(string) error { return ErrUnsupported }
diff --git a/internal/host/agententry.go b/internal/host/agententry.go
index 1085f735c..35bb3fd90 100644
--- a/internal/host/agententry.go
+++ b/internal/host/agententry.go
@@ -55,6 +55,11 @@ func agentEntry(getenv func(string) string, resolve func() (string, error), back
// every boxSelfEvery while the agent runs, so one that can no longer
// be written goes stale and the drill (boxself.ReadFresh) refuses it;
// a failed write also removes the earlier record where it can.
+ // A write the agent or the drill crashed in the middle of leaves a
+ // staging directory in <data>/monitor; clear the stale ones first.
+ if err := boxself.ReapStaging(dataDirFrom(getenv)); err != nil {
+ logf("agent: clearing crashed writes in the restore drill's records: %v", err)
+ }
selfCtx, stopSelf := context.WithCancel(context.Background())
publish := func() { publishBoxSelf(dataDirFrom(getenv), groupReferenced(getenv), time.Now(), logf) }
publish()
diff --git a/internal/host/boxself_census_linux_test.go b/internal/host/boxself_census_linux_test.go
index 58a922143..c86aab0b6 100644
--- a/internal/host/boxself_census_linux_test.go
+++ b/internal/host/boxself_census_linux_test.go
@@ -3,7 +3,10 @@
package host
import (
+ "crypto/rand"
"errors"
+ "fmt"
+ "os"
"path/filepath"
"slices"
"testing"
@@ -12,6 +15,7 @@ import (
"github.com/carlosframework/platform/internal/boxself"
"github.com/carlosframework/platform/internal/dbverify"
"github.com/carlosframework/platform/internal/hostbox"
+ "github.com/carlosframework/platform/internal/safefile"
)
// TestBoxSelfFilesInClaimCensus: the drill records the agent writes on
@@ -42,3 +46,92 @@ func TestBoxSelfFilesInClaimCensus(t *testing.T) {
t.Fatalf("census without self.json's entry: %v", err)
}
}
+
+// TestCrashedMonitorWriteNeverWedgesClaimCensus: a write that crashed
+// between staging and rename leaves safefile's staging directory in
+// <data>/monitor. The claim census accepts it meanwhile (and nothing that
+// merely looks like one), and the next write, once it is stale, removes it.
+func TestCrashedMonitorWriteNeverWedgesClaimCensus(t *testing.T) {
+ data, opt, units := t.TempDir(), t.TempDir(), t.TempDir()
+ roots := map[string]string{"data": data, "opt": opt, "units": units}
+ census := func() error {
+ return hostbox.CheckMigrationRoots(t.Context(), roots, map[string][]string{"data": claimDataCensus(data)}, nil)
+ }
+ if err := boxself.Write(data, boxself.Self{Ref: "jolly-otter", At: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+ stage := func(dir string) string {
+ var nonce [16]byte
+ if _, err := rand.Read(nonce[:]); err != nil {
+ t.Fatal(err)
+ }
+ p := filepath.Join(dir, fmt.Sprintf("%s%x", safefile.StagePrefix, nonce))
+ if err := os.Mkdir(p, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(p, "data"), []byte(`{"v":1`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return p
+ }
+ monitor := filepath.Join(data, "monitor")
+ crashed := stage(monitor)
+ if err := census(); err != nil {
+ t.Fatalf("the census refused a crashed write's stage: %v", err)
+ }
+
+ // Only the writer's exact shape is accepted.
+ for name, plant := range map[string]func() (undo func()){
+ "a stage with a second file": func() func() {
+ p := stage(monitor)
+ if err := os.WriteFile(filepath.Join(p, "more"), nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return func() { os.RemoveAll(p) }
+ },
+ "a stage-named symlink": func() func() {
+ p := filepath.Join(monitor, safefile.StagePrefix+"00000000000000000000000000000000")
+ if err := os.Symlink(t.TempDir(), p); err != nil {
+ t.Fatal(err)
+ }
+ return func() { os.Remove(p) }
+ },
+ "a near-miss name": func() func() {
+ p := filepath.Join(monitor, safefile.StagePrefix+"abc")
+ if err := os.Mkdir(p, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(p, "data"), nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return func() { os.RemoveAll(p) }
+ },
+ "a stage outside monitor": func() func() {
+ p := stage(data)
+ return func() { os.RemoveAll(p) }
+ },
+ } {
+ undo := plant()
+ if err := census(); !errors.Is(err, hostbox.ErrTypedInventory) {
+ t.Errorf("%s: census = %v, want ErrTypedInventory", name, err)
+ }
+ undo()
+ }
+
+ // Once stale, the next write removes it, and the census still passes.
+ old := time.Now().Add(-time.Hour)
+ for _, p := range []string{filepath.Join(crashed, "data"), crashed} {
+ if err := os.Chtimes(p, old, old); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := boxself.Write(data, boxself.Self{Ref: "jolly-otter", At: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Lstat(crashed); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("the next write left the crashed write's stage: %v", err)
+ }
+ if err := census(); err != nil {
+ t.Fatalf("census after the cleanup: %v", err)
+ }
+}
diff --git a/internal/host/claimcensus.go b/internal/host/claimcensus.go
index bf0fefcf5..14d475ab3 100644
--- a/internal/host/claimcensus.go
+++ b/internal/host/claimcensus.go
@@ -119,14 +119,17 @@ func claimBoxDataCensus(dataDir string) []string {
// the drill's local copy of its record (dbverify.LocalPath). All
// three are written through boxself.WriteFile, whose staging
// directory is removed after the rename; a crash between the two
- // leaves a .carlos-write-* directory holding the staged file,
- // which this census does not classify and so refuses (fails
- // closed); an operator removes it.
+ // leaves a .carlos-write-<hex> directory holding the staged file,
+ // which CensusStages below accepts until the next write (or the
+ // agent's start) removes it.
boxself.SelfPath(dataDir), boxself.AssignmentPath(dataDir), dbverify.LocalPath(dataDir),
} {
files = append(files, hostbox.CensusFile(rel(path)))
}
- return files
+ // <data>/monitor may also hold those writes' crash leftovers: staging
+ // directories by safefile's exact name, each empty or holding one
+ // regular file (boxself.ReapStaging removes them).
+ return append(files, hostbox.CensusStages(rel(filepath.Dir(boxself.SelfPath(dataDir)))))
}
func claimOptCensus(optDir string) []string {
diff --git a/internal/hostbox/empty_census.go b/internal/hostbox/empty_census.go
index f6c15e96e..f15d957b3 100644
--- a/internal/hostbox/empty_census.go
+++ b/internal/hostbox/empty_census.go
@@ -6,14 +6,17 @@ import (
"encoding/json"
"errors"
"github.com/carlosframework/platform/internal/hostguard"
+ "io"
"io/fs"
"os"
+ "path"
"path/filepath"
"slices"
"strings"
"github.com/carlosframework/platform/internal/hostclaim"
"github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/safefile"
)
type EmptyInstallationCensus struct {
@@ -221,6 +224,9 @@ func (c EmptyInstallationCensus) checkLocal(ctx context.Context, obs hostclaim.O
if rule, ok := rules[rel]; ok {
return rule.check(path, d)
}
+ if censusIsStage(rules, rel) {
+ return censusStageCheck(path, d)
+ }
if name == "units" && censusVendorUnitLink(root, path) {
return nil
}
@@ -252,9 +258,10 @@ func (c EmptyInstallationCensus) checkLocal(ctx context.Context, obs hostclaim.O
// claim journals check their own records). The tagged forms are the precise
// classes. None of them assigns anything to an installation.
const (
- censusFileTag = "file:"
- censusTreeTag = "tree:"
- censusLinkTag = "link:"
+ censusFileTag = "file:"
+ censusTreeTag = "tree:"
+ censusLinkTag = "link:"
+ censusStageTag = "stage:"
)
// CensusFile classifies rel as one shared regular file.
@@ -264,6 +271,14 @@ func CensusFile(rel string) string { return censusFileTag + rel }
// hold only directories and regular files, still checked for the host name.
func CensusTree(rel string) string { return censusTreeTag + rel }
+// CensusStages classifies rel as a directory whose direct entries may also
+// include a safefile writer's staging directories (safefile.IsStageName):
+// a crash between staging and rename leaves one, and the writer removes it
+// later (safefile.ReapStages). Each must be a real directory holding at
+// most one regular file named data. Every other entry of rel is censused
+// as before; rel itself must be a real directory.
+func CensusStages(rel string) string { return censusStageTag + rel }
+
// CensusLink classifies rel as a symlink whose raw target is exactly target.
func CensusLink(rel, target string) string { return censusLinkTag + rel + "\x00" + target }
@@ -277,7 +292,7 @@ func censusRules(entries []string, host string) (map[string]censusRule, error) {
for _, entry := range entries {
rule := censusRule{}
rel := entry
- for _, tag := range []string{censusFileTag, censusTreeTag, censusLinkTag} {
+ for _, tag := range []string{censusFileTag, censusTreeTag, censusLinkTag, censusStageTag} {
if rest, ok := strings.CutPrefix(entry, tag); ok {
rule.kind, rel = tag, rest
break
@@ -317,7 +332,7 @@ func (r censusRule) check(path string, d fs.DirEntry) error {
return ErrTypedInventory
}
return nil
- case censusTreeTag:
+ case censusTreeTag, censusStageTag:
if symlink || !d.IsDir() {
return ErrTypedInventory
}
@@ -338,6 +353,38 @@ func (r censusRule) check(path string, d fs.DirEntry) error {
return ErrTypedInventory
}
+// censusIsStage reports whether rel is a staging directory's name directly
+// in a directory classified CensusStages.
+func censusIsStage(rules map[string]censusRule, rel string) bool {
+ rule, ok := rules[path.Dir(rel)]
+ return ok && rule.kind == censusStageTag && safefile.IsStageName(path.Base(rel))
+}
+
+// censusStageCheck accepts a writer's staging directory: a real directory
+// (not a symlink) holding nothing, or one regular file named data. It is
+// listed through safefile.OpenDir (on Linux no component followed, so a
+// stage swapped for a symlink after the walk's lstat is refused, never
+// listed), names and types only, no file opened. Its contents are not
+// walked further.
+func censusStageCheck(p string, d fs.DirEntry) error {
+ if d.Type()&os.ModeSymlink != 0 || !d.IsDir() {
+ return ErrTypedInventory
+ }
+ dir, err := safefile.OpenDir(p)
+ if err != nil {
+ return ErrTypedInventory
+ }
+ defer dir.Close()
+ entries, err := dir.ReadDir(3)
+ if err != nil && err != io.EOF {
+ return err
+ }
+ if len(entries) > 1 || len(entries) == 1 && (entries[0].Name() != "data" || !entries[0].Type().IsRegular()) {
+ return ErrTypedInventory
+ }
+ return filepath.SkipDir
+}
+
// censusInTree reports whether the nearest classified ancestor of rel is a
// shared tree. An opaque ancestor is skipped before its contents are read.
func censusInTree(rules map[string]censusRule, rel string) bool {
diff --git a/internal/hostbox/empty_census_classes_test.go b/internal/hostbox/empty_census_classes_test.go
index 30506adf4..39a7b9415 100644
--- a/internal/hostbox/empty_census_classes_test.go
+++ b/internal/hostbox/empty_census_classes_test.go
@@ -62,8 +62,14 @@ func TestEmptyCensusClassifiesSharedEntriesExactly(t *testing.T) {
write(at("opt", "store/v1/app"))
write(at("units", "a.service"))
link(at("units", "a.service"), at("units", "multi-user.target.wants/a.service"))
+ // A crashed safefile write's leftover beside the monitor files.
+ stage := "monitor/.carlos-write-0123456789abcdef0123456789abcdef"
+ write(at("data", stage+"/data"))
+ if err = os.Mkdir(at("data", "monitor/.carlos-write-fedcba9876543210fedcba9876543210"), 0o700); err != nil {
+ t.Fatal(err)
+ }
shared := map[string][]string{
- "data": {"opaque"},
+ "data": {"opaque", CensusStages("monitor")},
"opt": {CensusFile("bin"), CensusTree("store")},
"units": {CensusFile("a.service"), CensusLink("multi-user.target.wants/a.service", at("units", "a.service"))},
}
@@ -119,6 +125,16 @@ func TestEmptyCensusClassifiesSharedEntriesExactly(t *testing.T) {
}
}))
refuse("host-named foreign unit", created(at("units", "x@shop.example.service"), write))
+ refuse("a stage with a second file", created(at("data", stage+"/more"), write))
+ refuse("a stage's data as a symlink", func() func() {
+ path := at("data", stage+"/data")
+ remove(path)()
+ link(at("opt", "bin"), path)
+ return func() { remove(path)(); write(path) }
+ })
+ refuse("a stage-named symlink", created(at("data", "monitor/.carlos-write-00000000000000000000000000000000"), func(p string) { link(at("opt", "store"), p) }))
+ refuse("a near-miss stage name", created(at("data", "monitor/.carlos-write-abc/data"), write))
+ refuse("a stage below the stages directory", created(at("data", "monitor/sub/.carlos-write-11111111111111111111111111111111/data"), write))
refuse("file where a link is classified", func() func() {
path := at("units", "multi-user.target.wants/a.service")
remove(path)()
diff --git a/internal/hostbox/migration_census_linux.go b/internal/hostbox/migration_census_linux.go
index f047ac80b..026ae04e5 100644
--- a/internal/hostbox/migration_census_linux.go
+++ b/internal/hostbox/migration_census_linux.go
@@ -93,6 +93,13 @@ func CheckMigrationRoots(ctx context.Context, roots map[string]string, shared ma
}
return err
}
+ if censusIsStage(rules, rel) {
+ err := censusStageCheck(path, d)
+ if err != nil && err != filepath.SkipDir {
+ return migrationRefusal(err, name, rel)
+ }
+ return err
+ }
if name == "units" && censusVendorUnitLink(root, path) {
return nil
}
diff --git a/internal/safefile/file.go b/internal/safefile/file.go
index 63e72a6ab..1f70dafab 100644
--- a/internal/safefile/file.go
+++ b/internal/safefile/file.go
@@ -3,8 +3,27 @@ package safefile
import (
"io"
"os"
+ "strings"
)
+// StagePrefix begins every staging directory the Linux writer makes beside
+// its target: StagePrefix followed by 32 lowercase hex digits.
+const StagePrefix = ".carlos-write-"
+
+// IsStageName reports whether name is exactly a writer staging directory's
+// name, the only names Reap and ReapStages remove.
+func IsStageName(name string) bool {
+ if !strings.HasPrefix(name, StagePrefix) || len(name) != len(StagePrefix)+32 {
+ return false
+ }
+ for _, c := range name[len(StagePrefix):] {
+ if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
+ return false
+ }
+ }
+ return true
+}
+
func WriteFile(path string, body []byte, mode os.FileMode) error {
return Write(path, mode, func(w io.Writer) error { _, err := w.Write(body); return err })
}
diff --git a/internal/safefile/reap_linux.go b/internal/safefile/reap_linux.go
index 5d8670629..ddd97d3d8 100644
--- a/internal/safefile/reap_linux.go
+++ b/internal/safefile/reap_linux.go
@@ -30,17 +30,58 @@ func Reap(dir string) error {
return nil
}
-func reapStageName(name string) bool {
- const prefix = ".carlos-write-"
- if !strings.HasPrefix(name, prefix) || len(name) != len(prefix)+32 {
- return false
+func reapStageName(name string) bool { return IsStageName(name) }
+
+// ReapStages removes abandoned writer staging directories directly in dir,
+// with Reap's checks (the exact stage name, owned by this euid, mode 0700,
+// at most the writer's single regular data file, nothing followed, nothing
+// crossed), older than olderThan. Unlike Reap it looks at dir's own entries
+// only and descends into nothing else. A missing dir is harmless.
+func ReapStages(dir string, olderThan time.Duration) error {
+ fd, err := openDir(dir, false, 0)
+ if errors.Is(err, unix.ENOENT) {
+ return nil
+ }
+ if err != nil {
+ return err
}
- for _, c := range name[len(prefix):] {
- if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
- return false
+ d := os.NewFile(uintptr(fd), dir)
+ defer d.Close()
+ cutoff := time.Now().Add(-olderThan)
+ var failures error
+ for seen := 0; ; {
+ entries, err := d.ReadDir(128)
+ if err != nil && err != io.EOF {
+ return &os.PathError{Op: "reap staging", Path: dir, Err: errors.Join(failures, err)}
+ }
+ for _, entry := range entries {
+ if seen++; seen > 100000 {
+ return &os.PathError{Op: "reap staging", Path: dir, Err: errors.Join(failures, fmt.Errorf("more than 100000 entries"))}
+ }
+ name := entry.Name()
+ if !reapStageName(name) || entry.Type() != 0 && !entry.IsDir() {
+ continue
+ }
+ cfd, e := reapOpenAt(int(d.Fd()), name, unix.O_RDONLY|unix.O_DIRECTORY)
+ if reapSkip(e) {
+ continue
+ }
+ if e != nil {
+ failures = errors.Join(failures, e)
+ continue
+ }
+ child := os.NewFile(uintptr(cfd), name)
+ e = reapStage(int(d.Fd()), name, child, cutoff)
+ child.Close()
+ failures = errors.Join(failures, e)
+ }
+ if err == io.EOF {
+ if failures != nil {
+ return &os.PathError{Op: "reap staging", Path: dir, Err: failures}
+ }
+ return nil
}
}
- return true
}
func reapOpenAt(dir int, name string, flags uint64) (int, error) {
diff --git a/internal/safefile/reap_linux_test.go b/internal/safefile/reap_linux_test.go
index bd60238e3..1c10ca1f9 100644
--- a/internal/safefile/reap_linux_test.go
+++ b/internal/safefile/reap_linux_test.go
@@ -228,3 +228,55 @@ func TestReapContinuesPastUnreadableDirectory(t *testing.T) {
t.Fatalf("unreadable sibling prevented cleanup: %v", err)
}
}
+
+// TestReapStagesTopLevelOnly: ReapStages removes stale stages directly in
+// dir with Reap's checks and its own age, and descends into nothing.
+func TestReapStagesTopLevelOnly(t *testing.T) {
+ root := t.TempDir()
+ stale := reapTestStage(t, root, ".carlos-write-"+strings.Repeat("1", 32), true)
+ empty := reapTestStage(t, root, ".carlos-write-"+strings.Repeat("2", 32), false)
+ nested := reapTestStage(t, filepath.Join(root, "sub"), ".carlos-write-"+strings.Repeat("3", 32), true)
+ extra := reapTestStage(t, root, ".carlos-write-"+strings.Repeat("4", 32), true)
+ if err := os.WriteFile(filepath.Join(extra, "more"), []byte("x"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ reapTestAge(t, extra)
+ young := reapTestStage(t, root, ".carlos-write-"+strings.Repeat("5", 32), true)
+ recent := time.Now().Add(-5 * time.Minute)
+ for _, p := range []string{filepath.Join(young, "data"), young} {
+ if err := os.Chtimes(p, recent, recent); err != nil {
+ t.Fatal(err)
+ }
+ }
+ victim := filepath.Join(t.TempDir(), "victim")
+ if err := os.Mkdir(victim, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(victim, "data"), []byte("keep"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(root, ".carlos-write-"+strings.Repeat("6", 32))
+ if err := os.Symlink(victim, link); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := ReapStages(root, 10*time.Minute); err != nil {
+ t.Fatal(err)
+ }
+ for _, p := range []string{stale, empty} {
+ if _, err := os.Lstat(p); !os.IsNotExist(err) {
+ t.Errorf("stale stage remains: %s: %v", p, err)
+ }
+ }
+ for _, p := range []string{nested, extra, young} {
+ if _, err := os.Stat(filepath.Join(p, "data")); err != nil {
+ t.Errorf("retained stage changed: %s: %v", p, err)
+ }
+ }
+ if body, err := os.ReadFile(filepath.Join(victim, "data")); err != nil || string(body) != "keep" {
+ t.Errorf("a stage-named symlink was followed: %q, %v", body, err)
+ }
+ if err := ReapStages(filepath.Join(root, "missing"), time.Minute); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/safefile/reap_other.go b/internal/safefile/reap_other.go
index 74f6e02f5..f228f5e29 100644
--- a/internal/safefile/reap_other.go
+++ b/internal/safefile/reap_other.go
@@ -2,5 +2,10 @@
package safefile
+import "time"
+
// Reap has no work on platforms whose writer uses ordinary temporary files.
func Reap(dir string) error { return nil }
+
+// ReapStages likewise has no work here.
+func ReapStages(dir string, olderThan time.Duration) error { return nil }