Debian Codegraph @

pkg/endpoints/filters/webhook_duration.go

raw
1 /*
2 Copyright 2021 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 filters
18
19 import (
20 "context"
21 "net/http"
22 "time"
23
24 "k8s.io/apimachinery/pkg/util/sets"
25 "k8s.io/apiserver/pkg/endpoints/request"
26 "k8s.io/apiserver/pkg/endpoints/responsewriter"
27 )
28
29 var (
30 watchVerbs = sets.NewString("watch")
31 )
32
33 // WithLatencyTrackers adds a LatencyTrackers instance to the
34 // context associated with a request so that we can measure latency
35 // incurred in various components within the apiserver.
36 func WithLatencyTrackers(handler http.Handler) http.Handler {
37 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
38 ctx := req.Context()
39 requestInfo, ok := request.RequestInfoFrom(ctx)
40 if !ok {
41 handleError(w, req, http.StatusInternalServerError, nil, "no RequestInfo found in context, handler chain must be wrong")
42 return
43 }
44
45 if watchVerbs.Has(requestInfo.Verb) {
46 handler.ServeHTTP(w, req)
47 return
48 }
49
50 req = req.WithContext(request.WithLatencyTrackers(ctx))
51 w = responsewriter.WrapForHTTP1Or2(&writeLatencyTracker{
52 ResponseWriter: w,
53 ctx: req.Context(),
54 })
55
56 handler.ServeHTTP(w, req)
57 })
58 }
59
60 var _ http.ResponseWriter = &writeLatencyTracker{}
61 var _ responsewriter.UserProvidedDecorator = &writeLatencyTracker{}
62
63 type writeLatencyTracker struct {
64 http.ResponseWriter
65 ctx context.Context
66 }
67
68 func (wt *writeLatencyTracker) Unwrap() http.ResponseWriter {
69 return wt.ResponseWriter
70 }
71
72 func (wt *writeLatencyTracker) Write(bs []byte) (int, error) {
73 startedAt := time.Now()
74 defer func() {
75 request.TrackResponseWriteLatency(wt.ctx, time.Since(startedAt))
76 }()
77
78 return wt.ResponseWriter.Write(bs)
79 }