forked from sourcegraph/checkup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpchecker.go
180 lines (158 loc) · 5.04 KB
/
httpchecker.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package checkup
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
)
// HTTPChecker implements a Checker for HTTP endpoints.
type HTTPChecker struct {
// Name is the name of the endpoint.
Name string `json:"endpoint_name"`
// URL is the URL of the endpoint.
URL string `json:"endpoint_url"`
// UpStatus is the HTTP status code expected by
// a healthy endpoint. Default is http.StatusOK.
UpStatus int `json:"up_status,omitempty"`
// ThresholdRTT is the maximum round trip time to
// allow for a healthy endpoint. If non-zero and a
// request takes longer than ThresholdRTT, the
// endpoint will be considered unhealthy. Note that
// this duration includes any in-between network
// latency.
ThresholdRTT time.Duration `json:"threshold_rtt,omitempty"`
// MustContain is a string that the response body
// must contain in order to be considered up.
// NOTE: If set, the entire response body will
// be consumed, which has the potential of using
// lots of memory and slowing down checks if the
// response body is large.
MustContain string `json:"must_contain,omitempty"`
// MustNotContain is a string that the response
// body must NOT contain in order to be considered
// up. If both MustContain and MustNotContain are
// set, they are and-ed together. NOTE: If set,
// the entire response body will be consumed, which
// has the potential of using lots of memory and
// slowing down checks if the response body is large.
MustNotContain string `json:"must_not_contain,omitempty"`
// Attempts is how many requests the client will
// make to the endpoint in a single check.
Attempts int `json:"attempts,omitempty"`
// Client is the http.Client with which to make
// requests. If not set, DefaultHTTPClient is
// used.
Client *http.Client `json:"-"`
}
// Check performs checks using c according to its configuration.
// An error is only returned if there is a configuration error.
func (c HTTPChecker) Check() (Result, error) {
if c.Attempts < 1 {
c.Attempts = 1
}
if c.Client == nil {
c.Client = DefaultHTTPClient
}
if c.UpStatus == 0 {
c.UpStatus = http.StatusOK
}
result := Result{Title: c.Name, Endpoint: c.URL, Timestamp: Timestamp()}
req, err := http.NewRequest("GET", c.URL, nil)
if err != nil {
return result, err
}
result.Times = c.doChecks(req)
return c.conclude(result), nil
}
// doChecks executes req using c.Client and returns each attempt.
func (c HTTPChecker) doChecks(req *http.Request) Attempts {
checks := make(Attempts, c.Attempts)
for i := 0; i < c.Attempts; i++ {
start := time.Now()
resp, err := c.Client.Do(req)
checks[i].RTT = time.Since(start)
if err != nil {
checks[i].Error = err.Error()
continue
}
err = c.checkDown(resp)
if err != nil {
checks[i].Error = err.Error()
}
resp.Body.Close()
}
return checks
}
// conclude takes the data in result from the attempts and
// computes remaining values needed to fill out the result.
// It detects degraded (high-latency) responses and makes
// the conclusion about the result's status.
func (c HTTPChecker) conclude(result Result) Result {
result.ThresholdRTT = c.ThresholdRTT
// Check errors (down)
for i := range result.Times {
if result.Times[i].Error != "" {
result.Down = true
return result
}
}
// Check round trip time (degraded)
if c.ThresholdRTT > 0 {
stats := result.ComputeStats()
if stats.Median > c.ThresholdRTT {
result.Notice = fmt.Sprintf("median round trip time exceeded threshold (%s)", c.ThresholdRTT)
result.Degraded = true
return result
}
}
result.Healthy = true
return result
}
// checkDown checks whether the endpoint is down based on resp and
// the configuration of c. It returns a non-nil error if down.
// Note that it does not check for degraded response.
func (c HTTPChecker) checkDown(resp *http.Response) error {
// Check status code
if resp.StatusCode != c.UpStatus {
return fmt.Errorf("response status %s", resp.Status)
}
// Check response body
if c.MustContain == "" && c.MustNotContain == "" {
return nil
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("reading response body: %v", err)
}
body := string(bodyBytes)
if c.MustContain != "" && !strings.Contains(body, c.MustContain) {
return fmt.Errorf("response does not contain '%s'", c.MustContain)
}
if c.MustNotContain != "" && strings.Contains(body, c.MustNotContain) {
return fmt.Errorf("response contains '%s'", c.MustNotContain)
}
return nil
}
// DefaultHTTPClient is used when no other http.Client
// is specified on a HTTPChecker.
var DefaultHTTPClient = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 0,
}).Dial,
TLSHandshakeTimeout: 5 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
MaxIdleConnsPerHost: 1,
DisableCompression: true,
DisableKeepAlives: true,
ResponseHeaderTimeout: 5 * time.Second,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return fmt.Errorf("no redirects allowed")
},
Timeout: 10 * time.Second,
}