Skip to content

Commit

Permalink
move common metrics-related funcs to internal package
Browse files Browse the repository at this point in the history
Signed-off-by: Dave Henderson <[email protected]>
  • Loading branch information
hairyhenderson committed Jan 25, 2022
1 parent da4a759 commit 7ca5921
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 94 deletions.
39 changes: 39 additions & 0 deletions internal/metrics/metrics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package metrics

import (
"net/http"
"strconv"
)

func SanitizeCode(s int) string {
switch s {
case 0, 200:
return "200"
default:
return strconv.Itoa(s)
}
}

// Only support the list of "regular" HTTP methods, see
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
var methodMap = map[string]string{
"GET": http.MethodGet, "get": http.MethodGet,
"HEAD": http.MethodHead, "head": http.MethodHead,
"PUT": http.MethodPut, "put": http.MethodPut,
"POST": http.MethodPost, "post": http.MethodPost,
"DELETE": http.MethodDelete, "delete": http.MethodDelete,
"CONNECT": http.MethodConnect, "connect": http.MethodConnect,
"OPTIONS": http.MethodOptions, "options": http.MethodOptions,
"TRACE": http.MethodTrace, "trace": http.MethodTrace,
"PATCH": http.MethodPatch, "patch": http.MethodPatch,
}

// SanitizeMethod sanitizes the method for use as a metric label. This helps
// prevent high cardinality on the method label. The name is always upper case.
func SanitizeMethod(m string) string {
if m, ok := methodMap[m]; ok {
return m
}

return "OTHER"
}
28 changes: 28 additions & 0 deletions internal/metrics/metrics_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package metrics

import (
"strings"
"testing"
)

func TestSanitizeMethod(t *testing.T) {
tests := []struct {
method string
expected string
}{
{method: "get", expected: "GET"},
{method: "POST", expected: "POST"},
{method: "OPTIONS", expected: "OPTIONS"},
{method: "connect", expected: "CONNECT"},
{method: "trace", expected: "TRACE"},
{method: "UNKNOWN", expected: "OTHER"},
{method: strings.Repeat("ohno", 9999), expected: "OTHER"},
}

for _, d := range tests {
actual := SanitizeMethod(d.method)
if actual != d.expected {
t.Errorf("Not same: expected %#v, but got %#v", d.expected, actual)
}
}
}
39 changes: 3 additions & 36 deletions metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package caddy

import (
"net/http"
"strconv"

"github.com/caddyserver/caddy/v2/internal/metrics"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promauto"
Expand Down Expand Up @@ -45,8 +45,8 @@ func instrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler)
d := newDelegator(w)
next.ServeHTTP(d, r)
counter.With(prometheus.Labels{
"code": sanitizeCode(d.status),
"method": sanitizeMethod(r.Method),
"code": metrics.SanitizeCode(d.status),
"method": metrics.SanitizeMethod(r.Method),
}).Inc()
})
}
Expand All @@ -66,36 +66,3 @@ func (d *delegator) WriteHeader(code int) {
d.status = code
d.ResponseWriter.WriteHeader(code)
}

func sanitizeCode(s int) string {
switch s {
case 0, 200:
return "200"
default:
return strconv.Itoa(s)
}
}

// Only support the list of "regular" HTTP methods, see
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
var methodMap = map[string]string{
"GET": http.MethodGet, "get": http.MethodGet,
"HEAD": http.MethodHead, "head": http.MethodHead,
"PUT": http.MethodPut, "put": http.MethodPut,
"POST": http.MethodPost, "post": http.MethodPost,
"DELETE": http.MethodDelete, "delete": http.MethodDelete,
"CONNECT": http.MethodConnect, "connect": http.MethodConnect,
"OPTIONS": http.MethodOptions, "options": http.MethodOptions,
"TRACE": http.MethodTrace, "trace": http.MethodTrace,
"PATCH": http.MethodPatch, "patch": http.MethodPatch,
}

