forked from minio/sidekick
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp-tracer.go
497 lines (447 loc) · 14.4 KB
/
http-tracer.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// Copyright (c) 2020 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/minio/pkg/console"
)
// recordRequest - records the first recLen bytes
// of a given io.Reader
type recordRequest struct {
// Data source to record
io.Reader
// Response body should be logged
logBody bool
// Internal recording buffer
buf bytes.Buffer
// request headers
headers http.Header
// total bytes read including header size
bytesRead int
}
const timeFormat = "15:04:05.000"
func (r *recordRequest) Read(p []byte) (n int, err error) {
n, err = r.Reader.Read(p)
r.bytesRead += n
if r.logBody {
r.buf.Write(p[:n])
}
if err != nil {
return n, err
}
return n, err
}
func (r *recordRequest) Size() int {
sz := r.bytesRead
for k, v := range r.headers {
sz += len(k) + len(v)
}
return sz
}
// ResponseWriter - is a wrapper to trap the http response status code.
type ResponseWriter struct {
http.ResponseWriter
StatusCode int
// Response body should be logged
LogBody bool
TimeToFirstByte time.Duration
StartTime time.Time
// number of bytes written
bytesWritten int
// Internal recording buffer
headers bytes.Buffer
body bytes.Buffer
// Indicate if headers are written in the log
headersLogged bool
}
// NewResponseWriter - returns a wrapped response writer to trap
// http status codes for auditiing purposes.
func NewResponseWriter(w http.ResponseWriter) *ResponseWriter {
return &ResponseWriter{
ResponseWriter: w,
StatusCode: http.StatusOK,
StartTime: time.Now().UTC(),
}
}
func (lrw *ResponseWriter) Write(p []byte) (int, error) {
n, err := lrw.ResponseWriter.Write(p)
lrw.bytesWritten += n
if lrw.TimeToFirstByte == 0 {
lrw.TimeToFirstByte = time.Now().UTC().Sub(lrw.StartTime)
}
if !lrw.headersLogged {
// We assume the response code to be '200 OK' when WriteHeader() is not called,
// that way following Golang HTTP response behavior.
lrw.writeHeaders(&lrw.headers, http.StatusOK, lrw.Header())
lrw.headersLogged = true
}
if lrw.StatusCode >= http.StatusBadRequest || lrw.LogBody {
// Always logging error responses.
lrw.body.Write(p)
}
if err != nil {
return n, err
}
return n, err
}
// Write the headers into the given buffer
func (lrw *ResponseWriter) writeHeaders(w io.Writer, statusCode int, headers http.Header) {
n, _ := fmt.Fprintf(w, "%d %s\n", statusCode, http.StatusText(statusCode))
lrw.bytesWritten += n
for k, v := range headers {
n, _ := fmt.Fprintf(w, "%s: %s\n", k, v[0])
lrw.bytesWritten += n
}
}
// BodyPlaceHolder returns a dummy body placeholder
var BodyPlaceHolder = []byte("<BODY>")
// Body - Return response body.
func (lrw *ResponseWriter) Body() []byte {
// If there was an error response or body logging is enabled
// then we return the body contents
if lrw.StatusCode >= http.StatusBadRequest || lrw.LogBody {
return lrw.body.Bytes()
}
// ... otherwise we return the <BODY> place holder
return BodyPlaceHolder
}
// WriteHeader - writes http status code
func (lrw *ResponseWriter) WriteHeader(code int) {
lrw.StatusCode = code
if !lrw.headersLogged {
lrw.writeHeaders(&lrw.headers, code, lrw.ResponseWriter.Header())
lrw.headersLogged = true
}
lrw.ResponseWriter.WriteHeader(code)
}
// Flush - Calls the underlying Flush.
func (lrw *ResponseWriter) Flush() {
lrw.ResponseWriter.(http.Flusher).Flush()
}
// Size - reutrns the number of bytes written
func (lrw *ResponseWriter) Size() int {
return lrw.bytesWritten
}
// Return the bytes that were recorded.
func (r *recordRequest) Data() []byte {
// If body logging is enabled then we return the actual body
if r.logBody {
return r.buf.Bytes()
}
// ... otherwise we return <BODY> placeholder
return BodyPlaceHolder
}
func httpInternalTrace(req *http.Request, resp *http.Response, reqTime, respTime time.Time, backend *Backend) {
ti := InternalTrace(req, resp, reqTime, respTime)
doTrace(ti, backend)
}
// InternalTrace returns trace for sidekick http requests
func InternalTrace(req *http.Request, resp *http.Response, reqTime, respTime time.Time) TraceInfo {
t := TraceInfo{}
t.NodeName = req.Host
if host, _, err := net.SplitHostPort(t.NodeName); err == nil {
t.NodeName = host
}
reqHeaders := req.Header.Clone()
reqHeaders.Set("Host", req.Host)
if len(req.TransferEncoding) == 0 {
reqHeaders.Set("Content-Length", strconv.Itoa(int(req.ContentLength)))
}
for _, enc := range req.TransferEncoding {
reqHeaders.Add("Transfer-Encoding", enc)
}
reqBodyRecorder := &recordRequest{Reader: req.Body, logBody: false, headers: reqHeaders}
req.Body = ioutil.NopCloser(reqBodyRecorder)
respBodyStr := "<BODY>"
if resp.Body != nil {
respBody, _ := ioutil.ReadAll(resp.Body)
respBodyStr = string(respBody)
}
rq := traceRequestInfo{
Time: reqTime,
Method: req.Method,
Path: req.URL.Path,
RawQuery: req.URL.RawQuery,
Client: getSourceIP(req),
Headers: reqHeaders,
Body: string(reqBodyRecorder.Data()),
}
rs := traceResponseInfo{
Time: respTime,
Headers: resp.Header.Clone(),
StatusCode: resp.StatusCode,
Body: respBodyStr,
}
if rs.StatusCode == 0 {
rs.StatusCode = http.StatusOK
}
t.ReqInfo = rq
t.RespInfo = rs
t.CallStats = traceCallStats{
Latency: rs.Time.Sub(rq.Time),
Rx: reqBodyRecorder.Size(),
Tx: len(rs.Body),
}
t.Type = TraceMsgType
if globalDebugEnabled {
t.Type = DebugMsgType
}
return t
}
// Trace gets trace of http request
func Trace(f http.HandlerFunc, logBody bool, w http.ResponseWriter, r *http.Request, endpoint string) TraceInfo {
// Setup a http request body recorder
reqHeaders := r.Header.Clone()
reqHeaders.Set("Host", r.Host)
if len(r.TransferEncoding) == 0 {
reqHeaders.Set("Content-Length", strconv.Itoa(int(r.ContentLength)))
}
for _, enc := range r.TransferEncoding {
reqHeaders.Add("Transfer-Encoding", enc)
}
var reqBodyRecorder *recordRequest
t := TraceInfo{}
reqBodyRecorder = &recordRequest{Reader: r.Body, logBody: logBody, headers: reqHeaders}
r.Body = ioutil.NopCloser(reqBodyRecorder)
t.NodeName = r.Host
if host, _, err := net.SplitHostPort(t.NodeName); err == nil {
t.NodeName = host
}
rw := NewResponseWriter(w)
rw.LogBody = logBody
f(rw, r)
rq := traceRequestInfo{
Time: time.Now().UTC(),
Method: r.Method,
Path: r.URL.Path,
RawQuery: r.URL.RawQuery,
Client: getSourceIP(r),
Headers: reqHeaders,
Body: string(reqBodyRecorder.Data()),
}
rs := traceResponseInfo{
Time: time.Now().UTC(),
Headers: rw.Header().Clone(),
StatusCode: rw.StatusCode,
Body: string(rw.Body()),
}
if rs.StatusCode == 0 {
rs.StatusCode = http.StatusOK
}
t.ReqInfo = rq
t.RespInfo = rs
t.NodeName = endpoint
t.CallStats = traceCallStats{
Latency: rs.Time.Sub(rw.StartTime),
Rx: reqBodyRecorder.Size(),
Tx: rw.Size(),
TimeToFirstByte: rw.TimeToFirstByte,
}
t.Type = TraceMsgType
if globalDebugEnabled {
t.Type = DebugMsgType
}
return t
}
// Log only the headers.
func httpTraceHdrs(f http.HandlerFunc, w http.ResponseWriter, r *http.Request, backend *Backend) {
trace := Trace(f, false, w, r, backend.endpoint)
doTrace(trace, backend)
}
func doTrace(trace TraceInfo, backend *Backend) {
st := shortTrace(trace)
defer backend.updateCallStats(st)
if globalQuietEnabled || globalTrace == "" {
return
}
if globalTrace == "minio" && st.Path != backend.healthCheckPath {
return
}
if globalJSONEnabled {
if globalDebugEnabled {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
// Disable escaping special chars to display XML tags correctly
enc.SetEscapeHTML(false)
if err := enc.Encode(trace); err != nil {
console.Fatalln(err)
}
console.Println(strings.TrimSuffix(buf.String(), "\n"))
} else {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
// Disable escaping special chars to display XML tags correctly
enc.SetEscapeHTML(false)
if err := enc.Encode(st); err != nil {
console.Fatalln(err)
}
console.Println(strings.TrimSuffix(buf.String(), "\n"))
}
return
}
if globalConsoleDisplay {
if globalDebugEnabled {
console.Println(trace)
return
}
console.Println(st)
return
}
}
// TraceInfo - represents a trace record, additionally
// also reports errors if any while listening on trace.
type TraceInfo struct {
Type string `json:"type"`
NodeName string `json:"nodename"`
ReqInfo traceRequestInfo `json:"request"`
RespInfo traceResponseInfo `json:"response"`
CallStats traceCallStats `json:"stats"`
}
// Short trace record
type shortTraceMsg struct {
Type string `json:"type"`
Host string `json:"host"`
Time time.Time `json:"time"`
Client string `json:"client"`
CallStats traceCallStats `json:"callStats"`
StatusCode int `json:"statusCode"`
StatusMsg string `json:"statusMsg"`
Method string `json:"method"`
Path string `json:"path"`
Query string `json:"query"`
}
func (s shortTraceMsg) String() string {
b := &strings.Builder{}
fmt.Fprintf(b, " %5s: ", TraceMsgType)
fmt.Fprintf(b, "%s ", s.Time.Format(timeFormat))
statusStr := console.Colorize("RespStatus", fmt.Sprintf("%d %s", s.StatusCode, s.StatusMsg))
if s.StatusCode >= http.StatusBadRequest {
statusStr = console.Colorize("ErrStatus", fmt.Sprintf("%d %s", s.StatusCode, s.StatusMsg))
}
fmt.Fprintf(b, "[%s] ", statusStr)
fmt.Fprintf(b, " %s ", s.Host)
if s.Query != "" {
fmt.Fprintf(b, "%s %s?%s", s.Method, s.Path, s.Query)
} else {
fmt.Fprintf(b, "%s %s", s.Method, s.Path)
}
fmt.Fprintf(b, " %s ", s.Client)
spaces := 15 - len(s.Client)
fmt.Fprintf(b, "%*s", spaces, " ")
fmt.Fprint(b, console.Colorize("HeaderValue", fmt.Sprintf(" %2s", s.CallStats.Latency.Round(time.Microsecond).String())))
spaces = 12 - len(fmt.Sprintf("%2s", s.CallStats.Latency.Round(time.Microsecond)))
fmt.Fprintf(b, "%*s", spaces, " ")
fmt.Fprint(b, console.Colorize("Stat", " ↑ "))
fmt.Fprint(b, console.Colorize("HeaderValue", humanize.IBytes(uint64(s.CallStats.Rx))))
fmt.Fprint(b, console.Colorize("Stat", " ↓ "))
fmt.Fprint(b, console.Colorize("HeaderValue", humanize.IBytes(uint64(s.CallStats.Tx))))
return b.String()
}
func shortTrace(t TraceInfo) shortTraceMsg {
s := shortTraceMsg{}
s.Type = console.Colorize("TraceMsgType", t.Type)
s.Time = t.ReqInfo.Time
if host, ok := t.ReqInfo.Headers["Host"]; ok {
s.Host = strings.Join(host, "")
}
s.Host = t.NodeName
s.StatusCode = t.RespInfo.StatusCode
s.StatusMsg = http.StatusText(t.RespInfo.StatusCode)
cSlice := strings.Split(t.ReqInfo.Client, ":")
s.Client = cSlice[0]
s.CallStats.Latency = t.CallStats.Latency
s.CallStats.Rx = t.CallStats.Rx
s.CallStats.Tx = t.CallStats.Tx
s.Path = t.ReqInfo.Path
s.Query = t.ReqInfo.RawQuery
s.Method = t.ReqInfo.Method
return s
}
func (trc TraceInfo) String() string {
var nodeNameStr string
b := &strings.Builder{}
if trc.NodeName != "" {
nodeNameStr = fmt.Sprintf("%s: %s ", console.Colorize("TraceMsgType", DebugMsgType), trc.NodeName)
}
ri := trc.ReqInfo
rs := trc.RespInfo
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Request", "[REQUEST] "))
fmt.Fprintf(b, "%s\n", ri.Time.Format(timeFormat))
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Method", fmt.Sprintf("%s %s", ri.Method, ri.Path)))
if ri.RawQuery != "" {
fmt.Fprintf(b, "?%s", ri.RawQuery)
}
fmt.Fprint(b, "\n")
host, ok := ri.Headers["Host"]
if ok {
delete(ri.Headers, "Host")
}
hostStr := strings.Join(host, "")
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Host", fmt.Sprintf("Host: %s\n", hostStr)))
for k, v := range ri.Headers {
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("ReqHeaderKey",
fmt.Sprintf("%s: ", k))+console.Colorize("HeaderValue", fmt.Sprintf("%s\n", strings.Join(v, ""))))
}
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Body", fmt.Sprintf("%s\n", ri.Body)))
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("Response", "[RESPONSE] "))
fmt.Fprintf(b, "[%s] ", rs.Time.Format(timeFormat))
fmt.Fprint(b, console.Colorize("Stat", fmt.Sprintf("[ Duration %2s ↑ %s ↓ %s ]\n", trc.CallStats.Latency.Round(time.Microsecond), humanize.IBytes(uint64(trc.CallStats.Rx)), humanize.IBytes(uint64(trc.CallStats.Tx)))))
statusStr := console.Colorize("RespStatus", fmt.Sprintf("%d %s", rs.StatusCode, http.StatusText(rs.StatusCode)))
if rs.StatusCode != http.StatusOK {
statusStr = console.Colorize("ErrStatus", fmt.Sprintf("%d %s", rs.StatusCode, http.StatusText(rs.StatusCode)))
}
fmt.Fprintf(b, "%s%s\n", nodeNameStr, statusStr)
for k, v := range rs.Headers {
fmt.Fprintf(b, "%s%s", nodeNameStr, console.Colorize("RespHeaderKey",
fmt.Sprintf("%s: ", k))+console.Colorize("HeaderValue", fmt.Sprintf("%s\n", strings.Join(v, ""))))
}
fmt.Fprintf(b, "%s%s\n", nodeNameStr, console.Colorize("Body", rs.Body))
fmt.Fprint(b, nodeNameStr)
return b.String()
}
// traceCallStats records request stats
type traceCallStats struct {
Rx int `json:"rx"`
Tx int `json:"tx"`
Latency time.Duration `json:"latency"`
TimeToFirstByte time.Duration `json:"timetofirstbyte"`
}
// traceRequestInfo represents trace of http request
type traceRequestInfo struct {
Time time.Time `json:"time"`
Method string `json:"method"`
Path string `json:"path,omitempty"`
RawQuery string `json:"rawquery,omitempty"`
Headers http.Header `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
Client string `json:"client"`
}
// traceResponseInfo represents trace of http request
type traceResponseInfo struct {
Time time.Time `json:"time"`
Headers http.Header `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
StatusCode int `json:"statuscode,omitempty"`
}