Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 8 additions & 11 deletions pkg/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import (
)

var (
RequestDurationLabels = metrics.NewLabels([]string{"scheme", "host", "path", "method", "status"})
RequestDurationMetric = metrics.NewSummaryVecWithOpts(
prometheus.SummaryOpts{
Name: "request_duration_seconds",
Expand All @@ -38,7 +37,7 @@ var (
ConstLabels: prometheus.Labels{"handler": "instrumented_http"},
Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
},
*RequestDurationLabels,
[]string{metrics.LabelScheme, metrics.LabelHost, metrics.LabelPath, metrics.LabelMethod, metrics.LabelStatus},
)
)

Expand All @@ -64,15 +63,13 @@ func (r *CustomRoundTripper) RoundTrip(req *http.Request) (*http.Response, error
status = fmt.Sprintf("%d", resp.StatusCode)
}

RequestDurationLabels.WithOptions(
metrics.WithLabel("scheme", req.URL.Scheme),
metrics.WithLabel("host", req.URL.Host),
metrics.WithLabel("path", metrics.PathProcessor(req.URL.Path)),
metrics.WithLabel("method", req.Method),
metrics.WithLabel("status", status),
)

RequestDurationMetric.SetWithLabels(time.Since(start).Seconds(), RequestDurationLabels)
RequestDurationMetric.SetWithLabels(time.Since(start).Seconds(), metrics.Labels{
metrics.LabelScheme: req.URL.Scheme,
metrics.LabelHost: req.URL.Host,
metrics.LabelPath: metrics.PathProcessor(req.URL.Path),
metrics.LabelMethod: req.Method,
metrics.LabelStatus: status,
})

return resp, err
}
Expand Down
97 changes: 97 additions & 0 deletions pkg/http/http_benchmark_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
Copyright 2025 The Kubernetes Authors.

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 http

import (
"bytes"
"io"
"net/http"
"sync"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

type roundTripFunc func(req *http.Request) *http.Response

func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}

// newTestClient returns *http.client with Transport replaced to avoid making real calls
func newTestClient(fn roundTripFunc) *http.Client {
return &http.Client{
Transport: NewInstrumentedTransport(fn),
}
}

type apiUnderTest struct {
client *http.Client
baseURL string
}

func (api *apiUnderTest) doStuff() ([]byte, error) {
resp, err := api.client.Get(api.baseURL + "/some/path")
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}

func BenchmarkRoundTripper(b *testing.B) {
client := newTestClient(func(req *http.Request) *http.Response {
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`OK`)),
Header: make(http.Header),
}
})

for b.Loop() {
api := apiUnderTest{client, "http://example.com"}
body, err := api.doStuff()
require.NoError(b, err)
assert.Equal(b, []byte("OK"), body)
}
}

func TestRoundTripper_Concurrent(t *testing.T) {
client := newTestClient(func(req *http.Request) *http.Response {
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`OK`)),
Header: make(http.Header),
}
})
api := &apiUnderTest{client: client, baseURL: "http://example.com"}

const numGoroutines = 100
var wg sync.WaitGroup
wg.Add(numGoroutines)

for i := 0; i < numGoroutines; i++ {
go func() {
defer wg.Done()
body, err := api.doStuff()
assert.NoError(t, err)
assert.Equal(t, []byte("OK"), body)
}()
}
wg.Wait()
}
65 changes: 9 additions & 56 deletions pkg/metrics/labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,62 +17,15 @@ limitations under the License.
package metrics

import (
"sort"
"strings"

"github.com/sirupsen/logrus"
"github.com/prometheus/client_golang/prometheus"
)

type Labels struct {
values map[string]string
}

func (labels *Labels) GetKeysInOrder() []string {
keys := make([]string, 0, len(labels.values))
for key := range labels.values {
keys = append(keys, key)
}

sort.Strings(keys)

return keys
}

func (labels *Labels) GetValuesOrderedByKey() []string {
var orderedValues []string
for _, key := range labels.GetKeysInOrder() {
orderedValues = append(orderedValues, labels.values[key])
}

return orderedValues
}

type LabelOption func(*Labels)

func NewLabels(labelNames []string) *Labels {
labels := &Labels{
values: make(map[string]string),
}

for _, label := range labelNames {
labels.values[strings.ToLower(label)] = ""
}

return labels
}

func (labels *Labels) WithOptions(options ...LabelOption) {
for _, option := range options {
option(labels)
}
}
const (
LabelScheme = "scheme"
LabelHost = "host"
LabelPath = "path"
LabelMethod = "method"
LabelStatus = "status"
)

func WithLabel(labelName string, labelValue string) LabelOption {
return func(labels *Labels) {
if _, ok := labels.values[strings.ToLower(labelName)]; !ok {
logrus.Errorf("Attempting to set a value for a label that doesn't exist! '%s' does not exist!", labelName)
} else {
labels.values[strings.ToLower(labelName)] = labelValue
}
}
}
type Labels = prometheus.Labels
Loading
Loading