// sanitizeMethod sanitizes the method for use as a metric label. This helps
// prevent high cardinality on the method label. The name is always upper case.
func sanitizeMethod(m string) string {
if m, ok := methodMap[m]; ok {
return m
}

return "OTHER"
}
39 changes: 4 additions & 35 deletions modules/caddyhttp/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package caddyhttp
import (
"context"
"net/http"
"strconv"
"sync"
"time"

"github.com/caddyserver/caddy/v2/internal/metrics"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
Expand Down Expand Up @@ -108,7 +108,7 @@ func newMetricsInstrumentedHandler(handler string, mh MiddlewareHandler) *metric
func (h *metricsInstrumentedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error {
server := serverNameFromContext(r.Context())
labels := prometheus.Labels{"server": server, "handler": h.handler}
method := sanitizeMethod(r.Method)
method := metrics.SanitizeMethod(r.Method)
// the "code" value is set later, but initialized here to eliminate the possibility
// of a panic
statusLabels := prometheus.Labels{"server": server, "handler": h.handler, "method": method, "code": ""}
Expand All @@ -123,7 +123,7 @@ func (h *metricsInstrumentedHandler) ServeHTTP(w http.ResponseWriter, r *http.Re
// being called when the headers are written.
// Effectively the same behaviour as promhttp.InstrumentHandlerTimeToWriteHeader.
writeHeaderRecorder := ShouldBufferFunc(func(status int, header http.Header) bool {
statusLabels["code"] = sanitizeCode(status)
statusLabels["code"] = metrics.SanitizeCode(status)
ttfb := time.Since(start).Seconds()
httpMetrics.responseDuration.With(statusLabels).Observe(ttfb)
return false
Expand All @@ -142,7 +142,7 @@ func (h *metricsInstrumentedHandler) ServeHTTP(w http.ResponseWriter, r *http.Re
if statusLabels["code"] == "" {
// we still sanitize it, even though it's likely to be 0. A 200 is
// returned on fallthrough so we want to reflect that.
statusLabels["code"] = sanitizeCode(wrec.Status())
statusLabels["code"] = metrics.SanitizeCode(wrec.Status())
}

httpMetrics.requestDuration.With(statusLabels).Observe(dur)
Expand All @@ -152,37 +152,6 @@ func (h *metricsInstrumentedHandler) ServeHTTP(w http.ResponseWriter, r *http.Re
return nil
}

func sanitizeCode(code int) string {
if code == 0 {
return "200"
}
return strconv.Itoa(code)
}

// Only support the list of "regular" HTTP methods, see
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
var methodMap = map[string]string{
"GET": http.MethodGet, "get": http.MethodGet,
"HEAD": http.MethodHead, "head": http.MethodHead,
"PUT": http.MethodPut, "put": http.MethodPut,
"POST": http.MethodPost, "post": http.MethodPost,
"DELETE": http.MethodDelete, "delete": http.MethodDelete,
"CONNECT": http.MethodConnect, "connect": http.MethodConnect,
"OPTIONS": http.MethodOptions, "options": http.MethodOptions,
"TRACE": http.MethodTrace, "trace": http.MethodTrace,
"PATCH": http.MethodPatch, "patch": http.MethodPatch,
}

// sanitizeMethod sanitizes the method for use as a metric label. This helps
// prevent high cardinality on the method label. The name is always upper case.
func sanitizeMethod(m string) string {
if m, ok := methodMap[m]; ok {
return m
}

return "OTHER"
}

// taken from https://github.com/prometheus/client_golang/blob/6007b2b5cae01203111de55f753e76d8dac1f529/prometheus/promhttp/instrument_server.go#L298
func computeApproximateRequestSize(r *http.Request) int {
s := 0
Expand Down
23 changes: 0 additions & 23 deletions modules/caddyhttp/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/prometheus/client_golang/prometheus/testutil"
Expand Down Expand Up @@ -83,25 +82,3 @@ type middlewareHandlerFunc func(http.ResponseWriter, *http.Request, Handler) err
func (f middlewareHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request, h Handler) error {
return f(w, r, h)
}

func TestSanitizeMethod(t *testing.T) {
tests := []struct {
method string
expected string
}{
{method: "get", expected: "GET"},
{method: "POST", expected: "POST"},
{method: "OPTIONS", expected: "OPTIONS"},
{method: "connect", expected: "CONNECT"},
{method: "trace", expected: "TRACE"},
{method: "UNKNOWN", expected: "OTHER"},
{method: strings.Repeat("ohno", 9999), expected: "OTHER"},
}

for _, d := range tests {
actual := sanitizeMethod(d.method)
if actual != d.expected {
t.Errorf("Not same: expected %#v, but got %#v", d.expected, actual)
}
}
}

0 comments on commit 7ca5921

Please sign in to comment.