Skip to content

Commit

Permalink
httptransport: add a request_id to logs
Browse files Browse the repository at this point in the history
This re-uses any trace ID that OpenTelemetry supports, or generates a
weakly random one based on some request features.

Closes: quay#1547
Signed-off-by: Hank Donnay <hdonnay@redhat.com>
  • Loading branch information
hdonnay committed Dec 6, 2022
1 parent 4b37dcd commit 2a58ae4
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 3 deletions.
31 changes: 31 additions & 0 deletions httptransport/common.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
package httptransport

import (
"encoding/hex"
"errors"
"fmt"
"hash"
"hash/fnv"
"io"
"mime"
"net/http"
"path"
"sort"
"strconv"
"strings"
"sync"

"github.com/quay/zlog"
"go.opentelemetry.io/otel/trace"

"github.com/quay/claircore"
)
Expand Down Expand Up @@ -106,3 +114,26 @@ func (a *accept) Match(mt string) bool {
t, s := mt[:i], mt[i+1:]
return a.Type == t && (a.Subtype == s || a.Subtype == "*")
}

var idPool sync.Pool

func withRequestID(r *http.Request) *http.Request {
const key = `request_id`
ctx := r.Context()
sctx := trace.SpanContextFromContext(ctx)
if sctx.HasTraceID() {
ctx = zlog.ContextWithValues(ctx, key, sctx.TraceID().String())
} else {
h := idPool.Get().(hash.Hash64)
if h == nil {
h = fnv.New64a()
} else {
h.Reset()
}
io.WriteString(h, r.RequestURI)
io.WriteString(h, r.RemoteAddr)
ctx = zlog.ContextWithValues(ctx, key, hex.EncodeToString(h.Sum(nil)))
idPool.Put(h)
}
return r.WithContext(ctx)
}
2 changes: 1 addition & 1 deletion httptransport/indexer_v1.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func (h *IndexerV1) ServeHTTP(w http.ResponseWriter, r *http.Request) {
Dur("duration", time.Since(start)).
Msg("handled HTTP request")
}()
h.inner.ServeHTTP(wr, r)
h.inner.ServeHTTP(wr, withRequestID(r))
}

func (h *IndexerV1) indexReport(w http.ResponseWriter, r *http.Request) {
Expand Down
2 changes: 1 addition & 1 deletion httptransport/matcher_v1.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (h *MatcherV1) ServeHTTP(w http.ResponseWriter, r *http.Request) {
Dur("duration", time.Since(start)).
Msg("handled HTTP request")
}()
h.inner.ServeHTTP(wr, r)
h.inner.ServeHTTP(wr, withRequestID(r))
}

func (h *MatcherV1) vulnerabilityReport(w http.ResponseWriter, r *http.Request) {
Expand Down
2 changes: 1 addition & 1 deletion httptransport/notification_v1.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func (h *NotificationV1) ServeHTTP(w http.ResponseWriter, r *http.Request) {
Dur("duration", time.Since(start)).
Msg("handled HTTP request")
}()
h.inner.ServeHTTP(wr, r)
h.inner.ServeHTTP(wr, withRequestID(r))
}

func (h *NotificationV1) serveHTTP(w http.ResponseWriter, r *http.Request) {
Expand Down

0 comments on commit 2a58ae4

Please sign in to comment.