-
Notifications
You must be signed in to change notification settings - Fork 2
/
http.go
333 lines (306 loc) · 9.4 KB
/
http.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package healthcheck
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"html"
"io"
"net"
"net/http"
"os"
"regexp"
"time"
"github.com/pkg/errors"
"go.uber.org/zap"
"gopkg.in/tomb.v2"
)
// HTTPHealthcheckConfiguration defines an HTTP healthcheck configuration
type HTTPHealthcheckConfiguration struct {
Base `json:",inline" yaml:",inline"`
ValidStatus []uint `json:"valid-status" yaml:"valid-status"`
// can be an IP or a domain
Target string `json:"target"`
Method string `json:"method"`
Port uint `json:"port"`
Redirect bool `json:"redirect"`
Body string `json:"body,omitempty"`
Query map[string]string `json:"query,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Protocol Protocol `json:"protocol"`
Path string `json:"path,omitempty"`
SourceIP IP `json:"source-ip,omitempty" yaml:"source-ip,omitempty"`
BodyRegexp []Regexp `json:"body-regexp,omitempty" yaml:"body-regexp,omitempty"`
Insecure bool `json:"insecure"`
Timeout Duration `json:"timeout"`
Key string `json:"key,omitempty"`
Cert string `json:"cert,omitempty"`
Cacert string `json:"cacert,omitempty"`
}
// Validate validates the healthcheck configuration
func (config *HTTPHealthcheckConfiguration) Validate() error {
if config.Base.Name == "" {
return errors.New("The healthcheck name is missing")
}
if len(config.ValidStatus) == 0 {
return errors.New("At least one valid status code should be provided")
}
if config.Target == "" {
return errors.New("The healthcheck target is missing")
}
if config.Port == 0 {
return errors.New("The healthcheck port is missing")
}
if config.Timeout == 0 {
return errors.New("The healthcheck timeout is missing")
}
if config.Method != "" {
if config.Method != "GET" && config.Method != "POST" && config.Method != "PUT" && config.Method != "HEAD" && config.Method != "DELETE" {
return errors.New(fmt.Sprintf("The healthcheck method is invalid: %s", config.Method))
}
} else {
config.Method = "GET"
}
if !config.Base.OneOff {
if config.Base.Interval < Duration(2*time.Second) {
return errors.New("The healthcheck interval should be greater than 2 second")
}
if config.Base.Interval < config.Timeout {
return errors.New("The healthcheck interval should be greater than the timeout")
}
}
if !((config.Key != "" && config.Cert != "") ||
(config.Key == "" && config.Cert == "")) {
return errors.New("Invalid certificates")
}
return nil
}
// HTTPHealthcheck defines an HTTP healthcheck
type HTTPHealthcheck struct {
Logger *zap.Logger
Config *HTTPHealthcheckConfiguration
URL string
Tick *time.Ticker
t tomb.Tomb
transport *http.Transport
}
// buildURL build the target URL for the HTTP healthcheck, depending of its
// configuration
func (h *HTTPHealthcheck) buildURL() {
protocol := "http"
if h.Config.Protocol == HTTPS {
protocol = "https"
}
h.URL = fmt.Sprintf(
"%s://%s%s",
protocol,
net.JoinHostPort(h.Config.Target, fmt.Sprintf("%d", h.Config.Port)),
h.Config.Path)
}
// Summary returns an healthcheck summary
func (h *HTTPHealthcheck) Summary() string {
summary := ""
if h.Config.Base.Description != "" {
summary = fmt.Sprintf("HTTP healthcheck %s on %s:%d", h.Config.Base.Description, h.Config.Target, h.Config.Port)
} else {
summary = fmt.Sprintf("HTTP healthcheck on %s:%d", h.Config.Target, h.Config.Port)
}
return summary
}
// Initialize the healthcheck.
func (h *HTTPHealthcheck) Initialize() error {
h.buildURL()
dialer := net.Dialer{}
tlsConfig := &tls.Config{}
if h.Config.SourceIP != nil {
srcIP := net.IP(h.Config.SourceIP).String()
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:0", srcIP))
if err != nil {
return errors.Wrapf(err, "Fail to set the source IP %s", srcIP)
}
dialer = net.Dialer{
LocalAddr: addr,
}
}
if h.Config.Key != "" {
cert, err := tls.LoadX509KeyPair(h.Config.Cert, h.Config.Key)
if err != nil {
return errors.Wrapf(err, "Fail to load certificates")
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
if h.Config.Cacert != "" {
caCert, err := os.ReadFile(h.Config.Cacert)
if err != nil {
return errors.Wrapf(err, "Fail to load the ca certificate")
}
caCertPool := x509.NewCertPool()
result := caCertPool.AppendCertsFromPEM(caCert)
if !result {
return fmt.Errorf("fail to read ca certificate for healthcheck %s", h.Config.Base.Name)
}
tlsConfig.RootCAs = caCertPool
}
tlsConfig.InsecureSkipVerify = h.Config.Insecure
h.transport = &http.Transport{
DialContext: dialer.DialContext,
TLSClientConfig: tlsConfig,
}
return nil
}
// GetConfig get the config
func (h *HTTPHealthcheck) GetConfig() interface{} {
return h.Config
}
// Base get the base configuration
func (h *HTTPHealthcheck) Base() Base {
return h.Config.Base
}
// SetSource set the healthcheck source
func (h *HTTPHealthcheck) SetSource(source string) {
h.Config.Base.Source = source
}
// isSuccessful verifies if a healthcheck result is considered valid
// depending of the healthcheck configuration
func (h *HTTPHealthcheck) isSuccessful(response *http.Response) bool {
for _, s := range h.Config.ValidStatus {
if uint(response.StatusCode) == s {
return true
}
}
return false
}
// LogError logs an error with context
func (h *HTTPHealthcheck) LogError(err error, message string) {
h.Logger.Error(err.Error(),
zap.String("extra", message),
zap.String("target", h.Config.Target),
zap.Uint("port", h.Config.Port),
zap.String("name", h.Config.Base.Name))
}
// LogDebug logs a message with context
func (h *HTTPHealthcheck) LogDebug(message string) {
h.Logger.Debug(message,
zap.String("target", h.Config.Target),
zap.Uint("port", h.Config.Port),
zap.String("name", h.Config.Base.Name))
}
// LogInfo logs a message with context
func (h *HTTPHealthcheck) LogInfo(message string) {
h.Logger.Info(message,
zap.String("target", h.Config.Target),
zap.Uint("port", h.Config.Port),
zap.String("name", h.Config.Base.Name))
}
// Execute executes an healthcheck on the given target
func (h *HTTPHealthcheck) Execute() error {
h.LogDebug("start executing healthcheck")
ctx := h.t.Context(context.TODO())
body := bytes.NewBuffer([]byte(h.Config.Body))
req, err := http.NewRequest(h.Config.Method, h.URL, body)
if err != nil {
return errors.Wrapf(err, "fail to initialize HTTP request")
}
req.Header.Set("User-Agent", "Cabourotte")
for k, v := range h.Config.Headers {
req.Header.Set(k, v)
}
redirect := http.ErrUseLastResponse
if h.Config.Redirect {
redirect = nil
}
client := &http.Client{
Transport: h.transport,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return redirect
},
}
timeoutCtx, cancel := context.WithTimeout(ctx, time.Duration(h.Config.Timeout))
defer cancel()
req = req.WithContext(timeoutCtx)
if len(h.Config.Query) != 0 {
q := req.URL.Query()
for k, v := range h.Config.Query {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
}
response, err := client.Do(req)
if err != nil {
return errors.Wrapf(err, "HTTP request failed")
}
defer response.Body.Close()
responseBody, err := io.ReadAll(response.Body)
if err != nil {
return errors.Wrapf(err, "Fail to read request body")
}
responseBodyStr := string(responseBody)
maxMessageSize := 1000
message := responseBodyStr
if len(responseBodyStr) > maxMessageSize {
message = responseBodyStr[0:maxMessageSize]
}
if !h.isSuccessful(response) {
errorMsg := fmt.Sprintf("HTTP request failed: (status %d) => %s", response.StatusCode, html.EscapeString(message))
err = errors.New(errorMsg)
return err
}
for _, regex := range h.Config.BodyRegexp {
r := regexp.Regexp(regex)
if !r.MatchString(responseBodyStr) {
return fmt.Errorf("healthcheck body does not match regex %s: %s", r.String(), message)
}
}
return nil
}
// NewHTTPHealthcheck creates a HTTP healthcheck from a logger and a configuration
func NewHTTPHealthcheck(logger *zap.Logger, config *HTTPHealthcheckConfiguration) *HTTPHealthcheck {
return &HTTPHealthcheck{
Logger: logger,
Config: config,
}
}
// MarshalJSON marshal to json a dns healthcheck
func (h *HTTPHealthcheck) MarshalJSON() ([]byte, error) {
return json.Marshal(h.Config)
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *HTTPHealthcheckConfiguration) DeepCopyInto(out *HTTPHealthcheckConfiguration) {
*out = *in
in.Base.DeepCopyInto(&out.Base)
if in.ValidStatus != nil {
in, out := &in.ValidStatus, &out.ValidStatus
*out = make([]uint, len(*in))
copy(*out, *in)
}
if in.Headers != nil {
in, out := &in.Headers, &out.Headers
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
if in.SourceIP != nil {
in, out := &in.SourceIP, &out.SourceIP
*out = make(IP, len(*in))
copy(*out, *in)
}
if in.BodyRegexp != nil {
in, out := &in.BodyRegexp, &out.BodyRegexp
*out = make([]Regexp, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPHealthcheckConfiguration.
func (in *HTTPHealthcheckConfiguration) DeepCopy() *HTTPHealthcheckConfiguration {
if in == nil {
return nil
}
out := new(HTTPHealthcheckConfiguration)
in.DeepCopyInto(out)
return out
}