// 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") } }