fix: report storage usage and reclaim archived workspaces (#1813)
This commit is contained in:
@@ -42,25 +42,41 @@ func New(config Config) *Provider {
|
||||
}
|
||||
|
||||
type candidate struct {
|
||||
path string
|
||||
owner OwnershipMarker
|
||||
size int64
|
||||
path string
|
||||
owner OwnershipMarker
|
||||
size int64
|
||||
measured bool
|
||||
}
|
||||
|
||||
func (p *Provider) Analyze(ctx context.Context) (Analysis, error) {
|
||||
candidates, protected, warnings, err := p.classify(ctx)
|
||||
_, trashTasks, protected, roots, warnings, err := p.classificationInputs(ctx)
|
||||
if err != nil {
|
||||
return Analysis{}, err
|
||||
}
|
||||
analysis := Analysis{Warnings: warnings}
|
||||
for _, item := range candidates {
|
||||
analysis.CandidateBytes += item.size
|
||||
}
|
||||
for path := range protected {
|
||||
if size, sizeErr := directorySizeNoSymlinks(path); sizeErr == nil {
|
||||
for index := range roots {
|
||||
size, sizeErr := directorySizeNoFollow(roots[index].path)
|
||||
if sizeErr != nil {
|
||||
analysis.Warnings = append(
|
||||
analysis.Warnings,
|
||||
fmt.Sprintf("measure workspace %s: %v", roots[index].path, sizeErr),
|
||||
)
|
||||
continue
|
||||
}
|
||||
roots[index].size = size
|
||||
roots[index].measured = true
|
||||
analysis.TotalBytes += size
|
||||
if _, active := protected[roots[index].path]; active {
|
||||
analysis.ActiveBytes += size
|
||||
}
|
||||
}
|
||||
candidates, err := p.eligibleCandidates(roots, protected, trashTasks)
|
||||
if err != nil {
|
||||
return Analysis{}, err
|
||||
}
|
||||
for _, item := range candidates {
|
||||
analysis.CandidateBytes += item.size
|
||||
}
|
||||
return analysis, nil
|
||||
}
|
||||
|
||||
@@ -145,11 +161,14 @@ func (p *Provider) eligibleCandidates(
|
||||
if info.ModTime().After(cutoff) {
|
||||
continue
|
||||
}
|
||||
size, err := directorySizeNoSymlinks(root.path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("measure workspace candidate %s: %w", root.path, err)
|
||||
if !root.measured {
|
||||
size, err := directorySizeNoFollow(root.path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("measure workspace candidate %s: %w", root.path, err)
|
||||
}
|
||||
root.size = size
|
||||
root.measured = true
|
||||
}
|
||||
root.size = size
|
||||
candidates = append(candidates, root)
|
||||
}
|
||||
return candidates, nil
|
||||
@@ -337,7 +356,7 @@ func (p *Provider) PermanentDelete(
|
||||
if p.config.Now().Before(entry.DeleteAfter) {
|
||||
return entry, fmt.Errorf("%w: quarantine retention deadline has not elapsed", storage.ErrConflict)
|
||||
}
|
||||
if _, err := directorySizeNoSymlinks(entry.QuarantinePath); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
if _, err := directorySizeNoFollow(entry.QuarantinePath); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return entry, fmt.Errorf("validate quarantined workspace: %w", err)
|
||||
}
|
||||
if p.config.Pruner != nil && !p.config.Now().Before(entry.DeleteAfter) {
|
||||
@@ -632,14 +651,15 @@ func looksSemanticTaskDir(name string) bool {
|
||||
return index > 0 && len(name[index+1:]) == 3
|
||||
}
|
||||
|
||||
func directorySizeNoSymlinks(root string) (int64, error) {
|
||||
// directorySizeNoFollow counts files in root while treating nested symlinks as opaque entries.
|
||||
func directorySizeNoFollow(root string) (int64, error) {
|
||||
var size int64
|
||||
err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
if entry.Type()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("symlink found at %s", path)
|
||||
return nil
|
||||
}
|
||||
if entry.Type().IsRegular() {
|
||||
info, err := entry.Info()
|
||||
@@ -705,7 +725,34 @@ func writeJSONFile(path string, value any) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, encoded, 0o600)
|
||||
if info, err := os.Lstat(path); err == nil {
|
||||
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
|
||||
return fmt.Errorf("unsafe JSON control file: %s", path)
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("inspect JSON control file %s: %w", path, err)
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(path), ".kandev-control-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmpPath := tmp.Name()
|
||||
defer func() { _ = os.Remove(tmpPath) }()
|
||||
if err := tmp.Chmod(0o600); err != nil {
|
||||
_ = tmp.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := tmp.Write(encoded); err != nil {
|
||||
_ = tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmpPath, path); err != nil {
|
||||
return fmt.Errorf("install JSON control file %s: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readQuarantineManifest(root string) (quarantineManifest, error) {
|
||||
|
||||
@@ -114,6 +114,49 @@ func TestCleanupFailsClosedWhenInventoryIsIncompleteOrErrors(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnalyzeReportsAllWorkspaceBytesIncludingYoungOrphans(t *testing.T) {
|
||||
provider, root, _ := newProviderFixture(t, Inventory{Complete: true}, nil)
|
||||
oldOrphan := createOwnedCandidate(t, root, "old-orphan_abc", OwnershipMarker{
|
||||
TaskID: "old", TaskDirName: "old-orphan_abc", LayoutVersion: LayoutVersionSemantic,
|
||||
})
|
||||
youngOrphan := createOwnedCandidate(t, root, "young-orphan_def", OwnershipMarker{
|
||||
TaskID: "young", TaskDirName: "young-orphan_def", LayoutVersion: LayoutVersionSemantic,
|
||||
})
|
||||
active := createOwnedCandidate(t, root, "active-task_ghi", OwnershipMarker{
|
||||
TaskID: "active", TaskDirName: "active-task_ghi", LayoutVersion: LayoutVersionSemantic,
|
||||
})
|
||||
for path, contents := range map[string]string{
|
||||
oldOrphan: "old orphan bytes", youngOrphan: "young orphan bytes", active: "active bytes",
|
||||
} {
|
||||
if err := os.WriteFile(filepath.Join(path, "artifact"), []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
old := provider.config.Now().Add(-8 * 24 * time.Hour)
|
||||
if err := os.Chtimes(oldOrphan, old, old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider.config.Inventory = fakeInventorySource{inventory: Inventory{
|
||||
Complete: true, EnvironmentPaths: []string{active},
|
||||
}}
|
||||
|
||||
analysis, err := provider.Analyze(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Analyze: %v", err)
|
||||
}
|
||||
wantTotal := int64(0)
|
||||
for _, path := range []string{oldOrphan, youngOrphan, active} {
|
||||
size, sizeErr := directorySizeNoFollow(path)
|
||||
if sizeErr != nil {
|
||||
t.Fatal(sizeErr)
|
||||
}
|
||||
wantTotal += size
|
||||
}
|
||||
if analysis.TotalBytes != wantTotal {
|
||||
t.Fatalf("TotalBytes = %d, want %d", analysis.TotalBytes, wantTotal)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupQuarantinesOldOwnedOrphanAndRestoreIsConflictSafe(t *testing.T) {
|
||||
provider, root, store := newProviderFixture(t, Inventory{Complete: true}, nil)
|
||||
candidate := createOwnedCandidate(t, root, "orphan-task_abc", OwnershipMarker{
|
||||
@@ -282,33 +325,77 @@ func TestCleanupProtectsEveryInventorySourceAndScratchSiblingsIndependently(t *t
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupPathUncertaintyAbortsBeforeAnyMove(t *testing.T) {
|
||||
func TestCleanupQuarantinesWorkspaceWithoutFollowingNestedSymlink(t *testing.T) {
|
||||
provider, root, store := newProviderFixture(t, Inventory{Complete: true}, nil)
|
||||
first := createOwnedCandidate(t, root, "first-task_abc", OwnershipMarker{TaskID: "first", TaskDirName: "first-task_abc", LayoutVersion: LayoutVersionSemantic})
|
||||
unsafe := createOwnedCandidate(t, root, "unsafe-task_def", OwnershipMarker{TaskID: "unsafe", TaskDirName: "unsafe-task_def", LayoutVersion: LayoutVersionSemantic})
|
||||
for _, path := range []string{first, unsafe} {
|
||||
old := time.Date(2026, time.July, 1, 0, 0, 0, 0, time.UTC)
|
||||
if err := os.Chtimes(path, old, old); err != nil {
|
||||
t.Fatalf("Chtimes: %v", err)
|
||||
}
|
||||
candidate := createOwnedCandidate(t, root, "linked-task_abc", OwnershipMarker{
|
||||
TaskID: "linked", TaskDirName: "linked-task_abc", LayoutVersion: LayoutVersionSemantic,
|
||||
})
|
||||
external := t.TempDir()
|
||||
externalArtifact := filepath.Join(external, "keep")
|
||||
if err := os.WriteFile(externalArtifact, []byte("external"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(t.TempDir(), filepath.Join(unsafe, "escape")); err != nil {
|
||||
if err := os.Symlink(external, filepath.Join(candidate, "external-link")); err != nil {
|
||||
t.Fatalf("Symlink: %v", err)
|
||||
}
|
||||
old := time.Date(2026, time.July, 1, 0, 0, 0, 0, time.UTC)
|
||||
if err := os.Chtimes(unsafe, old, old); err != nil {
|
||||
t.Fatalf("Chtimes unsafe after symlink: %v", err)
|
||||
if err := os.Chtimes(candidate, old, old); err != nil {
|
||||
t.Fatalf("Chtimes candidate: %v", err)
|
||||
}
|
||||
|
||||
result, err := provider.Cleanup(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Cleanup: %v", err)
|
||||
}
|
||||
if result.Quarantined != 1 || len(store.entries) != 1 {
|
||||
t.Fatalf("cleanup result=%#v entries=%#v", result, store.entries)
|
||||
}
|
||||
if _, err := os.Stat(externalArtifact); err != nil {
|
||||
t.Fatalf("cleanup followed nested symlink target: %v", err)
|
||||
}
|
||||
entry := store.entries["entry-1"]
|
||||
if _, err := os.Lstat(filepath.Join(entry.QuarantinePath, "external-link")); err != nil {
|
||||
t.Fatalf("symlink entry was not quarantined: %v", err)
|
||||
}
|
||||
provider.config.Now = func() time.Time { return entry.DeleteAfter }
|
||||
if _, err := provider.PermanentDelete(context.Background(), entry.ID, "DELETE"); err != nil {
|
||||
t.Fatalf("PermanentDelete: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(externalArtifact); err != nil {
|
||||
t.Fatalf("permanent deletion followed nested symlink target: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupRejectsSymlinkedQuarantineManifestWithoutFollowingTarget(t *testing.T) {
|
||||
provider, root, _ := newProviderFixture(t, Inventory{Complete: true}, nil)
|
||||
candidate := createOwnedCandidate(t, root, "linked-manifest_abc", OwnershipMarker{
|
||||
TaskID: "linked-manifest", TaskDirName: "linked-manifest_abc", LayoutVersion: LayoutVersionSemantic,
|
||||
})
|
||||
externalArtifact := filepath.Join(t.TempDir(), "keep")
|
||||
const original = "external"
|
||||
if err := os.WriteFile(externalArtifact, []byte(original), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(externalArtifact, filepath.Join(candidate, quarantineManifestName)); err != nil {
|
||||
t.Fatalf("Symlink quarantine manifest: %v", err)
|
||||
}
|
||||
old := time.Date(2026, time.July, 1, 0, 0, 0, 0, time.UTC)
|
||||
if err := os.Chtimes(candidate, old, old); err != nil {
|
||||
t.Fatalf("Chtimes candidate: %v", err)
|
||||
}
|
||||
|
||||
if _, err := provider.Cleanup(context.Background()); err == nil {
|
||||
t.Fatal("Cleanup succeeded with symlink uncertainty")
|
||||
t.Fatal("Cleanup succeeded with a symlinked quarantine manifest")
|
||||
}
|
||||
if len(store.entries) != 0 {
|
||||
t.Fatalf("persisted %d entries before validating every candidate", len(store.entries))
|
||||
if _, err := os.Stat(candidate); err != nil {
|
||||
t.Fatalf("candidate moved after manifest validation failed: %v", err)
|
||||
}
|
||||
for _, path := range []string{first, unsafe} {
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
t.Fatalf("candidate moved despite path uncertainty: %v", err)
|
||||
}
|
||||
contents, err := os.ReadFile(externalArtifact)
|
||||
if err != nil {
|
||||
t.Fatalf("read external target: %v", err)
|
||||
}
|
||||
if string(contents) != original {
|
||||
t.Fatalf("quarantine manifest write followed symlink target: %q", contents)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -77,6 +77,7 @@ type CleanupResult struct {
|
||||
}
|
||||
|
||||
type Analysis struct {
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
ActiveBytes int64 `json:"active_bytes"`
|
||||
CandidateBytes int64 `json:"candidate_bytes"`
|
||||
Warnings []string `json:"warnings,omitempty"`
|
||||
|
||||
Reference in New Issue
Block a user