fix(scanner): remove scanner temp files after every scan

A scanner binary that its timeout kills cannot remove its own temp files.
A killed trivy left its database download in the temp dir as trivy-<n>
and getter<n>, up to 279 MB for each scan. Concurrent rescans filled the
scanner temp dir, and the disk guard then refused all new scans.

Each scanner run now gets a private dir in the temp dir, and the scanner
binary gets this dir as TMPDIR. The scan removes the dir and its contents
when the scan ends, also after a timeout or an error. Each new scan also
removes abandoned dirs that are older than one hour. These dirs come from
a process that stopped during a scan, or from a removal that failed.
This commit is contained in:
2026-12-01 03:11:51 +00:00
parent 8c53c3c741
commit e4077066ef
10 changed files with 331 additions and 31 deletions
+106
View File
@@ -0,0 +1,106 @@
// Package workdir gives each scanner run a private temp dir. The scanner binary gets it as
// TMPDIR, so the files it stages there, such as the database download of a trivy killed by
// its timeout, are removed with the dir.
package workdir
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/rs/zerolog/log"
)
const (
prefix = "gohoarder-scan-"
// Far past every scanner timeout, so a sweep never takes the dir of a scan still running elsewhere.
abandonedAfter = time.Hour
)
var (
liveMu sync.Mutex
live = map[string]struct{}{}
// One sweep at a time; concurrent scans skip it instead of queueing.
sweeping sync.Mutex
)
// Dir is the temp dir of one scanner run.
type Dir struct {
path string
}
// New sweeps abandoned work dirs, then creates one for scanner.
func New(scanner string) (*Dir, error) {
sweep(time.Now().Add(-abandonedAfter))
path, err := os.MkdirTemp("", prefix+scanner+"-*")
if err != nil {
return nil, fmt.Errorf("create scan work dir: %w", err)
}
liveMu.Lock()
live[path] = struct{}{}
liveMu.Unlock()
return &Dir{path: path}, nil
}
// Path returns the work dir.
func (d *Dir) Path() string { return d.path }
// Env returns env with TMPDIR set to the work dir; exec uses the last value of a duplicate key.
func (d *Dir) Env(env []string) []string {
return append(env, "TMPDIR="+d.path)
}
// Remove deletes the work dir and everything in it. A dir it cannot delete is left to a later sweep.
func (d *Dir) Remove() {
err := os.RemoveAll(d.path)
liveMu.Lock()
delete(live, d.path)
liveMu.Unlock()
if err != nil {
log.Warn().Err(err).Str("path", d.path).Msg("Cannot remove scan work dir")
}
}
// sweep removes work dirs last modified before cutoff that no scan in this process uses: those of
// a process killed mid-scan, and those Remove could not delete.
func sweep(cutoff time.Time) {
if !sweeping.TryLock() {
return
}
defer sweeping.Unlock()
dir := os.TempDir()
entries, err := os.ReadDir(dir)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
log.Warn().Err(err).Str("dir", dir).Msg("Cannot list dir for abandoned scan work dirs")
}
return
}
for _, e := range entries {
if !e.IsDir() || !strings.HasPrefix(e.Name(), prefix) {
continue
}
path := filepath.Join(dir, e.Name())
liveMu.Lock()
_, inUse := live[path]
liveMu.Unlock()
if inUse {
continue
}
info, err := e.Info()
if err != nil || !info.ModTime().Before(cutoff) {
continue
}
if err := os.RemoveAll(path); err != nil {
log.Warn().Err(err).Str("path", path).Msg("Cannot remove abandoned scan work dir")
continue
}
log.Info().Str("path", path).Msg("Removed abandoned scan work dir")
}
}
+100
View File
@@ -0,0 +1,100 @@
package workdir
import (
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func entries(t *testing.T, dir string) []string {
t.Helper()
list, err := os.ReadDir(dir)
require.NoError(t, err)
names := make([]string, 0, len(list))
for _, e := range list {
names = append(names, e.Name())
}
return names
}
func TestRemoveDeletesWhatTheScannerLeft(t *testing.T) {
tmp := t.TempDir()
t.Setenv("TMPDIR", tmp)
wd, err := New("trivy")
require.NoError(t, err)
assert.Equal(t, tmp, filepath.Dir(wd.Path()))
assert.Equal(t, "TMPDIR="+wd.Path(), wd.Env([]string{"TMPDIR=/tmp"})[1])
require.NoError(t, os.MkdirAll(filepath.Join(wd.Path(), "trivy-1", "db"), 0o700))
require.NoError(t, os.WriteFile(filepath.Join(wd.Path(), "trivy-1", "db", "trivy.db"), []byte("x"), 0o600))
wd.Remove()
assert.Empty(t, entries(t, tmp))
}
func TestSweepRemovesOnlyAbandonedDirs(t *testing.T) {
tmp := t.TempDir()
t.Setenv("TMPDIR", tmp)
old := time.Now().Add(-2 * abandonedAfter)
mk := func(name string, mtime time.Time) {
path := filepath.Join(tmp, name)
require.NoError(t, os.MkdirAll(filepath.Join(path, "x"), 0o700))
require.NoError(t, os.Chtimes(path, mtime, mtime))
}
mk(prefix+"trivy-1", old)
mk(prefix+"npm-audit-2", time.Now())
mk("trivy-3", old)
live, err := New("grype")
require.NoError(t, err)
require.NoError(t, os.Chtimes(live.Path(), old, old))
sweep(time.Now().Add(-abandonedAfter))
assert.ElementsMatch(t, []string{prefix + "npm-audit-2", "trivy-3", filepath.Base(live.Path())}, entries(t, tmp))
live.Remove()
}
func TestSweepRetriesADirWhoseRemoveFailed(t *testing.T) {
tmp := t.TempDir()
t.Setenv("TMPDIR", tmp)
wd, err := New("trivy")
require.NoError(t, err)
locked := filepath.Join(wd.Path(), "locked")
require.NoError(t, os.MkdirAll(filepath.Join(locked, "f"), 0o700))
require.NoError(t, os.Chmod(locked, 0o500)) // #nosec G302 -- read-only on purpose
t.Cleanup(func() { _ = os.Chmod(locked, 0o700) }) // #nosec G302 -- test dir
wd.Remove()
require.NoError(t, os.Chmod(locked, 0o700)) // #nosec G302 -- test dir
old := time.Now().Add(-2 * abandonedAfter)
require.NoError(t, os.Chtimes(wd.Path(), old, old))
sweep(time.Now().Add(-abandonedAfter))
assert.Empty(t, entries(t, tmp))
}
func TestConcurrentScansLeaveNothing(t *testing.T) {
tmp := t.TempDir()
t.Setenv("TMPDIR", tmp)
var wg sync.WaitGroup
for range 16 {
wg.Add(1)
go func() {
defer wg.Done()
wd, err := New("npm-audit")
if !assert.NoError(t, err) {
return
}
assert.NoError(t, os.WriteFile(filepath.Join(wd.Path(), "f"), []byte("x"), 0o600))
wd.Remove()
}()
}
wg.Wait()
assert.Empty(t, entries(t, tmp))
}