Return an error if metric cannot be registered

`prometheus.MustRegister` panics if the metric cannot be registered.
Instead, use `prometheus.Register` and return the error if the metric
cannot be registered.

Also, add tests for `RegisterMetricAndTrackRateLimiterUsage`.

Signed-off-by: Ferran Rodenas <frodenas@gmail.com>
This commit is contained in:
Ferran Rodenas 2017-10-08 13:35:43 +02:00
parent 6e2249b784
commit a334eb1a49
3 changed files with 67 additions and 1 deletions

View File

@ -3,6 +3,7 @@ package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
@ -16,6 +17,15 @@ go_library(
],
)
go_test(
name = "go_default_test",
srcs = ["util_test.go"],
library = ":go_default_library",
deps = [
"//vendor/k8s.io/client-go/util/flowcontrol:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),

View File

@ -51,7 +51,9 @@ func registerRateLimiterMetric(ownerName string) error {
Help: fmt.Sprintf("A metric measuring the saturation of the rate limiter for %v", ownerName),
})
rateLimiterMetrics[ownerName] = metric
prometheus.MustRegister(metric)
if err := prometheus.Register(metric); err != nil {
return fmt.Errorf("error registering rate limiter usage metric: %v", err)
}
return nil
}

View File

@ -0,0 +1,54 @@
/*
Copyright 2017 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 metrics
import (
"strings"
"testing"
"k8s.io/client-go/util/flowcontrol"
)
func TestRegisterMetricAndTrackRateLimiterUsage(t *testing.T) {
testCases := []struct {
ownerName string
rateLimiter flowcontrol.RateLimiter
err string
}{
{
ownerName: "owner_name",
rateLimiter: flowcontrol.NewTokenBucketRateLimiter(1, 1),
err: "",
},
{
ownerName: "invalid-owner-name",
rateLimiter: flowcontrol.NewTokenBucketRateLimiter(1, 1),
err: "error registering rate limiter usage metric",
},
}
for i, tc := range testCases {
e := RegisterMetricAndTrackRateLimiterUsage(tc.ownerName, tc.rateLimiter)
if e != nil {
if tc.err == "" {
t.Errorf("[%d] unexpected error: %v", i, e)
} else if !strings.Contains(e.Error(), tc.err) {
t.Errorf("[%d] expected an error containing %q: %v", i, tc.err, e)
}
}
}
}