1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
15 "git.arvados.org/arvados.git/sdk/go/ctxlog"
16 "git.arvados.org/arvados.git/sdk/go/stats"
17 "github.com/sirupsen/logrus"
20 type contextKey struct {
25 requestTimeContextKey = contextKey{"requestTime"}
26 responseLogFieldsContextKey = contextKey{"responseLogFields"}
27 mutexContextKey = contextKey{"mutex"}
30 type hijacker interface {
35 // hijackNotifier wraps a ResponseWriter, calling the provided
36 // Notify() func if/when the wrapped Hijacker is hijacked.
37 type hijackNotifier struct {
42 func (hn hijackNotifier) Hijack() (net.Conn, *bufio.ReadWriter, error) {
44 return hn.hijacker.Hijack()
47 // HandlerWithDeadline cancels the request context if the request
48 // takes longer than the specified timeout without having its
49 // connection hijacked.
51 // If timeout is 0, there is no deadline: HandlerWithDeadline is a
53 func HandlerWithDeadline(timeout time.Duration, next http.Handler) http.Handler {
57 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
58 ctx, cancel := context.WithCancel(r.Context())
60 nodeadline := make(chan bool)
65 case <-time.After(timeout):
69 if hj, ok := w.(hijacker); ok {
70 w = hijackNotifier{hj, nodeadline}
72 next.ServeHTTP(w, r.WithContext(ctx))
76 func SetResponseLogFields(ctx context.Context, fields logrus.Fields) {
77 m, _ := ctx.Value(&mutexContextKey).(*sync.Mutex)
78 c, _ := ctx.Value(&responseLogFieldsContextKey).(logrus.Fields)
79 if m == nil || c == nil {
84 for k, v := range fields {
89 // LogRequests wraps an http.Handler, logging each request and
91 func LogRequests(h http.Handler) http.Handler {
92 return http.HandlerFunc(func(wrapped http.ResponseWriter, req *http.Request) {
93 w := &responseTimer{ResponseWriter: WrapResponseWriter(wrapped)}
94 lgr := ctxlog.FromContext(req.Context()).WithFields(logrus.Fields{
95 "RequestID": req.Header.Get("X-Request-Id"),
96 "remoteAddr": req.RemoteAddr,
97 "reqForwardedFor": req.Header.Get("X-Forwarded-For"),
98 "reqMethod": req.Method,
100 "reqPath": req.URL.Path[1:],
101 "reqQuery": req.URL.RawQuery,
102 "reqBytes": req.ContentLength,
105 ctx = context.WithValue(ctx, &requestTimeContextKey, time.Now())
106 ctx = context.WithValue(ctx, &responseLogFieldsContextKey, logrus.Fields{})
107 ctx = context.WithValue(ctx, &mutexContextKey, &sync.Mutex{})
108 ctx = ctxlog.Context(ctx, lgr)
109 req = req.WithContext(ctx)
111 logRequest(w, req, lgr)
112 defer logResponse(w, req, lgr)
113 h.ServeHTTP(rewrapResponseWriter(w, wrapped), req)
117 // Rewrap w to restore additional interfaces provided by wrapped.
118 func rewrapResponseWriter(w http.ResponseWriter, wrapped http.ResponseWriter) http.ResponseWriter {
119 if hijacker, ok := wrapped.(http.Hijacker); ok {
128 func Logger(req *http.Request) logrus.FieldLogger {
129 return ctxlog.FromContext(req.Context())
132 func logRequest(w *responseTimer, req *http.Request, lgr *logrus.Entry) {
136 func logResponse(w *responseTimer, req *http.Request, lgr *logrus.Entry) {
137 if tStart, ok := req.Context().Value(&requestTimeContextKey).(time.Time); ok {
139 writeTime := w.writeTime
141 // Empty response body. Header was sent when
145 lgr = lgr.WithFields(logrus.Fields{
146 "timeTotal": stats.Duration(tDone.Sub(tStart)),
147 "timeToStatus": stats.Duration(writeTime.Sub(tStart)),
148 "timeWriteBody": stats.Duration(tDone.Sub(writeTime)),
151 if responseLogFields, ok := req.Context().Value(&responseLogFieldsContextKey).(logrus.Fields); ok {
152 lgr = lgr.WithFields(responseLogFields)
154 respCode := w.WroteStatus()
156 respCode = http.StatusOK
158 fields := logrus.Fields{
159 "respStatusCode": respCode,
160 "respStatus": http.StatusText(respCode),
161 "respBytes": w.WroteBodyBytes(),
164 fields["respBody"] = string(w.Sniffed())
166 lgr.WithFields(fields).Info("response")
169 type responseTimer struct {
175 func (rt *responseTimer) CloseNotify() <-chan bool {
176 if cn, ok := rt.ResponseWriter.(http.CloseNotifier); ok {
177 return cn.CloseNotify()
182 func (rt *responseTimer) WriteHeader(code int) {
185 rt.writeTime = time.Now()
187 rt.ResponseWriter.WriteHeader(code)
190 func (rt *responseTimer) Write(p []byte) (int, error) {
193 rt.writeTime = time.Now()
195 return rt.ResponseWriter.Write(p)