-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttpchk.go
More file actions
293 lines (250 loc) · 6.43 KB
/
Copy pathhttpchk.go
File metadata and controls
293 lines (250 loc) · 6.43 KB
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
package main
import (
"encoding/csv"
"fmt"
"html/template"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"slices"
"strconv"
"strings"
"time"
"github.com/gorilla/handlers"
)
var checkTemplate = template.Must(template.ParseFiles("templates/check.html"))
func main() {
mux := buildMux()
port := os.Getenv("PORT")
addr := "0.0.0.0:" + port
loggedRouter := handlers.CombinedLoggingHandler(os.Stdout, mux)
log.Fatal(http.ListenAndServe(addr, loggedRouter))
}
func buildMux() *http.ServeMux {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("./static")))
mux.HandleFunc("/up", upHandler)
mux.HandleFunc("/check", checkAndReportHTML)
mux.HandleFunc("/check.txt", checkAndReport)
return mux
}
func readChecksCSV(r io.ReadCloser) []check {
csvReader := csv.NewReader(r)
csvReader.TrimLeadingSpace = true
csvReader.LazyQuotes = true
var result []check
for {
fields, err := csvReader.Read()
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
check := checkFromCSVFields(fields)
// Ignore invalid URLs (like in the header row)
if isURL(check.URL) {
result = append(result, check)
}
}
fmt.Printf("Read %d checks from CSV.\n", len(result))
return result
}
func checkFromCSVFields(fields []string) check {
return check{
ID: fields[0],
URL: fields[1],
ExpectedText: fields[2],
}
}
func isURL(s string) bool {
hasHttpPrefix := strings.HasPrefix(s, "http://") || strings.HasPrefix(s, "https://")
if !hasHttpPrefix {
return false
}
_, err := url.Parse(s)
return err == nil
}
// CheckResult contains an array of checks and helper function to return
// - the number of passed checks
// - allChecksOk is true if all checks passed
// - the slowest check
// - list of failed checks
type CheckResult struct {
Checks []check
}
func (cr *CheckResult) SortChecks() {
// sort Checks by ID (ascending)
slices.SortFunc(cr.Checks, func(a, b check) int {
return strings.Compare(strings.ToLower(a.ID), strings.ToLower(b.ID))
})
}
func (cr *CheckResult) PassedChecks() int {
passedChecks := 0
for _, check := range cr.Checks {
if check.OK {
passedChecks++
}
}
return passedChecks
}
func (cr *CheckResult) AllChecksOk() bool {
return cr.PassedChecks() == len(cr.Checks)
}
func (cr *CheckResult) SlowestCheck() *check {
slowestCheck := cr.Checks[0]
for _, check := range cr.Checks {
if check.runtime > slowestCheck.runtime {
slowestCheck = check
}
}
return &slowestCheck
}
func (cr *CheckResult) FailedChecks() []check {
var failedChecks []check
for _, check := range cr.Checks {
if !check.OK {
failedChecks = append(failedChecks, check)
}
}
return failedChecks
}
func runAllChecks(checks []check) CheckResult {
channel := make(chan check)
for _, check := range checks {
go runSingleCheck(check, channel)
}
result := make([]check, len(checks))
for i := 0; i < len(checks); i++ {
check := <-channel
result[i] = check
}
return CheckResult{Checks: result}
}
type ResultPageData struct {
ErrorMessage string
Checks []check
PassedChecks int
TotalChecks int
}
func checkAndReportHTML(res http.ResponseWriter, r *http.Request) {
checkURL := r.FormValue("checks")
if checkURL == "" {
errorMessage := "ERROR: checks parameter missing\n"
checkTemplate.Execute(res, ResultPageData{ErrorMessage: errorMessage})
return
}
resp, err := http.Get(checkURL)
if err != nil {
errorMessage := "ERROR: Could not fetch checks CSV file\n"
checkTemplate.Execute(res, ResultPageData{ErrorMessage: errorMessage})
return
}
defer resp.Body.Close()
checks := readChecksCSV(resp.Body)
result := runAllChecks(checks)
result.SortChecks()
page := ResultPageData{
Checks: result.Checks,
PassedChecks: result.PassedChecks(),
TotalChecks: len(checks),
}
err = checkTemplate.Execute(res, page)
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
}
}
func checkAndReport(res http.ResponseWriter, r *http.Request) {
checkURL := r.FormValue("checks")
if checkURL == "" {
errorMessage := "ERROR: checks parameter missing\n"
http.Error(res, errorMessage, http.StatusNotFound)
return
}
resp, err := http.Get(checkURL)
if err != nil {
errorMessage := "ERROR: Could not fetch checks CSV file\n"
http.Error(res, errorMessage, http.StatusServiceUnavailable)
return
}
defer resp.Body.Close()
checks := readChecksCSV(resp.Body)
result := runAllChecks(checks)
allChecksOk := result.AllChecksOk()
slowestCheck := result.SlowestCheck()
if allChecksOk {
io.WriteString(res, fmt.Sprintf("%d checks OK\n", len(checks)))
io.WriteString(res, "\n")
message := fmt.Sprintf("Slowest %s:%v", slowestCheck.ID, slowestCheck.runtime)
io.WriteString(res, message)
} else {
failures := result.FailedChecks()
// Concatenate all URLs of failed checks
var failedURLs []string
for _, check := range failures {
failedURLs = append(failedURLs, check.URL)
}
errorMessage := "ERROR: \n" + strings.Join(failedURLs, "\n")
http.Error(res, errorMessage, http.StatusServiceUnavailable)
}
}
func contains(ints []string, n int) bool {
for _, str := range ints {
i, _ := strconv.Atoi(str)
if i == n {
return true
}
}
return false
}
type check struct {
ID string
URL string
ExpectedText string
OK bool
runtime time.Duration
}
func timeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) {
return func(netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, cTimeout)
if err != nil {
return nil, err
}
conn.SetDeadline(time.Now().Add(rwTimeout))
return conn, nil
}
}
func runSingleCheck(check check, channel chan check) {
check.OK = false
start := time.Now()
check.runtime = 0
timeout := time.Duration(29 * time.Second)
transport := http.Transport{
Dial: timeoutDialer(timeout, timeout),
}
client := http.Client{
Transport: &transport,
}
resp, err := client.Get(check.URL)
if err == nil && resp.StatusCode == 200 {
if check.ExpectedText == "" {
check.OK = true
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
bodyText := string(body)
if (err == nil) && strings.Contains(bodyText, check.ExpectedText) {
check.OK = true
}
}
check.runtime = time.Since(start)
fmt.Printf("Check completed: %v+\n", check)
channel <- check
}
// /up is a simple health check endpoint (used by kamal deploy)
func upHandler(res http.ResponseWriter, r *http.Request) {
io.WriteString(res, "OK\n")
}