/
gra_log_purger.go
134 lines (112 loc) · 2.54 KB
/
gra_log_purger.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"flag"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
)
func main() {
var (
graLogDir string
graLogDaysToKeep int
)
flag.StringVar(&graLogDir,
"graLogDir",
"",
"Specifies the directory from which to purge GRA log files.",
)
flag.IntVar(&graLogDaysToKeep,
"graLogDaysToKeep",
60,
"Specifies the maximum age of the GRA log files allowed.",
)
flag.Parse()
if graLogDir == "" {
logErrorWithTimestamp(fmt.Errorf("No gra log directory supplied"))
os.Exit(1)
}
if graLogDaysToKeep < 0 {
logErrorWithTimestamp(fmt.Errorf("graLogDaysToKeep should be >= 0"))
os.Exit(1)
}
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGTERM)
logWithTimestamp("Will purge old GRA logs once every hour\n")
ticker := time.NewTicker(1 * time.Hour)
defer ticker.Stop()
cleanup := func() {
ageCutoff := time.Duration(graLogDaysToKeep*24) * time.Hour
deleted, failed, err := PurgeGraLogs(graLogDir, ageCutoff)
if err != nil {
logErrorWithTimestamp(err)
} else {
logWithTimestamp(fmt.Sprintf("Deleted %v files, failed to delete %v files\n", deleted, failed))
}
logWithTimestamp("Sleeping for one hour\n")
}
cleanup()
for {
select {
case sig := <-sigCh:
logWithTimestamp("%s", sig)
os.Exit(0)
case <-ticker.C:
cleanup()
}
}
}
func isOldGraLog(file os.FileInfo, oldestTime time.Time) bool {
if file.IsDir() == false &&
strings.HasPrefix(file.Name(), "GRA_") &&
strings.HasSuffix(file.Name(), ".log") &&
file.ModTime().Before(oldestTime) {
return true
}
return false
}
func PurgeGraLogs(dir string, ageCutoff time.Duration) (int, int, error) {
succeeded := 0
failed := 0
handle, err := os.Open(dir)
if err != nil {
return succeeded, failed, err
}
oldestTime := time.Now().Add(-ageCutoff)
for {
files, err := handle.Readdir(1024)
if err == io.EOF {
break
} else if err != nil {
return succeeded, failed, err
}
for _, file := range files {
fileName := file.Name()
if isOldGraLog(file, oldestTime) {
if err := os.Remove(filepath.Join(dir, fileName)); err != nil {
logErrorWithTimestamp(err)
failed++
} else {
succeeded++
}
}
}
}
return succeeded, failed, nil
}
func logErrorWithTimestamp(err error) {
fmt.Fprintf(os.Stderr, "[%s] - ", time.Now().Local())
fmt.Fprintf(os.Stderr, err.Error()+"\n")
}
func logWithTimestamp(format string, args ...interface{}) {
fmt.Printf("[%s] - ", time.Now().Local())
if nil == args {
fmt.Printf(format)
} else {
fmt.Printf(format, args...)
}
}