2024-04-21 21:46:40 -04:00
|
|
|
package scheduler
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2024-04-22 00:14:58 -04:00
|
|
|
"log"
|
|
|
|
"strings"
|
2024-04-21 21:46:40 -04:00
|
|
|
"time"
|
|
|
|
|
2024-04-22 00:14:58 -04:00
|
|
|
"git.simponic.xyz/simponic/backup-notify/args"
|
2024-04-21 21:46:40 -04:00
|
|
|
"git.simponic.xyz/simponic/backup-notify/database"
|
2024-04-22 00:14:58 -04:00
|
|
|
"git.simponic.xyz/simponic/backup-notify/ntfy"
|
2024-04-21 21:46:40 -04:00
|
|
|
"github.com/go-co-op/gocron"
|
|
|
|
)
|
|
|
|
|
2024-04-22 00:14:58 -04:00
|
|
|
func contains(hostnames []string, hostname string) bool {
|
|
|
|
for _, h := range hostnames {
|
|
|
|
if h == hostname {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func StartScheduler(dbConn *sql.DB, argv *args.Arguments) {
|
2024-04-21 21:46:40 -04:00
|
|
|
scheduler := gocron.NewScheduler(time.Local)
|
2024-04-22 00:14:58 -04:00
|
|
|
|
2024-04-21 21:49:41 -04:00
|
|
|
scheduler.Every(1).Hour().Do(func() {
|
2024-04-22 00:14:58 -04:00
|
|
|
err := database.DeleteOldBackups(dbConn, 31)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("could not delete old backups:", err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
scheduler.Every(1).Day().Do(func() {
|
|
|
|
hostnames, err := database.BackupedHostnamesInTheLastDay(dbConn)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("could not list hostnames that have been backed up in the last day:", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
allHostnames, err := database.ReceivedHostnames(dbConn)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("could not list received hostnames:", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
failedHostnames := []string{}
|
|
|
|
for _, hostname := range allHostnames {
|
|
|
|
if !contains(hostnames, hostname) {
|
|
|
|
failedHostnames = append(failedHostnames, hostname)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(failedHostnames) > 0 {
|
|
|
|
msg := "the following hostnames have not been backed up in the last day:\n" + strings.Join(failedHostnames, ", ")
|
|
|
|
log.Println(msg)
|
|
|
|
|
|
|
|
err := ntfy.SendMessage(msg, argv.NtfyEndpoint, argv.NtfyAlertTopics)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("could not send alert:", err)
|
|
|
|
}
|
|
|
|
}
|
2024-04-21 21:46:40 -04:00
|
|
|
})
|
2024-04-22 00:14:58 -04:00
|
|
|
|
2024-04-21 21:46:40 -04:00
|
|
|
scheduler.StartAsync()
|
|
|
|
}
|