forked from statping/statping
-
Notifications
You must be signed in to change notification settings - Fork 144
/
routines.go
52 lines (41 loc) · 1.54 KB
/
routines.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
package database
import (
"fmt"
"github.com/statping-ng/statping-ng/utils"
"time"
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/postgres"
_ "github.com/mattn/go-sqlite3"
)
var (
log = utils.Log.WithField("type", "database")
)
// Maintenance will automatically delete old records from 'failures' and 'hits'
// this function is currently set to delete records 7+ days old every 60 minutes
// env: REMOVE_AFTER - golang duration parsed time for deleting records older than REMOVE_AFTER duration from now
// env: CLEANUP_INTERVAL - golang duration parsed time for checking old records routine
func Maintenance() {
dur := utils.Params.GetDuration("REMOVE_AFTER")
interval := utils.Params.GetDuration("CLEANUP_INTERVAL")
log.Infof("Database Cleanup runs every %s and will remove records older than %s", interval.String(), dur.String())
ticker := interval
for {
select {
case <-time.After(ticker):
deleteAfter := utils.Now().Add(-dur)
log.Infof("Deleting failures older than %s", deleteAfter.String())
deleteAllSince("failures", deleteAfter)
log.Infof("Deleting hits older than %s", deleteAfter.String())
deleteAllSince("hits", deleteAfter)
ticker = interval
}
}
}
// deleteAllSince will delete a specific table's records based on a time.
func deleteAllSince(table string, date time.Time) {
sql := fmt.Sprintf("DELETE FROM %s WHERE created_at < '%s'", table, database.FormatTime(date))
log.Info(sql)
if err := database.Exec(sql).Error(); err != nil {
log.WithField("query", sql).Errorln(err)
}
}