From 220f45b7bff73b23071fd1fb52e8ec88318980b7 Mon Sep 17 00:00:00 2001 From: zhouhaibing089 Date: Mon, 1 Apr 2024 21:45:50 -0700 Subject: [PATCH] webhook: register metrics only with default stats reporter This is a followup from [knative/pkg#2931][1]. RegisterMetrics may register unwanted metrics if the default stats reporter is not used. [1]: https://github.com/knative/pkg/pull/2931 --- injection/sharedmain/main.go | 8 -------- webhook/webhook.go | 7 +++++++ 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/injection/sharedmain/main.go b/injection/sharedmain/main.go index 79c42c201..2703e4b7f 100644 --- a/injection/sharedmain/main.go +++ b/injection/sharedmain/main.go @@ -289,14 +289,6 @@ func MainWithConfig(ctx context.Context, component string, cfg *rest.Config, cto // and pass them in. var wh *webhook.Webhook if len(webhooks) > 0 { - // Register webhook metrics - opts := webhook.GetOptions(ctx) - if opts != nil { - webhook.RegisterMetrics(opts.StatsReporterOptions...) - } else { - webhook.RegisterMetrics() - } - wh, err = webhook.New(ctx, webhooks) if err != nil { logger.Fatalw("Failed to create webhook", zap.Error(err)) diff --git a/webhook/webhook.go b/webhook/webhook.go index d8842df35..d507bf55f 100644 --- a/webhook/webhook.go +++ b/webhook/webhook.go @@ -25,6 +25,7 @@ import ( "log" "net" "net/http" + "sync" "time" // Injection stuff @@ -40,6 +41,10 @@ import ( "knative.dev/pkg/system" ) +var ( + metricsOnce sync.Once +) + // Options contains the configuration for the webhook type Options struct { // TLSMinVersion contains the minimum TLS version that is acceptable to communicate with the API server. @@ -147,6 +152,8 @@ func New( logger := logging.FromContext(ctx) if opts.StatsReporter == nil { + // Register webhook metrics + metricsOnce.Do(func() { RegisterMetrics(opts.StatsReporterOptions...) }) reporter, err := NewStatsReporter(opts.StatsReporterOptions...) if err != nil { return nil, err