go-watchdog/cmd/watchdog/watchdog.go

121 lines
2.1 KiB
Go
Raw Normal View History

2019-06-21 06:53:02 +00:00
//go:generate go run -mod=vendor git.rootprojects.org/root/go-gitver
// Watchdog Binary
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
2019-06-27 08:54:51 +00:00
"git.rootprojects.org/root/watchdog.go"
2019-06-21 06:53:02 +00:00
)
2019-06-21 07:03:15 +00:00
var GitRev, GitVersion, GitTimestamp string
2019-06-21 06:53:02 +00:00
func usage() {
fmt.Println("Usage: watchdog -c config.json")
}
func main() {
for i := range os.Args {
switch {
case strings.HasSuffix(os.Args[i], "version"):
fmt.Println(GitTimestamp)
fmt.Println(GitVersion)
fmt.Println(GitRev)
os.Exit(0)
case strings.HasSuffix(os.Args[i], "help"):
usage()
os.Exit(0)
2019-06-27 08:54:51 +00:00
case os.Args[i] == "install":
args := []string{}
if len(os.Args) > i+1 {
args = os.Args[i+1:]
}
install(os.Args[0], args)
os.Exit(0)
2019-06-21 06:53:02 +00:00
}
}
if 3 != len(os.Args) {
usage()
os.Exit(1)
return
}
if "-c" != os.Args[1] {
usage()
os.Exit(1)
return
}
filename := os.Args[2]
f, err := os.Open(filename)
if nil != err {
log.Fatal(err)
return
}
configFile, err := ioutil.ReadAll(f)
if nil != err {
log.Fatal(err)
return
}
config := &watchdog.Config{}
err = json.Unmarshal(configFile, config)
if nil != err {
log.Fatal(err)
return
}
//fmt.Printf("%#v\n", config)
done := make(chan struct{}, 1)
2019-06-25 02:00:01 +00:00
allWebhooks := make(map[string]watchdog.Webhook)
2019-06-21 06:53:02 +00:00
for i := range config.Webhooks {
h := config.Webhooks[i]
allWebhooks[h.Name] = h
}
logQueue := make(chan string, 10)
go logger(logQueue)
for i := range config.Watches {
c := config.Watches[i]
logQueue <- fmt.Sprintf("Watching '%s'", c.Name)
go func(c watchdog.ConfigWatch) {
d := watchdog.New(&watchdog.Dog{
Name: c.Name,
CheckURL: c.URL,
Keywords: c.Keywords,
Recover: c.RecoverScript,
Webhooks: c.Webhooks,
AllWebhooks: allWebhooks,
Logger: logQueue,
})
d.Watch()
}(config.Watches[i])
}
if 0 == len(config.Watches) {
log.Fatal("Nothing to watch")
return
}
<-done
}
// This is so that the log messages don't trample
// over each other when they happen simultaneously.
func logger(msgs chan string) {
for {
msg := <-msgs
log.Println(msg)
}
}