Debian Codegraph @

pkg/authorization/metrics/metrics.go

raw
1 /*
2 Copyright 2024 The Kubernetes 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 metrics
18
19 import (
20 "context"
21 "sync"
22
23 "k8s.io/apiserver/pkg/authorization/authorizer"
24 "k8s.io/component-base/metrics"
25 "k8s.io/component-base/metrics/legacyregistry"
26 )
27
28 const (
29 namespace = "apiserver"
30 subsystem = "authorization"
31 )
32
33 var (
34 authorizationDecisionsTotal = metrics.NewCounterVec(
35 &metrics.CounterOpts{
36 Namespace: namespace,
37 Subsystem: subsystem,
38 Name: "decisions_total",
39 Help: "Total number of terminal decisions made by an authorizer split by authorizer type, name, and decision.",
40 StabilityLevel: metrics.ALPHA,
41 },
42 []string{"type", "name", "decision"},
43 )
44 )
45
46 var registerMetrics sync.Once
47
48 func RegisterMetrics() {
49 registerMetrics.Do(func() {
50 legacyregistry.MustRegister(authorizationDecisionsTotal)
51 })
52 }
53
54 func ResetMetricsForTest() {
55 authorizationDecisionsTotal.Reset()
56 }
57
58 func RecordAuthorizationDecision(authorizerType, authorizerName, decision string) {
59 authorizationDecisionsTotal.WithLabelValues(authorizerType, authorizerName, decision).Inc()
60 }
61
62 func InstrumentedAuthorizer(authorizerType string, authorizerName string, delegate authorizer.Authorizer) authorizer.Authorizer {
63 RegisterMetrics()
64 return &instrumentedAuthorizer{
65 authorizerType: string(authorizerType),
66 authorizerName: authorizerName,
67 delegate: delegate,
68 }
69 }
70
71 type instrumentedAuthorizer struct {
72 authorizerType string
73 authorizerName string
74 delegate authorizer.Authorizer
75 }
76
77 func (a *instrumentedAuthorizer) Authorize(ctx context.Context, attributes authorizer.Attributes) (authorizer.Decision, string, error) {
78 decision, reason, err := a.delegate.Authorize(ctx, attributes)
79 switch decision {
80 case authorizer.DecisionNoOpinion:
81 // non-terminal, not reported
82 case authorizer.DecisionAllow:
83 // matches SubjectAccessReview status.allowed field name
84 RecordAuthorizationDecision(a.authorizerType, a.authorizerName, "allowed")
85 case authorizer.DecisionDeny:
86 // matches SubjectAccessReview status.denied field name
87 RecordAuthorizationDecision(a.authorizerType, a.authorizerName, "denied")
88 default:
89 RecordAuthorizationDecision(a.authorizerType, a.authorizerName, "unknown")
90 }
91 return decision, reason, err
92 }