-
Notifications
You must be signed in to change notification settings - Fork 2
/
statistics.go
167 lines (140 loc) · 3.8 KB
/
statistics.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
package main
import (
"bufio"
"bytes"
"io/ioutil"
"net"
"net/http"
"strings"
"sync"
"time"
)
type Statistics struct {
ByteTotal int64 `json:"byte_total"`
FirstMessage string `json:"first_message"`
LastMessage string `json:"last_message"`
MessageCount int64 `json:"message_count"`
RequestCount int64 `json:"request_count"`
Requests []*RequestStatistics `json:"requests"`
}
type RequestStatistics struct {
Start time.Time `json:"start"`
End time.Time `json:"end"`
Status int `json:"status"`
}
// TODO(jesse) consider moving Statistics to handler with channel to avoid
// requests blocking each other and to drain on shutdown
type statisticsMiddleware struct {
mu sync.Mutex
statistics *Statistics
}
func newStatisticsMiddleware() *statisticsMiddleware {
return &statisticsMiddleware{
statistics: &Statistics{},
}
}
func (sm *statisticsMiddleware) WrapHTTP(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
handledRequest := &handledRequest{
startTime: time.Now(),
contentType: r.Header.Get("Content-Type"),
contentLength: r.Header.Get("Content-Length"),
}
var b bytes.Buffer
_, err := b.ReadFrom(r.Body)
if err != nil {
handledRequest.statusCode = http.StatusBadRequest
http.Error(rw, "can't read body", http.StatusBadRequest)
return
}
r.Body = ioutil.NopCloser(&b)
handledRequest.body = b.Bytes()
wrapper := &responseWriterWrapper{ResponseWriter: rw}
next.ServeHTTP(wrapper, r)
handledRequest.statusCode = wrapper.status
handledRequest.endTime = time.Now()
go func() {
sm.recordRequest(handledRequest)
}()
})
}
func (sm *statisticsMiddleware) recordRequest(r *handledRequest) {
byteLen := len(r.body)
body := string(r.body)
messages := []string{}
switch r.contentType {
// Unfortunately fluentbit does not use the proper content type when sending
// new line delimited JSON :(
case "application/json":
messages = strings.Split(body, "\n")
case "application/ndjson":
messages = strings.Split(body, "\n")
case "application/x-ndjson":
messages = strings.Split(body, "\n")
case "text/plain":
messages = strings.Split(body, "\n")
}
messageCount := len(messages)
firstMessage := ""
lastMessage := ""
if messageCount > 0 {
firstMessage = messages[0]
lastMessage = messages[messageCount-1]
}
sm.mu.Lock()
defer sm.mu.Unlock()
sm.statistics.RequestCount++
sm.statistics.ByteTotal += int64(byteLen)
sm.statistics.MessageCount += int64(messageCount)
if sm.statistics.FirstMessage == "" {
sm.statistics.FirstMessage = firstMessage
}
if lastMessage != "" {
sm.statistics.LastMessage = lastMessage
}
sm.statistics.Requests = append(sm.statistics.Requests, &RequestStatistics{
Start: r.startTime.UTC(),
End: r.endTime.UTC(),
Status: r.statusCode,
})
}
func (sm *statisticsMiddleware) MessageCount() int64 {
sm.mu.Lock()
defer sm.mu.Unlock()
return sm.statistics.MessageCount
}
func (sm *statisticsMiddleware) RequestCount() int64 {
sm.mu.Lock()
defer sm.mu.Unlock()
return sm.statistics.RequestCount
}
func (sm *statisticsMiddleware) Statistics() Statistics {
sm.mu.Lock()
defer sm.mu.Unlock()
return *sm.statistics
}
type handledRequest struct {
startTime time.Time
endTime time.Time
body []byte
contentType string
contentLength string
statusCode int
}
type responseWriterWrapper struct {
http.ResponseWriter
written int64
status int
}
func (w *responseWriterWrapper) WriteHeader(code int) {
w.status = code
w.ResponseWriter.WriteHeader(code)
}
func (w *responseWriterWrapper) Write(b []byte) (int, error) {
n, err := w.ResponseWriter.Write(b)
w.written += int64(n)
return n, err
}
func (f *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return f.ResponseWriter.(http.Hijacker).Hijack()
}