-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_check.go
94 lines (77 loc) · 1.82 KB
/
http_check.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
package deer
import (
"context"
"fmt"
"time"
)
// HTTPCheck defines http type check.
type HTTPCheck struct {
ref
// body
IntervalSec uint64 `hcl:"interval"`
TimeoutSec uint64 `hcl:"timeout"`
Addr string `hcl:"addr"`
Expectations []Expect `hcl:"expect,block"`
}
// Validate ensures correct values are set for http check.
func (h *HTTPCheck) Validate() error {
switch {
case h.TimeoutSec <= 0:
return fmt.Errorf("Timeout must be > 0")
case h.IntervalSec <= 0:
return fmt.Errorf("Interval must be > 0")
case len(h.Addr) == 0:
return fmt.Errorf("Addr cannot be empty")
case len(h.Expectations) == 0:
return fmt.Errorf("At least one expectation fot http check is required")
}
for _, expect := range h.Expectations {
if expect.Subject != "status" {
return fmt.Errorf("Invalid expectation subject")
}
}
return nil
}
// RunFn returns task function to run check.
func (h *HTTPCheck) RunFn(s Store) func() {
store := s
return func() {
now := time.Now()
req := Request{}
resp := req.Get(h.Addr, time.Duration(h.TimeoutSec)*time.Second)
success := h.Check(resp)
result := CheckResult{
MonitorID: h.ref.Monitor.ID,
ServiceID: h.ref.Service.ID,
At: now,
Success: success,
Trace: &resp.Trace,
Error: resp.Err,
}
if resp.Resp != nil {
result.StatusCode = resp.Resp.StatusCode
}
store.Save(context.Background(), &result)
}
}
// Check verifies if check is valid or not.
func (h *HTTPCheck) Check(resp *Response) bool {
if resp.Err != nil {
return false
}
success := true
for _, expect := range h.Expectations {
switch expect.Subject {
case "status":
status := resp.Resp.StatusCode
found := false
for _, s := range expect.Inclusion {
if s == status {
found = true
}
}
success = success && found
}
}
return success
}