-
Notifications
You must be signed in to change notification settings - Fork 1
/
cleanup.go
71 lines (61 loc) · 1.7 KB
/
cleanup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"io/ioutil"
"log"
"os"
"path"
"time"
)
func cleanup() {
if !(config.CleanupEveryMinutes > 0) {
log.Printf("CLEANUP_EVERY_MINUTES is not set - cleanup disabled")
return
}
if !(config.CleanupAfterHours > 0) {
log.Printf("CLEANUP_AFTER_HOURS is not set - cleanup disabled")
return
}
go func() {
interval := time.Duration(config.CleanupEveryMinutes) * time.Minute
log.Printf("Cleaning up every %v", interval)
ticker := time.NewTicker(interval)
for {
<-ticker.C
log.Printf("Cleaning up...")
removeIfOlderThan := time.Now().Add(
(-1 * time.Duration(config.CleanupAfterHours) * time.Hour))
entries, err := ioutil.ReadDir(config.DataDir)
if err != nil {
log.Printf("Error: Cleanup failed to read dir: %v", err)
continue
}
for _, entry := range entries {
keyPath := path.Join(config.DataDir, entry.Name())
perKeyEntries, err := ioutil.ReadDir(keyPath)
if err != nil {
log.Printf("Error: Cleanup failed to read dir: %v", err)
continue
}
if len(perKeyEntries) != 1 {
log.Printf("Error: Cleanup expected 1 file for key '%s', but got %d",
entry.Name(), len(perKeyEntries))
continue
}
fileEntry := perKeyEntries[0]
if fileEntry.ModTime().Before(removeIfOlderThan) {
filePath := path.Join(config.DataDir, entry.Name(), fileEntry.Name())
log.Printf(" Removing: %s/%s ('%s')",
entry.Name(), fileEntry.Name(), filePath)
if err := os.Remove(filePath); err != nil {
log.Printf(" File removal failed: %v", err)
continue
}
if err := os.Remove(keyPath); err != nil {
log.Printf(" Dir removal failed: %v", err)
continue
}
}
}
}
}()
}