-
Notifications
You must be signed in to change notification settings - Fork 26
/
middleware.go
395 lines (354 loc) · 11.3 KB
/
middleware.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
package logs
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/http/httputil"
"strings"
"time"
"github.com/appbaseio/reactivesearch-api/middleware"
"github.com/appbaseio/reactivesearch-api/middleware/classify"
"github.com/appbaseio/reactivesearch-api/middleware/validate"
"github.com/appbaseio/reactivesearch-api/model/category"
"github.com/appbaseio/reactivesearch-api/model/console"
"github.com/appbaseio/reactivesearch-api/model/difference"
"github.com/appbaseio/reactivesearch-api/model/index"
"github.com/appbaseio/reactivesearch-api/model/request"
"github.com/appbaseio/reactivesearch-api/model/requestlogs"
"github.com/appbaseio/reactivesearch-api/plugins/auth"
"github.com/appbaseio/reactivesearch-api/plugins/telemetry"
"github.com/appbaseio/reactivesearch-api/util"
"github.com/buger/jsonparser"
log "github.com/sirupsen/logrus"
)
type chain struct {
middleware.Fifo
}
// SearchResponseBody represents the response body returned by search
type SearchResponseBody struct {
Took float64 `json:"took"`
}
// RSSettings represents the settings object in RS API response
type RSSettings struct {
Took float64 `json:"took"`
}
// ResponseBodyRS represents the response body returned by reactivesearch route
type ResponseBodyRS struct {
Settings RSSettings `json:"settings"`
}
func (c *chain) Wrap(h http.HandlerFunc) http.HandlerFunc {
return c.Adapt(h, list()...)
}
func list() []middleware.Middleware {
return []middleware.Middleware{
classifyCategory,
classify.Op(),
classify.Indices(),
auth.BasicAuth(),
validate.Sources(),
validate.Indices(),
validate.Operation(),
validate.Category(),
telemetry.Recorder(),
}
}
func classifyCategory(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
requestCategory := category.Logs
ctx := category.NewContext(req.Context(), &requestCategory)
req = req.WithContext(ctx)
h(w, req)
}
}
type Request struct {
URI string `json:"uri"`
Method string `json:"method"`
Headers map[string][]string `json:"header"`
Body string `json:"body"`
}
type Response struct {
Code int `json:"code"`
Status string `json:"status"`
Headers map[string][]string
Took *float64 `json:"took,omitempty"`
Body string `json:"body"`
}
type record struct {
Indices []string `json:"indices"`
Category string `json:"category"`
Request Request `json:"request"`
Response Response `json:"response"`
RequestChanges []difference.Difference `json:"requestChanges"`
ResponseChanges []difference.Difference `json:"responseChanges"`
Timestamp time.Time `json:"timestamp"`
Console []string `json:"console_logs"`
DiffLogs bool `json:"diffLogs"`
}
// Recorder records a log "record" for every request.
func Recorder() middleware.Middleware {
return Instance().recorder
}
func (l *Logs) recorder(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// skip logs from streams and blacklisted paths
if r.Header.Get("X-Request-Category") == "streams" || isPathBlacklisted(r.URL.Path) {
h(w, r)
return
}
dumpRequest, err := httputil.DumpRequest(r, true)
if err != nil {
log.Errorln(logTag, ":", err.Error())
return
}
// Init the console logs in the context
consoleLogs := make([]string, 0)
consoleLogsCtx := console.NewContext(r.Context(), &consoleLogs)
r = r.WithContext(consoleLogsCtx)
// Serve using response recorder
respRecorder := httptest.NewRecorder()
h(respRecorder, r)
// Copy the response to writer
for k, v := range respRecorder.Header() {
w.Header()[k] = v
}
w.WriteHeader(respRecorder.Code)
w.Write(respRecorder.Body.Bytes())
// Record the document
go l.recordResponse(respRecorder, r, dumpRequest)
}
}
type Query struct {
Type string `json:"type"`
}
type RSAPI struct {
Query []Query `json:"query"`
}
type RequestChange struct {
Before requestlogs.LogsResults
After requestlogs.LogsResults
}
func (l *Logs) recordResponse(w *httptest.ResponseRecorder, r *http.Request, reqBody []byte) {
var headers = make(map[string][]string)
for key, values := range r.Header {
headers[key] = values
}
ctx := r.Context()
reqCategory, err := category.FromContext(ctx)
if err != nil {
log.Errorln(logTag, ":", err)
return
}
reqIndices, err := index.FromContext(ctx)
if err != nil {
log.Errorln(logTag, ":", err)
return
}
requestInfo, err := request.FromRequestIDContext(ctx)
if err != nil {
if *reqCategory == category.ReactiveSearch {
log.Warnln(logTag, ":", err)
}
}
var rec record
rec.Indices = reqIndices
rec.Category = reqCategory.String()
requestBody := strings.Split(string(reqBody), "\r\n\r\n")
var parsedBody []byte
if len(requestBody) > 1 {
parsedBody = []byte(requestBody[1])
}
// apply suggestion category
if *reqCategory == category.ReactiveSearch {
var reqBody []byte
if requestInfo != nil {
reqBody = requestInfo.Body
var query RSAPI
err2 := json.Unmarshal(reqBody, &query)
if err2 != nil {
log.Errorln(logTag, ":", err2)
} else {
parsedBody = reqBody
for _, query := range query.Query {
if query.Type == "suggestion" {
rec.Category = "suggestion"
}
}
}
}
}
rec.Timestamp = time.Now()
// record response
response := w.Result()
rec.Response.Code = response.StatusCode
rec.Response.Status = http.StatusText(response.StatusCode)
rec.Response.Headers = response.Header
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Errorln(logTag, "can't read response body: ", err)
return
}
if *reqCategory == category.Search {
var resBody SearchResponseBody
err := json.Unmarshal(responseBody, &resBody)
if err != nil {
log.Errorln(logTag, "error encountered while parsing the response: ", err)
}
// ignore error to record error logs
if err == nil {
rec.Response.Took = &resBody.Took
}
}
requestBodyToStore := string(parsedBody[:util.Min(len(parsedBody), 1000000)])
if *reqCategory == category.ReactiveSearch {
rec.Request = Request{
URI: r.URL.Path,
Headers: headers,
Body: requestBodyToStore,
Method: r.Method,
}
// read success response from context
tookValue, err := jsonparser.GetFloat(w.Body.Bytes(), "settings", "took")
if err != nil {
log.Warnln(logTag, "error encountered while reading took key from response body:", err)
} else {
// Set took value
rec.Response.Took = &tookValue
}
// read error response from response recorder body
rec.Response.Body = string(responseBody[:util.Min(len(responseBody), 1000000)])
} else {
// record request
rec.Request = Request{
URI: r.URL.Path,
Headers: headers,
Body: requestBodyToStore,
Method: r.Method,
}
rec.Response.Body = string(responseBody[:util.Min(len(responseBody), 1000000)])
}
// Extract the request changes from context
if requestInfo != nil {
requestId := requestInfo.Id
rl := requestlogs.Get(requestId)
if rl != nil {
go func() {
rl.LogsDiffing.Wait()
close(rl.Output)
}()
requestChangesByStage := make(map[string]RequestChange)
responseChangesByStage := make(map[string]RequestChange)
for result := range rl.Output {
if result.LogType == "request" {
requestChange := RequestChange{}
rc, ok := requestChangesByStage[result.Stage]
if ok {
requestChange = rc
}
if result.LogTime == "before" {
requestChange.Before = result
} else if result.LogTime == "after" {
requestChange.After = result
}
requestChangesByStage[result.Stage] = requestChange
} else if result.LogType == "response" {
responseChange := RequestChange{}
rc, ok := requestChangesByStage[result.Stage]
if ok {
responseChange = rc
}
if result.LogTime == "before" {
responseChange.Before = result
} else if result.LogTime == "after" {
responseChange.Before = result
}
responseChangesByStage[result.Stage] = responseChange
}
}
// calculate diffing
rec = l.captureStageChanges(rec, requestChangesByStage, responseChangesByStage)
// Delete request logs
requestlogs.Delete(requestId)
}
}
// Extract the console logs
consoleStr, err := console.FromContext(ctx)
if err != nil {
log.Warnln(logTag, "couldn't extract console logs, ", err)
} else {
rec.Console = *consoleStr
}
marshalledLog, err := json.Marshal(rec)
if err != nil {
log.Warningln(logTag, "error encountered while marshalling record :", err)
return
}
n, err := l.lumberjack.Write(marshalledLog)
if err != nil {
log.Errorln(logTag, "error encountered while writing logs :", err)
return
}
// Add new line character so filebeat can sync it with ES
l.lumberjack.Write([]byte("\n"))
log.Println(logTag, "logged request successfully", n)
}
// captureStageChanges will capture the stage changes on a per-stage
// basis for the logs to be written
func (l *Logs) captureStageChanges(rec record, requestChangesByStage map[string]RequestChange, responseChangesByStage map[string]RequestChange) record {
// Capture the request changes
//
// We want to store the diffs of each stage if diffing flag is enabled.
// If the flag is disabled, we then store the request bodies in order
requestChanges := make([]difference.Difference, 0)
for stage, changes := range requestChangesByStage {
var differenceEach difference.Difference
if l.enableDiffing {
differenceEach = difference.Difference{
Body: util.CalculateBodyStringDiff(changes.Before.Data.Body, changes.After.Data.Body),
Headers: util.CalculateHeaderDiff(changes.Before.Data.Headers, changes.After.Data.Headers),
URI: util.CalculateStringDiff(changes.Before.Data.URL, changes.After.Data.URL),
Method: util.CalculateMethodStringDiff(changes.Before.Data.Method, changes.After.Data.Method),
Stage: stage,
Took: &changes.After.TimeTaken,
}
} else {
headersAsBytes, _ := json.Marshal(changes.After.Data.Headers)
differenceEach = difference.Difference{
Body: changes.After.Data.Body,
Headers: string(headersAsBytes),
URI: changes.After.Data.URL,
Method: changes.After.Data.Method,
Stage: stage,
Took: &changes.After.TimeTaken,
}
}
requestChanges = append(requestChanges, differenceEach)
}
rec.RequestChanges = requestChanges
responseChanges := make([]difference.Difference, 0)
for stage, changes := range responseChangesByStage {
var differenceEach difference.Difference
if l.enableDiffing {
differenceEach = difference.Difference{
Body: util.CalculateBodyStringDiff(changes.Before.Data.Body, changes.After.Data.Body),
Headers: util.CalculateHeaderDiff(changes.Before.Data.Headers, changes.After.Data.Headers),
Stage: stage,
Took: &changes.After.TimeTaken,
}
} else {
// We are already capturing the final response in the top level
// so we will need to capture the before of every stage here.
headersAsBytes, _ := json.Marshal(changes.After.Data.Headers)
differenceEach = difference.Difference{
Body: changes.Before.Data.Body,
Headers: string(headersAsBytes),
Stage: stage,
Took: &changes.After.TimeTaken,
}
}
responseChanges = append(responseChanges, differenceEach)
}
rec.ResponseChanges = responseChanges
rec.DiffLogs = l.enableDiffing
return rec
}