-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
227 lines (185 loc) · 5.16 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
package http
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/csmith/goplum"
"github.com/nelkinda/health-go"
)
var client = http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
ForceAttemptHTTP2: true,
DisableKeepAlives: true,
ExpectContinueTimeout: 1 * time.Second,
},
}
type Plugin struct{}
func (p Plugin) Alert(kind string) goplum.Alert {
switch kind {
case "webhook":
return WebHookAlert{}
default:
return nil
}
}
func (p Plugin) Check(kind string) goplum.Check {
switch kind {
case "get":
return GetCheck{
ContentExpected: true,
MinStatusCode: 100,
MaxStatusCode: 399,
}
case "healthcheck":
return HealthCheck{}
default:
return nil
}
}
type Credentials struct {
Username string
Password string
}
type BaseCheck struct {
Url string
Auth Credentials
}
type GetCheck struct {
BaseCheck `config:",squash"`
Content string
ContentExpected bool `config:"content_expected"`
CertificateValidity time.Duration `config:"certificate_validity"`
MinStatusCode int `config:"min_status_code"`
MaxStatusCode int `config:"max_status_code"`
}
func (g GetCheck) Execute(ctx context.Context) goplum.Result {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, g.Url, http.NoBody)
if err != nil {
goplum.FailingResult("Error building request: %v", err)
}
if len(g.Auth.Username) > 0 || len(g.Auth.Password) > 0 {
req.SetBasicAuth(g.Auth.Username, g.Auth.Password)
}
r, err := client.Do(req)
if err != nil {
return goplum.FailingResult("Error making request: %v", err)
} else if r.StatusCode < g.MinStatusCode || r.StatusCode > g.MaxStatusCode {
return goplum.FailingResult("Bad status code: %d", r.StatusCode)
}
defer r.Body.Close()
if len(g.Content) > 0 {
content, err := io.ReadAll(r.Body)
if err != nil {
return goplum.FailingResult("Error reading response body: %v", err)
}
// TODO: It would be nice to scan the body instead of having to read it all into memory
// TODO: Add options around case sensitivity/consider allowing regexp
found := strings.Contains(string(content), g.Content)
if !found && g.ContentExpected {
return goplum.FailingResult("Body does not contain '%s'", g.Content)
} else if found && !g.ContentExpected {
return goplum.FailingResult("Body contains '%s'", g.Content)
}
}
if g.CertificateValidity > 0 {
if r.TLS == nil {
return goplum.FailingResult("Connection did not use TLS")
}
remaining := time.Until(r.TLS.PeerCertificates[0].NotAfter)
if remaining < g.CertificateValidity {
return goplum.FailingResult("Certificate expires in %s", remaining)
}
}
return goplum.GoodResult()
}
func (g GetCheck) Validate() error {
if len(g.Url) == 0 {
return fmt.Errorf("missing required argument: url")
}
return nil
}
type HealthCheck struct {
BaseCheck `config:",squash"`
CheckComponents bool `config:"check_components"`
}
func (h HealthCheck) Execute(ctx context.Context) goplum.Result {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.Url, http.NoBody)
if err != nil {
goplum.FailingResult("Error building request: %v", err)
}
if len(h.Auth.Username) > 0 || len(h.Auth.Password) > 0 {
req.SetBasicAuth(h.Auth.Username, h.Auth.Password)
}
r, err := client.Do(req)
if err != nil {
return goplum.FailingResult("Error making request: %v", err)
}
defer r.Body.Close()
res := &health.Health{}
if err := json.NewDecoder(r.Body).Decode(res); err != nil {
return goplum.FailingResult("Error decoding response: %v", err)
}
status := h.convert(res.Status)
detail := res.Output
if status == goplum.StateGood && h.CheckComponents {
for name, checks := range res.Checks {
for i := range checks {
check := checks[i]
checkStatus := h.convert(check.Status)
if checkStatus > status {
status = checkStatus
detail = fmt.Sprintf("component %s: %s", name, check.Output)
}
}
}
}
return goplum.Result{State: status, Detail: detail, Time: time.Now()}
}
func (h HealthCheck) Validate() error {
if len(h.Url) == 0 {
return fmt.Errorf("missing required argument: url")
}
return nil
}
func (h HealthCheck) convert(status health.Status) goplum.CheckState {
lower := strings.ToLower(string(status))
if lower == "pass" || lower == "ok" || lower == "up" {
return goplum.StateGood
} else if lower == "fail" || lower == "error" || lower == "down" {
return goplum.StateFailing
} else if lower == "warn" {
return goplum.StateGood // TODO: Change when goplum implements warnings
} else {
return goplum.StateIndeterminate
}
}
type WebHookAlert struct {
Url string
}
func (w WebHookAlert) Send(details goplum.AlertDetails) error {
b, err := json.Marshal(details)
if err != nil {
return err
}
res, err := client.Post(w.Url, "application/json", bytes.NewReader(b))
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode >= 400 {
return fmt.Errorf("bad response from webhook: HTTP %d", res.StatusCode)
}
return nil
}
func (w WebHookAlert) Validate() error {
if len(w.Url) == 0 {
return fmt.Errorf("missing required argument: url")
}
return nil
}