-
Notifications
You must be signed in to change notification settings - Fork 0
/
watchdog.go
72 lines (60 loc) · 1.36 KB
/
watchdog.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
/* Watchdog
*
* Copyright (c) 2017 Bryant Moscon
*
* Please see the LICENSE file for the terms and conditions
* associated with this software.
*
*/
package main
import (
"log"
"net/http"
"os"
"os/exec"
"syscall"
"time"
)
var services map[string]time.Time
func handler(w http.ResponseWriter, r *http.Request) {
service := r.URL.Query().Get("id")
log.Printf("Got data from service %s", service)
if service != "" {
services[service] = time.Now()
} else {
http.Error(w, "invalid data", http.StatusBadRequest)
}
}
func restart(name string) {
cmd := exec.Command(name)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
err := cmd.Start()
if err != nil {
log.Printf("Error starting service %s: %v", name, err)
}
}
func watcher(ticker *time.Ticker) {
for {
<-ticker.C
for name, timestamp := range services {
if time.Now().Sub(timestamp).Seconds() > 10 {
delete(services, name)
log.Printf("Service %s died - restarting", name)
go restart(name)
}
}
}
}
func main() {
services = make(map[string]time.Time)
f, err := os.OpenFile("watchdog.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatal("Cannot create logfile: ", err)
}
defer f.Close()
log.SetOutput(f)
ticker := time.NewTicker(5 * time.Second)
go watcher(ticker)
http.HandleFunc("/heartbeat", handler)
http.ListenAndServe(":8888", nil)
}