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.
50 func HandlerWithDeadline(timeout time.Duration, next http.Handler) http.Handler {
51 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
52 ctx, cancel := context.WithCancel(r.Context())
54 nodeadline := make(chan bool)
59 case <-time.After(timeout):
63 if hj, ok := w.(hijacker); ok {
64 w = hijackNotifier{hj, nodeadline}
66 next.ServeHTTP(w, r.WithContext(ctx))
70 func SetResponseLogFields(ctx context.Context, fields logrus.Fields) {
71 m, _ := ctx.Value(&mutexContextKey).(*sync.Mutex)
72 c, _ := ctx.Value(&responseLogFieldsContextKey).(logrus.Fields)
73 if m == nil || c == nil {
78 for k, v := range fields {
83 // LogRequests wraps an http.Handler, logging each request and
85 func LogRequests(h http.Handler) http.Handler {
86 return http.HandlerFunc(func(wrapped http.ResponseWriter, req *http.Request) {
87 w := &responseTimer{ResponseWriter: WrapResponseWriter(wrapped)}
88 lgr := ctxlog.FromContext(req.Context()).WithFields(logrus.Fields{
89 "RequestID": req.Header.Get("X-Request-Id"),
90 "remoteAddr": req.RemoteAddr,
91 "reqForwardedFor": req.Header.Get("X-Forwarded-For"),
92 "reqMethod": req.Method,
94 "reqPath": req.URL.Path[1:],
95 "reqQuery": req.URL.RawQuery,
96 "reqBytes": req.ContentLength,
99 ctx = context.WithValue(ctx, &requestTimeContextKey, time.Now())
100 ctx = context.WithValue(ctx, &responseLogFieldsContextKey, logrus.Fields{})
101 ctx = context.WithValue(ctx, &mutexContextKey, &sync.Mutex{})
102 ctx = ctxlog.Context(ctx, lgr)
103 req = req.WithContext(ctx)
105 logRequest(w, req, lgr)
106 defer logResponse(w, req, lgr)
107 h.ServeHTTP(rewrapResponseWriter(w, wrapped), req)
111 // Rewrap w to restore additional interfaces provided by wrapped.
112 func rewrapResponseWriter(w http.ResponseWriter, wrapped http.ResponseWriter) http.ResponseWriter {
113 if hijacker, ok := wrapped.(http.Hijacker); ok {
122 func Logger(req *http.Request) logrus.FieldLogger {
123 return ctxlog.FromContext(req.Context())
126 func logRequest(w *responseTimer, req *http.Request, lgr *logrus.Entry) {
130 func logResponse(w *responseTimer, req *http.Request, lgr *logrus.Entry) {
131 if tStart, ok := req.Context().Value(&requestTimeContextKey).(time.Time); ok {
133 writeTime := w.writeTime
135 // Empty response body. Header was sent when
139 lgr = lgr.WithFields(logrus.Fields{
140 "timeTotal": stats.Duration(tDone.Sub(tStart)),
141 "timeToStatus": stats.Duration(writeTime.Sub(tStart)),
142 "timeWriteBody": stats.Duration(tDone.Sub(writeTime)),
145 if responseLogFields, ok := req.Context().Value(&responseLogFieldsContextKey).(logrus.Fields); ok {
146 lgr = lgr.WithFields(responseLogFields)
148 respCode := w.WroteStatus()
150 respCode = http.StatusOK
152 fields := logrus.Fields{
153 "respStatusCode": respCode,
154 "respStatus": http.StatusText(respCode),
155 "respBytes": w.WroteBodyBytes(),
158 fields["respBody"] = string(w.Sniffed())
160 lgr.WithFields(fields).Info("response")
163 type responseTimer struct {
169 func (rt *responseTimer) CloseNotify() <-chan bool {
170 if cn, ok := rt.ResponseWriter.(http.CloseNotifier); ok {
171 return cn.CloseNotify()
176 func (rt *responseTimer) WriteHeader(code int) {
179 rt.writeTime = time.Now()
181 rt.ResponseWriter.WriteHeader(code)
184 func (rt *responseTimer) Write(p []byte) (int, error) {
187 rt.writeTime = time.Now()
189 return rt.ResponseWriter.Write(p)