-
Notifications
You must be signed in to change notification settings - Fork 5
/
monitor.go
80 lines (72 loc) · 1.5 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
package main
import (
"net/http"
"net/url"
"time"
)
type monitor struct {
url string
cycle time.Duration
client http.Client
}
func newMonitor() monitor {
m := monitor{
url: urlFlag,
cycle: cycleFlag,
}
m.client = newHTTPClient(timeoutFlag, headerTimeoutFlag)
debug("* Monitor instance has been created: <url: %s, cycle: %v, timeout: %v, header timeout: %v>",
urlFlag, cycleFlag, timeoutFlag, headerTimeoutFlag)
return m
}
func (m *monitor) work() {
ticker := time.NewTicker(m.cycle)
for taskTime := range ticker.C {
go m.detect(taskTime)
}
}
func (m *monitor) detect(taskTime time.Time) {
debug("* Issuing a detection signal to %s ...", urlFlag)
resp, err := m.client.Get(m.url)
if err != nil {
urlErr := err.(*url.Error)
if urlErr.Timeout() {
// response timeout error
debug("* Result (timeout): %v", urlErr)
r := logRecord{
time: taskTime,
isTimeout: true,
err: urlErr,
}
logPush(r)
} else {
// other errors
debug("* Result (error): %v", urlErr)
r := logRecord{
time: taskTime,
err: urlErr,
}
logPush(r)
}
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
// non-2xx
debug("* Result (non-2xx): status code %d", resp.StatusCode)
r := logRecord{
time: taskTime,
statusCode: resp.StatusCode,
}
logPush(r)
} else {
// 200
debug("* Result (normal): status code %d", resp.StatusCode)
r := logRecord{
time: taskTime,
isNormal: true,
statusCode: 200,
}
logPush(r)
}
}