knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/webhook/metrics.go (about) 1 /* 2 Copyright 2025 The Knative Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package webhook 18 19 import ( 20 "context" 21 "time" 22 23 "go.opentelemetry.io/otel" 24 "go.opentelemetry.io/otel/metric" 25 26 "knative.dev/pkg/observability/attributekey" 27 ) 28 29 const ( 30 scopeName = "knative.dev/pkg/webhook" 31 32 WebhookTypeAdmission = "admission" 33 WebhookTypeDefaulting = "defaulting" 34 WebhookTypeValidation = "validation" 35 WebhookTypeConversion = "conversion" 36 ) 37 38 var ( 39 // WebhookType is an attribute that specifies whether the type of webhook is an admission 40 // eg. (defaulting/validation) or conversion 41 WebhookTypeAttr = attributekey.String("kn.webhook.type") 42 43 GroupAttr = attributekey.String("kn.webhook.resource.group") 44 VersionAttr = attributekey.String("kn.webhook.resource.version") 45 KindAttr = attributekey.String("kn.webhook.resource.kind") 46 SubresourceAttr = attributekey.String("kn.webhook.subresource") 47 OperationAttr = attributekey.String("kn.webhook.operation.type") 48 StatusAttr = attributekey.String("kn.webhook.operation.status") 49 ) 50 51 type metrics struct { 52 handlerDuration metric.Float64Histogram 53 } 54 55 func newMetrics(o Options) *metrics { 56 var ( 57 m metrics 58 err error 59 provider = o.MeterProvider 60 ) 61 62 if provider == nil { 63 provider = otel.GetMeterProvider() 64 } 65 66 meter := provider.Meter(scopeName) 67 68 m.handlerDuration, err = meter.Float64Histogram( 69 "kn.webhook.handler.duration", 70 metric.WithDescription("The duration of task execution."), 71 metric.WithUnit("s"), 72 metric.WithExplicitBucketBoundaries(0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10), 73 ) 74 if err != nil { 75 panic(err) 76 } 77 78 return &m 79 } 80 81 func (m *metrics) recordHandlerDuration(ctx context.Context, d time.Duration, ro ...metric.RecordOption) { 82 elapsedTime := float64(d) / float64(time.Second) 83 m.handlerDuration.Record(ctx, elapsedTime, ro...) 84 }