cabinet/internal/gc/gc.go

46 lines
809 B
Go
Raw Normal View History

package gc
import (
"os"
"sort"
"time"
"github.com/rs/zerolog/log"
)
type GC interface {
List() ([]os.FileInfo, error)
Delete(id string) error
}
func Start(g GC, maxSize int, interval time.Duration) {
ticker := time.NewTicker(interval)
for {
<-ticker.C
log.Debug().Msg("running GC")
infos, err := g.List()
if err != nil {
log.Err(err).Msg("could not run GC")
continue
}
var size int
for _, info := range infos {
size += int(info.Size())
}
sort.Sort(sorter(infos))
for size > maxSize {
fi := infos[0]
log.Debug().Msgf("deleting file %s", fi.Name())
if err := g.Delete(fi.Name()); err != nil {
log.Err(err).Msgf("could not delete file %s", fi.Name())
break
}
size -= int(fi.Size())
infos = infos[1:]
}
log.Debug().Msg("finished GC")
}
}