-
Notifications
You must be signed in to change notification settings - Fork 17
/
dead_mans_switch.go
107 lines (90 loc) · 2.12 KB
/
dead_mans_switch.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/prometheus/client_golang/prometheus"
)
var (
heatbeatSuccess = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "dead_mans_switch_heatbeat_success",
Help: "The number of heatbeat receive from webhook.",
},
)
failedNotifications = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "dead_mans_switch_notifications_failed",
Help: "The number of failed notifications.",
},
)
failedEvaluatePayload = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "dead_mans_switch_evaluate_failed",
Help: "The timestamps of failed evaluate.",
},
)
)
func init() {
prometheus.MustRegister(
heatbeatSuccess,
failedNotifications,
failedEvaluatePayload,
)
}
type DeadmansSwitch struct {
message <-chan string
interval time.Duration
ticker *time.Ticker
closer chan struct{}
notifier func(summary, detail string) error
}
func NewDeadMansSwitch(message <-chan string, interval time.Duration, notifier func(summary, detail string) error) *DeadmansSwitch {
return &DeadmansSwitch{
message: message,
interval: interval,
notifier: notifier,
closer: make(chan struct{}),
}
}
func (d *DeadmansSwitch) Run() error {
log.Println("starting dead mans switch")
d.ticker = time.NewTicker(d.interval)
skip := false
for {
select {
case <-d.ticker.C:
if !skip {
d.Notify("WatchdogDown", "alerting pipeline is unhealthy")
} else {
log.Println("received Deadman's Switch alert, skip notify")
}
skip = false
case msg := <-d.message:
if msg != "" {
failedEvaluatePayload.SetToCurrentTime()
} else {
// message is null, heatbeat success, just skip current check
failedEvaluatePayload.Set(0)
heatbeatSuccess.Inc()
skip = true
}
case <-d.closer:
break
}
}
}
// Notify send special message to notifier
func (d *DeadmansSwitch) Notify(summary, detail string) {
if err := d.notifier(summary, detail); err != nil {
failedNotifications.Inc()
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
}
}
func (d *DeadmansSwitch) Stop() {
if d.ticker != nil {
d.ticker.Stop()
}
d.closer <- struct{}{}
}