forked from palantir/witchcraft-go-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
174 lines (154 loc) · 6.24 KB
/
request.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
// Copyright (c) 2018 Palantir Technologies. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package middleware
import (
"net/http"
"time"
"github.com/palantir/pkg/metrics"
"github.com/palantir/witchcraft-go-logging/wlog"
"github.com/palantir/witchcraft-go-logging/wlog/auditlog/audit2log"
"github.com/palantir/witchcraft-go-logging/wlog/evtlog/evt2log"
"github.com/palantir/witchcraft-go-logging/wlog/extractor"
"github.com/palantir/witchcraft-go-logging/wlog/metriclog/metric1log"
"github.com/palantir/witchcraft-go-logging/wlog/svclog/svc1log"
"github.com/palantir/witchcraft-go-logging/wlog/trclog/trc1log"
"github.com/palantir/witchcraft-go-server/witchcraft/internal/negroni"
"github.com/palantir/witchcraft-go-server/wrouter"
"github.com/palantir/witchcraft-go-tracing/wtracing"
"github.com/palantir/witchcraft-go-tracing/wtracing/propagation/b3"
"github.com/palantir/witchcraft-go-tracing/wzipkin"
)
func NewRequestPanicRecovery() wrouter.RequestHandlerMiddleware {
return func(rw http.ResponseWriter, req *http.Request, next http.Handler) {
recovery := negroni.NewRecovery()
recovery.PrintStack = false
recovery.ServeHTTP(rw, req, func(rw http.ResponseWriter, req *http.Request) {
next.ServeHTTP(rw, req)
})
}
}
// NewRequestContextLoggers is request middleware that sets loggers that can be retrieved from a context on the request
// context.
func NewRequestContextLoggers(
svcLogger svc1log.Logger,
evtLogger evt2log.Logger,
auditLogger audit2log.Logger,
metricLogger metric1log.Logger,
) wrouter.RequestHandlerMiddleware {
return func(rw http.ResponseWriter, req *http.Request, next http.Handler) {
ctx := req.Context()
if svcLogger != nil {
ctx = svc1log.WithLogger(ctx, svcLogger)
}
if evtLogger != nil {
ctx = evt2log.WithLogger(ctx, evtLogger)
}
if auditLogger != nil {
ctx = audit2log.WithLogger(ctx, auditLogger)
}
if metricLogger != nil {
ctx = metric1log.WithLogger(ctx, metricLogger)
}
next.ServeHTTP(rw, req.WithContext(ctx))
}
}
// NewRequestContextMetricsRegistry is request middleware that sets the metrics registry on the request context.
func NewRequestContextMetricsRegistry(metricsRegistry metrics.Registry) wrouter.RequestHandlerMiddleware {
return func(rw http.ResponseWriter, req *http.Request, next http.Handler) {
ctx := req.Context()
if metricsRegistry != nil {
ctx = metrics.WithRegistry(ctx, metricsRegistry)
}
next.ServeHTTP(rw, req.WithContext(ctx))
}
}
func NewRequestExtractIDs(
svcLogger svc1log.Logger,
trcLogger trc1log.Logger,
tracerOptions []wtracing.TracerOption,
idsExtractor extractor.IDsFromRequest,
) wrouter.RequestHandlerMiddleware {
return func(rw http.ResponseWriter, req *http.Request, next http.Handler) {
// extract all IDs from request
ids := idsExtractor.ExtractIDs(req)
uid := ids[extractor.UIDKey]
sid := ids[extractor.SIDKey]
tokenID := ids[extractor.TokenIDKey]
// set IDs on context for loggers
ctx := req.Context()
if uid != "" {
ctx = wlog.ContextWithUID(ctx, uid)
}
if sid != "" {
ctx = wlog.ContextWithSID(ctx, sid)
}
if tokenID != "" {
ctx = wlog.ContextWithTokenID(ctx, tokenID)
}
// create tracer and set on context. Tracer logs to trace logger if it is non-nil or is a no-op if nil.
traceReporter := wtracing.NewNoopReporter()
if trcLogger != nil {
// add trc1logger with params set
// TODO(nmiyake): there is currently ongoing discussion about whether or not these fields are required for trace logs. If they are not, it would cleaner to put the logic that extracts the IDs into its own request middleware layer.
ctx = trc1log.WithLogger(ctx, trc1log.WithParams(trcLogger, trc1log.UID(uid), trc1log.SID(sid), trc1log.TokenID(tokenID)))
traceReporter = trcLogger
}
tracer, err := wzipkin.NewTracer(traceReporter, tracerOptions...)
if err != nil && svcLogger != nil {
svcLogger.Error("Failed to create tracer", svc1log.Stacktrace(err))
}
ctx = wtracing.ContextWithTracer(ctx, tracer)
// retrieve existing trace info from request and create a span
reqSpanContext := b3.SpanExtractor(req)()
span := tracer.StartSpan("witchcraft-go-server request middleware", wtracing.WithParentSpanContext(reqSpanContext))
defer span.Finish()
ctx = wtracing.ContextWithSpan(ctx, span)
b3.SpanInjector(req)(span.Context())
// update request with new context
req = req.WithContext(ctx)
// delegate to the next handler
next.ServeHTTP(rw, req)
}
}
// staticRootSpanIDGenerator returns the stored TraceID as its TraceID and SpanID.
type staticRootSpanIDGenerator wtracing.TraceID
func (s staticRootSpanIDGenerator) TraceID() wtracing.TraceID {
return wtracing.TraceID(s)
}
func (s staticRootSpanIDGenerator) SpanID(traceID wtracing.TraceID) wtracing.SpanID {
return wtracing.SpanID(s)
}
func NewRequestMetricRequestMeter(mr metrics.RootRegistry) wrouter.RouteHandlerMiddleware {
const (
serverResponseMetricName = "server.response"
serverResponseErrorMetricName = "server.response.error"
serverRequestSizeMetricName = "server.request.size"
serverResponseSizeMetricName = "server.response.size"
)
return func(rw http.ResponseWriter, r *http.Request, reqVals wrouter.RequestVals, next wrouter.RouteRequestHandler) {
// add capability to store tags on the context
r = r.WithContext(metrics.AddTags(r.Context()))
start := time.Now()
lrw := toLoggingResponseWriter(rw)
next(lrw, r, reqVals)
tags := reqVals.MetricTags
// record metrics for call
mr.Timer(serverResponseMetricName, tags...).Update(time.Since(start) / time.Microsecond)
mr.Histogram(serverRequestSizeMetricName, tags...).Update(r.ContentLength)
mr.Histogram(serverResponseSizeMetricName, tags...).Update(int64(lrw.Size()))
if lrw.Status()/100 == 5 {
mr.Meter(serverResponseErrorMetricName, tags...).Mark(1)
}
}
}