statping/database/routines.go

53 lines
1.5 KiB
Go
Raw Permalink Normal View History

2020-02-26 05:38:03 +00:00
package database
import (
"fmt"
2020-03-09 18:17:55 +00:00
"github.com/statping/statping/utils"
2020-02-26 05:38:03 +00:00
"time"
2020-03-03 06:42:37 +00:00
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/postgres"
_ "github.com/mattn/go-sqlite3"
2020-02-26 05:38:03 +00:00
)
var (
log = utils.Log.WithField("type", "database")
2020-02-26 05:38:03 +00:00
)
// Maintenance will automatically delete old records from 'failures' and 'hits'
2020-02-26 05:38:03 +00:00
// this function is currently set to delete records 7+ days old every 60 minutes
2020-09-16 07:01:44 +00:00
// 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() {
2020-04-17 05:51:55 +00:00
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
2020-02-26 05:38:03 +00:00
for {
select {
case <-time.After(ticker):
deleteAfter := utils.Now().Add(-dur)
2020-03-03 06:42:37 +00:00
log.Infof("Deleting failures older than %s", deleteAfter.String())
deleteAllSince("failures", deleteAfter)
2020-02-26 05:38:03 +00:00
log.Infof("Deleting hits older than %s", deleteAfter.String())
deleteAllSince("hits", deleteAfter)
2020-02-26 05:38:03 +00:00
ticker = interval
}
2020-02-26 05:38:03 +00:00
}
2020-02-26 05:38:03 +00:00
}
// 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)
2020-02-26 05:38:03 +00:00
}
}