/
main.go
345 lines (295 loc) · 8.43 KB
/
main.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
334
335
336
337
338
339
340
341
342
343
344
345
package main
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httptrace"
"net/url"
"os"
"strconv"
"time"
"github.com/getsentry/sentry-go"
"golang.org/x/net/http2"
)
// CheckRequest is the payload for the service
type CheckRequest struct {
Timeout string `json:"timeout"`
URL string `json:"url"`
RedirectsToFollow int `json:"redirects_to_follow"`
VerifyCerts bool `json:"verify_certs"`
timeout time.Duration
}
// CheckResponse holds a single check's response
type CheckResponse struct {
StatusCode int `json:"status"`
Error string `json:"error"`
DNSLookup time.Duration `json:"dns_lookup"`
TCPConnection time.Duration `json:"tcp_connection"`
TLSHandshake time.Duration `json:"tls_handshake"`
ServerProcessing time.Duration `json:"server_processing"`
ContentTransfer time.Duration `json:"content_transfer"`
NameLookup time.Duration `json:"name_lookup"`
Connect time.Duration `json:"connect"`
PreTransfer time.Duration `json:"pre_transfer"`
StartTransfer time.Duration `json:"start_transfer"`
Total time.Duration `json:"total"`
}
var (
defaultTimeout time.Duration
defaultMaxRedirects int
authToken string
// Version holds the current version of watchman
Version string = "dev"
// Region is used if Watchman is deployed to GCP Cloud Run
Region string = "unknown"
)
func main() {
if os.Getenv("SENTRY_API") != "" {
err := sentry.Init(sentry.ClientOptions{
Dsn: os.Getenv("SENTRY_API"),
})
if err != nil {
log.Fatalf("sentry.Init: %s", err)
}
defer sentry.Flush(2 * time.Second)
}
if os.Getenv("_DEPLOY_REGION") != "" {
Region = os.Getenv("_REGION")
}
log.Printf("Version %s, Region %s", Version, Region)
if os.Getenv("AUTH_TOKEN") != "" {
authToken = os.Getenv("AUTH_TOKEN")
}
var err error
defaultTimeout = 100 * time.Millisecond
timeoutDuration := os.Getenv("TIMEOUT")
if timeoutDuration != "" {
defaultTimeout, err = time.ParseDuration(timeoutDuration)
if err != nil {
log.Fatalf("invalid default timeout %s", err.Error())
}
}
defaultMaxRedirects = 0 // no redirects by default
maxRedirects := os.Getenv("MAX_REDIRECTS")
if maxRedirects != "" {
defaultMaxRedirects, err = strconv.Atoi(maxRedirects)
if err != nil {
log.Fatalf("invalid max redirects %s", err.Error())
}
}
log.Printf("using %s as default timeout", defaultTimeout)
http.HandleFunc("/", handler)
http.HandleFunc("/_ping", pingHandler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("defaulting port to %s", port)
}
log.Printf("listening on port %s", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}
func pingHandler(w http.ResponseWriter, r *http.Request) {
log.Print("ping")
response := struct {
Version string
Region string
}{
Version: Version,
Region: Region,
}
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func handler(w http.ResponseWriter, r *http.Request) {
log.Print("request received")
if authToken != "" {
token := r.Header.Get("X-Token")
if token != authToken {
http.Error(w, "invalid token", http.StatusForbidden)
return
}
}
var request CheckRequest
err := json.NewDecoder(r.Body).Decode(&request)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var timeout time.Duration
if request.Timeout != "" {
timeout, err = time.ParseDuration(request.Timeout)
if err != nil {
http.Error(w, "bad timeout", http.StatusBadRequest)
return
}
request.timeout = timeout
} else {
request.timeout = defaultTimeout
}
if request.RedirectsToFollow == 0 {
request.RedirectsToFollow = defaultMaxRedirects
}
log.Printf("checking %v...", request)
ctx := context.Background()
response, err := check(ctx, request, 0)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func isRedirect(resp *http.Response) bool {
return resp.StatusCode > 299 && resp.StatusCode < 400
}
// readResponseBody consumes the body of the response.
// readResponseBody returns an informational message about the
// disposition of the response body's contents.
func readResponseBody(req *http.Request, resp *http.Response) error {
if isRedirect(resp) {
return nil
}
if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {
return err
}
return nil
}
func check(ctx context.Context, request CheckRequest, redirectsFollowed int) (*CheckResponse, error) {
url, err := url.Parse(request.URL)
if err != nil {
return nil, err
}
response := &CheckResponse{}
var t0, t1, t2, t3, t4, t5, t6 time.Time
trace := &httptrace.ClientTrace{
DNSStart: func(_ httptrace.DNSStartInfo) { t0 = time.Now() },
DNSDone: func(_ httptrace.DNSDoneInfo) { t1 = time.Now() },
ConnectStart: func(_, _ string) {
if t1.IsZero() {
// connecting to IP
t1 = time.Now()
}
},
ConnectDone: func(net, addr string, err error) {
if err != nil {
response.Error = err.Error()
}
t2 = time.Now()
},
GotConn: func(_ httptrace.GotConnInfo) { t3 = time.Now() },
GotFirstResponseByte: func() { t4 = time.Now() },
TLSHandshakeStart: func() { t5 = time.Now() },
TLSHandshakeDone: func(_ tls.ConnectionState, _ error) { t6 = time.Now() },
}
req, err := http.NewRequest("GET", url.String(), nil)
if err != nil {
response.Error = err.Error()
return response, nil
}
ctx, cancel := context.WithTimeout(httptrace.WithClientTrace(context.Background(), trace), request.timeout)
defer cancel()
req = req.WithContext(ctx)
tr := &http.Transport{
MaxIdleConns: 5,
IdleConnTimeout: 1 * time.Second,
TLSHandshakeTimeout: 1 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
if url.Scheme == "https" {
host, _, err := net.SplitHostPort(req.Host)
if err != nil {
host = req.Host
}
tr.TLSClientConfig = &tls.Config{
ServerName: host,
InsecureSkipVerify: request.VerifyCerts,
}
// Because we create a custom TLSClientConfig, we have to opt-in to HTTP/2.
// See https://github.com/golang/go/issues/14275
err = http2.ConfigureTransport(tr)
if err != nil {
return nil, err
}
}
client := &http.Client{
Transport: tr,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
// always refuse to follow redirects, check does that
// manually if required.
return http.ErrUseLastResponse
},
}
req.Header.Set("User-Agent", fmt.Sprintf("watchman-%s", Version))
req.Header.Set("X-Region", Region)
resp, err := client.Do(req)
if err != nil {
response.Error = err.Error()
return response, nil
}
_ = readResponseBody(req, resp)
resp.Body.Close()
response.StatusCode = resp.StatusCode
t7 := time.Now()
if t0.IsZero() {
// we skipped DNS
t0 = t1
}
switch url.Scheme {
case "https":
response.DNSLookup = t1.Sub(t0)
response.TCPConnection = t2.Sub(t1)
response.TLSHandshake = t6.Sub(t5)
response.ServerProcessing = t4.Sub(t3)
response.ContentTransfer = t7.Sub(t4)
response.NameLookup = t1.Sub(t0)
response.Connect = t2.Sub(t0)
response.PreTransfer = t3.Sub(t0)
response.StartTransfer = t4.Sub(t0)
response.Total = t7.Sub(t0)
case "http":
response.DNSLookup = t1.Sub(t0)
response.TCPConnection = t3.Sub(t1)
response.ServerProcessing = t4.Sub(t3)
response.ContentTransfer = t7.Sub(t4)
response.NameLookup = t1.Sub(t0)
response.Connect = t2.Sub(t0)
response.StartTransfer = t4.Sub(t0)
response.Total = t7.Sub(t0)
}
if isRedirect(resp) {
loc, err := resp.Location()
if err != nil {
if err == http.ErrNoLocation {
// 30x but no Location to follow, give up.
response.Error = "no location to follow"
return response, nil
}
return nil, err
}
redirectsFollowed++
if redirectsFollowed > request.RedirectsToFollow {
response.Error = fmt.Sprintf("maximum number of redirects (%d) followed", request.RedirectsToFollow)
return response, nil
}
log.Printf("redirecting to %s (%d of %d)", loc.String(), redirectsFollowed, request.RedirectsToFollow)
request.URL = loc.String()
return check(ctx, request, redirectsFollowed)
}
return response, nil
}