This repository has been archived by the owner on Mar 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathmonitor.go
116 lines (98 loc) · 2.45 KB
/
monitor.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
108
109
110
111
112
113
114
115
116
package pingd
import (
"sync"
"time"
)
// PingFunc is function signature for ping checks
type PingFunc func(host string) (up bool, err error)
// Monitor is the main structure that represent a monitored host
// Whenever a host goes up or down it notifies it on the corresponding channel
type Monitor struct {
running *sync.Mutex // monitor must run only once
lock *sync.Mutex // protects internal values
ping PingFunc
host string
down bool
failures int
failLimit int
interval time.Duration
stop bool
notifyCh chan<- HostStatus
}
// NewMonitor takes a host, an initial state, and the notification channels and returns a monitorable host structure
func NewMonitor(status HostStatus, ping PingFunc, notifyCh chan<- HostStatus) *Monitor {
h := Monitor{
ping: ping,
host: status.Host,
down: status.Down,
notifyCh: notifyCh,
running: &sync.Mutex{},
lock: &sync.Mutex{},
}
return &h
}
// Start begins the periodic pinging of the host
func (m *Monitor) Start(interval time.Duration, failLimit int) {
m.running.Lock()
defer m.running.Unlock()
defer m.lock.Unlock()
m.lock.Lock()
m.interval = interval
m.failLimit = failLimit
m.stop = false
m.lock.Unlock()
ticker := time.NewTicker(interval)
defer ticker.Stop()
for _ = range ticker.C {
// log.Println("tick")
m.lock.Lock()
if m.stop {
return
}
m.lock.Unlock()
if up, err := m.ping(m.host); up {
// log.Println(m.host.Host + " pong")
m.markUp()
} else {
// log.Println(m.host.Host + " failed")
m.markDown(err)
}
}
}
// Stop stops pinging the host
func (m *Monitor) Stop() {
m.lock.Lock()
defer m.lock.Unlock()
m.stop = true
}
// markUp resets the failure count and the host status, then sends a channel notification that the host is up.
func (m *Monitor) markUp() {
m.lock.Lock()
defer m.lock.Unlock()
if !m.down {
m.failures = 0
return
}
m.failures--
if m.failures > 0 {
return
}
m.down = false
m.notifyCh <- HostStatus{Host: m.host, Down: m.down}
}
// markDown does nothing if the host is already down. If it's up, in increases the failure count
// changes the status to down and then sends a channel notification that the host is down.
func (m *Monitor) markDown(err error) {
m.lock.Lock()
defer m.lock.Unlock()
if m.down {
m.failures = m.failLimit
return
}
m.failures++
if m.failures < m.failLimit {
return
}
m.down = true
m.notifyCh <- HostStatus{Host: m.host, Down: m.down, Reason: err}
}