Fix metrics AlreadyRegisteredError on TestRecordOperation and TestGetHistogramVecFromGatherer unit test

This commit is contained in:
CatherineF-dev 2021-11-10 03:23:54 +00:00
parent 55e1d2f9a7
commit ef0b2dfbf4
2 changed files with 20 additions and 18 deletions

View File

@ -1,12 +1,9 @@
/* /*
Copyright 2016 The Kubernetes Authors. Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -19,20 +16,27 @@ package kuberuntime
import ( import (
"net" "net"
"net/http" "net/http"
"sync"
"testing" "testing"
"time" "time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"k8s.io/component-base/metrics/legacyregistry" compbasemetrics "k8s.io/component-base/metrics"
runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2" runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
"k8s.io/kubernetes/pkg/kubelet/metrics" "k8s.io/kubernetes/pkg/kubelet/metrics"
) )
var registerMetrics sync.Once
func TestRecordOperation(t *testing.T) { func TestRecordOperation(t *testing.T) {
legacyregistry.MustRegister(metrics.RuntimeOperations) // Use local registry
legacyregistry.MustRegister(metrics.RuntimeOperationsDuration) var registry = compbasemetrics.NewKubeRegistry()
legacyregistry.MustRegister(metrics.RuntimeOperationsErrors) registry.MustRegister(metrics.RuntimeOperations)
registry.MustRegister(metrics.RuntimeOperationsDuration)
registry.MustRegister(metrics.RuntimeOperationsErrors)
l, err := net.Listen("tcp", "127.0.0.1:0") l, err := net.Listen("tcp", "127.0.0.1:0")
assert.NoError(t, err) assert.NoError(t, err)
@ -41,7 +45,8 @@ func TestRecordOperation(t *testing.T) {
prometheusURL := "http://" + l.Addr().String() + "/metrics" prometheusURL := "http://" + l.Addr().String() + "/metrics"
mux := http.NewServeMux() mux := http.NewServeMux()
//lint:ignore SA1019 ignore deprecated warning until we move off of global registries //lint:ignore SA1019 ignore deprecated warning until we move off of global registries
mux.Handle("/metrics", legacyregistry.Handler()) handler := promhttp.InstrumentMetricHandler(prometheus.DefaultRegisterer, promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))
mux.Handle("/metrics", handler)
server := &http.Server{ server := &http.Server{
Addr: l.Addr().String(), Addr: l.Addr().String(),
Handler: mux, Handler: mux,
@ -61,6 +66,8 @@ func TestRecordOperation(t *testing.T) {
assert.HTTPBodyContains(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.HTTPBodyContains(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mux.ServeHTTP(w, r) mux.ServeHTTP(w, r)
}), "GET", prometheusURL, nil, runtimeOperationsDurationExpected) }), "GET", prometheusURL, nil, runtimeOperationsDurationExpected)
registry.Reset()
} }
func TestInstrumentedVersion(t *testing.T) { func TestInstrumentedVersion(t *testing.T) {

View File

@ -1,12 +1,9 @@
/* /*
Copyright 2020 The Kubernetes Authors. Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -20,13 +17,11 @@ import (
"fmt" "fmt"
"math" "math"
"reflect" "reflect"
"sync"
"testing" "testing"
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
dto "github.com/prometheus/client_model/go" dto "github.com/prometheus/client_model/go"
"k8s.io/component-base/metrics" "k8s.io/component-base/metrics"
"k8s.io/component-base/metrics/legacyregistry"
"k8s.io/utils/pointer" "k8s.io/utils/pointer"
) )
@ -517,7 +512,6 @@ func TestHistogramVec_Validate(t *testing.T) {
} }
func TestGetHistogramVecFromGatherer(t *testing.T) { func TestGetHistogramVecFromGatherer(t *testing.T) {
var registerMetrics sync.Once
tests := []struct { tests := []struct {
name string name string
lvMap map[string]string lvMap map[string]string
@ -576,16 +570,17 @@ func TestGetHistogramVecFromGatherer(t *testing.T) {
Buckets: buckets, Buckets: buckets,
} }
vec := metrics.NewHistogramVec(HistogramOpts, labels) vec := metrics.NewHistogramVec(HistogramOpts, labels)
registerMetrics.Do(func() { // Use local registry
legacyregistry.MustRegister(vec) var registry = metrics.NewKubeRegistry()
}) var gather metrics.Gatherer = registry
registry.MustRegister(vec)
// Observe two metrics with same value for label1 but different value of label2. // Observe two metrics with same value for label1 but different value of label2.
vec.WithLabelValues("value1-0", "value2-0").Observe(1.5) vec.WithLabelValues("value1-0", "value2-0").Observe(1.5)
vec.WithLabelValues("value1-0", "value2-1").Observe(2.5) vec.WithLabelValues("value1-0", "value2-1").Observe(2.5)
vec.WithLabelValues("value1-1", "value2-0").Observe(3.5) vec.WithLabelValues("value1-1", "value2-0").Observe(3.5)
vec.WithLabelValues("value1-1", "value2-1").Observe(4.5) vec.WithLabelValues("value1-1", "value2-1").Observe(4.5)
metricName := fmt.Sprintf("%s_%s_%s", HistogramOpts.Namespace, HistogramOpts.Subsystem, HistogramOpts.Name) metricName := fmt.Sprintf("%s_%s_%s", HistogramOpts.Namespace, HistogramOpts.Subsystem, HistogramOpts.Name)
histogramVec, _ := GetHistogramVecFromGatherer(legacyregistry.DefaultGatherer, metricName, tt.lvMap) histogramVec, _ := GetHistogramVecFromGatherer(gather, metricName, tt.lvMap)
if diff := cmp.Diff(tt.wantVec, histogramVec); diff != "" { if diff := cmp.Diff(tt.wantVec, histogramVec); diff != "" {
t.Errorf("Got unexpected HistogramVec (-want +got):\n%s", diff) t.Errorf("Got unexpected HistogramVec (-want +got):\n%s", diff)
} }