Debian Codegraph @

pkg/admission/plugin/webhook/mutating/plugin_test.go

raw
1 /*
2 Copyright 2017 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 mutating
18
19 import (
20 "context"
21 "fmt"
22 "net/url"
23 "os"
24 "reflect"
25 "strings"
26 "testing"
27
28 "github.com/stretchr/testify/assert"
29 "k8s.io/apiserver/pkg/endpoints/request"
30 clocktesting "k8s.io/utils/clock/testing"
31
32 "k8s.io/apimachinery/pkg/api/errors"
33 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
34 "k8s.io/apiserver/pkg/admission"
35 webhooktesting "k8s.io/apiserver/pkg/admission/plugin/webhook/testing"
36 auditinternal "k8s.io/apiserver/pkg/apis/audit"
37 )
38
39 // BenchmarkAdmit tests the performance cost of invoking a mutating webhook
40 func BenchmarkAdmit(b *testing.B) {
41 testServerURL := os.Getenv("WEBHOOK_TEST_SERVER_URL")
42 if len(testServerURL) == 0 {
43 b.Log("warning, WEBHOOK_TEST_SERVER_URL not set, starting in-process server, benchmarks will include webhook cost.")
44 b.Log("to run a standalone server, run:")
45 b.Log("go run k8s.io/apiserver/pkg/admission/plugin/webhook/testing/main/main.go")
46 testServer := webhooktesting.NewTestServer(b)
47 testServer.StartTLS()
48 defer testServer.Close()
49 testServerURL = testServer.URL
50 }
51
52 serverURL, err := url.ParseRequestURI(testServerURL)
53 if err != nil {
54 b.Fatalf("this should never happen? %v", err)
55 }
56
57 objectInterfaces := webhooktesting.NewObjectInterfacesForTest()
58
59 stopCh := make(chan struct{})
60 defer close(stopCh)
61
62 testCases := append(webhooktesting.NewMutatingTestCases(serverURL, "test-webhooks"),
63 webhooktesting.ConvertToMutatingTestCases(webhooktesting.NewNonMutatingTestCases(serverURL), "test-webhooks")...)
64
65 for _, tt := range testCases {
66 // For now, skip failure cases or tests that explicitly skip benchmarking
67 if !tt.ExpectAllow || tt.SkipBenchmark {
68 continue
69 }
70 b.Run(tt.Name, func(b *testing.B) {
71 wh, err := NewMutatingWebhook(nil)
72 if err != nil {
73 b.Errorf("failed to create mutating webhook: %v", err)
74 return
75 }
76
77 ns := "webhook-test"
78 client, informer := webhooktesting.NewFakeMutatingDataSource(ns, tt.Webhooks, stopCh)
79
80 wh.SetAuthenticationInfoResolverWrapper(webhooktesting.Wrapper(webhooktesting.NewAuthenticationInfoResolver(new(int32))))
81 wh.SetServiceResolver(webhooktesting.NewServiceResolver(*serverURL))
82 wh.SetExternalKubeClientSet(client)
83 wh.SetExternalKubeInformerFactory(informer)
84
85 informer.Start(stopCh)
86 informer.WaitForCacheSync(stopCh)
87
88 if err = wh.ValidateInitialization(); err != nil {
89 b.Errorf("failed to validate initialization: %v", err)
90 return
91 }
92
93 var attr admission.Attributes
94 if tt.IsCRD {
95 attr = webhooktesting.NewAttributeUnstructured(ns, tt.AdditionalLabels, tt.IsDryRun)
96 } else {
97 attr = webhooktesting.NewAttribute(ns, tt.AdditionalLabels, tt.IsDryRun)
98 }
99
100 b.ResetTimer()
101 b.RunParallel(func(pb *testing.PB) {
102 for pb.Next() {
103 wh.Admit(context.TODO(), attr, objectInterfaces)
104 }
105 })
106 })
107 }
108 }
109
110 // TestAdmit tests that MutatingWebhook#Admit works as expected
111 func TestAdmit(t *testing.T) {
112 testServer := webhooktesting.NewTestServer(t)
113 testServer.StartTLS()
114 defer testServer.Close()
115 serverURL, err := url.ParseRequestURI(testServer.URL)
116 if err != nil {
117 t.Fatalf("this should never happen? %v", err)
118 }
119
120 objectInterfaces := webhooktesting.NewObjectInterfacesForTest()
121
122 stopCh := make(chan struct{})
123 defer close(stopCh)
124
125 testCases := append(webhooktesting.NewMutatingTestCases(serverURL, "test-webhooks"),
126 webhooktesting.ConvertToMutatingTestCases(webhooktesting.NewNonMutatingTestCases(serverURL), "test-webhooks")...)
127
128 for _, tt := range testCases {
129 t.Run(tt.Name, func(t *testing.T) {
130 wh, err := NewMutatingWebhook(nil)
131 if err != nil {
132 t.Errorf("failed to create mutating webhook: %v", err)
133 return
134 }
135
136 ns := "webhook-test"
137 client, informer := webhooktesting.NewFakeMutatingDataSource(ns, tt.Webhooks, stopCh)
138
139 wh.SetAuthenticationInfoResolverWrapper(webhooktesting.Wrapper(webhooktesting.NewAuthenticationInfoResolver(new(int32))))
140 wh.SetServiceResolver(webhooktesting.NewServiceResolver(*serverURL))
141 wh.SetExternalKubeClientSet(client)
142 wh.SetExternalKubeInformerFactory(informer)
143
144 informer.Start(stopCh)
145 informer.WaitForCacheSync(stopCh)
146
147 if err = wh.ValidateInitialization(); err != nil {
148 t.Errorf("failed to validate initialization: %v", err)
149 return
150 }
151
152 var attr admission.Attributes
153 if tt.IsCRD {
154 attr = webhooktesting.NewAttributeUnstructured(ns, tt.AdditionalLabels, tt.IsDryRun)
155 } else {
156 attr = webhooktesting.NewAttribute(ns, tt.AdditionalLabels, tt.IsDryRun)
157 }
158
159 err = wh.Admit(context.TODO(), attr, objectInterfaces)
160 if tt.ExpectAllow != (err == nil) {
161 t.Errorf("expected allowed=%v, but got err=%v", tt.ExpectAllow, err)
162 }
163 if tt.ExpectLabels != nil {
164 if !reflect.DeepEqual(tt.ExpectLabels, attr.GetObject().(metav1.Object).GetLabels()) {
165 t.Errorf("expected labels '%v', but got '%v'", tt.ExpectLabels, attr.GetObject().(metav1.Object).GetLabels())
166 }
167 }
168 // ErrWebhookRejected is not an error for our purposes
169 if tt.ErrorContains != "" {
170 if err == nil || !strings.Contains(err.Error(), tt.ErrorContains) {
171 t.Errorf("expected an error saying %q, but got: %v", tt.ErrorContains, err)
172 }
173 }
174 if statusErr, isStatusErr := err.(*errors.StatusError); err != nil && !isStatusErr {
175 t.Errorf("expected a StatusError, got %T", err)
176 } else if isStatusErr {
177 if statusErr.ErrStatus.Code != tt.ExpectStatusCode {
178 t.Errorf("expected status code %d, got %d", tt.ExpectStatusCode, statusErr.ErrStatus.Code)
179 }
180 }
181 fakeAttr, ok := attr.(*webhooktesting.FakeAttributes)
182 if !ok {
183 t.Errorf("Unexpected error, failed to convert attr to webhooktesting.FakeAttributes")
184 return
185 }
186 if len(tt.ExpectAnnotations) == 0 {
187 assert.Empty(t, fakeAttr.GetAnnotations(auditinternal.LevelMetadata), tt.Name+": annotations not set as expected.")
188 } else {
189 assert.Equal(t, tt.ExpectAnnotations, fakeAttr.GetAnnotations(auditinternal.LevelMetadata), tt.Name+": annotations not set as expected.")
190 }
191 reinvocationCtx := fakeAttr.Attributes.GetReinvocationContext()
192 reinvocationCtx.SetIsReinvoke()
193 for webhook, expectReinvoke := range tt.ExpectReinvokeWebhooks {
194 shouldReinvoke := reinvocationCtx.Value(PluginName).(*webhookReinvokeContext).ShouldReinvokeWebhook(fmt.Sprintf("test-webhooks/%s/0", webhook))
195 if expectReinvoke != shouldReinvoke {
196 t.Errorf("expected reinvocationContext.ShouldReinvokeWebhook(%s)=%t, but got %t", webhook, expectReinvoke, shouldReinvoke)
197 }
198 }
199 })
200 }
201 }
202
203 // TestAdmitCachedClient tests that MutatingWebhook#Admit should cache restClient
204 func TestAdmitCachedClient(t *testing.T) {
205 testServer := webhooktesting.NewTestServer(t)
206 testServer.StartTLS()
207 defer testServer.Close()
208 serverURL, err := url.ParseRequestURI(testServer.URL)
209 if err != nil {
210 t.Fatalf("this should never happen? %v", err)
211 }
212
213 objectInterfaces := webhooktesting.NewObjectInterfacesForTest()
214
215 stopCh := make(chan struct{})
216 defer close(stopCh)
217
218 wh, err := NewMutatingWebhook(nil)
219 if err != nil {
220 t.Fatalf("Failed to create mutating webhook: %v", err)
221 }
222 wh.SetServiceResolver(webhooktesting.NewServiceResolver(*serverURL))
223
224 for _, tt := range webhooktesting.NewCachedClientTestcases(serverURL) {
225 ns := "webhook-test"
226 client, informer := webhooktesting.NewFakeMutatingDataSource(ns, webhooktesting.ConvertToMutatingWebhooks(tt.Webhooks), stopCh)
227
228 // override the webhook source. The client cache will stay the same.
229 cacheMisses := new(int32)
230 wh.SetAuthenticationInfoResolverWrapper(webhooktesting.Wrapper(webhooktesting.NewAuthenticationInfoResolver(cacheMisses)))
231 wh.SetExternalKubeClientSet(client)
232 wh.SetExternalKubeInformerFactory(informer)
233
234 informer.Start(stopCh)
235 informer.WaitForCacheSync(stopCh)
236
237 if err = wh.ValidateInitialization(); err != nil {
238 t.Errorf("%s: failed to validate initialization: %v", tt.Name, err)
239 continue
240 }
241
242 err = wh.Admit(context.TODO(), webhooktesting.NewAttribute(ns, nil, false), objectInterfaces)
243 if tt.ExpectAllow != (err == nil) {
244 t.Errorf("%s: expected allowed=%v, but got err=%v", tt.Name, tt.ExpectAllow, err)
245 }
246
247 if tt.ExpectCacheMiss && *cacheMisses == 0 {
248 t.Errorf("%s: expected cache miss, but got no AuthenticationInfoResolver call", tt.Name)
249 }
250
251 if !tt.ExpectCacheMiss && *cacheMisses > 0 {
252 t.Errorf("%s: expected client to be cached, but got %d AuthenticationInfoResolver calls", tt.Name, *cacheMisses)
253 }
254 }
255 }
256
257 // TestWebhookDuration tests that MutatingWebhook#Admit sets webhook duration in context correctly
258 func TestWebhookDuration(ts *testing.T) {
259 clk := clocktesting.FakeClock{}
260 testServer := webhooktesting.NewTestServerWithHandler(ts, webhooktesting.ClockSteppingWebhookHandler(ts, &clk))
261 testServer.StartTLS()
262 defer testServer.Close()
263 serverURL, err := url.ParseRequestURI(testServer.URL)
264 if err != nil {
265 ts.Fatalf("this should never happen? %v", err)
266 }
267
268 objectInterfaces := webhooktesting.NewObjectInterfacesForTest()
269
270 stopCh := make(chan struct{})
271 defer close(stopCh)
272
273 for _, test := range webhooktesting.NewValidationDurationTestCases(serverURL) {
274 ts.Run(test.Name, func(t *testing.T) {
275 ctx := context.TODO()
276 if test.InitContext {
277 ctx = request.WithLatencyTrackersAndCustomClock(ctx, &clk)
278 }
279 wh, err := NewMutatingWebhook(nil)
280 if err != nil {
281 t.Errorf("failed to create mutating webhook: %v", err)
282 return
283 }
284
285 ns := "webhook-test"
286 client, informer := webhooktesting.NewFakeMutatingDataSource(ns, webhooktesting.ConvertToMutatingWebhooks(test.Webhooks), stopCh)
287
288 wh.SetAuthenticationInfoResolverWrapper(webhooktesting.Wrapper(webhooktesting.NewAuthenticationInfoResolver(new(int32))))
289 wh.SetServiceResolver(webhooktesting.NewServiceResolver(*serverURL))
290 wh.SetExternalKubeClientSet(client)
291 wh.SetExternalKubeInformerFactory(informer)
292
293 informer.Start(stopCh)
294 informer.WaitForCacheSync(stopCh)
295
296 if err = wh.ValidateInitialization(); err != nil {
297 t.Errorf("failed to validate initialization: %v", err)
298 return
299 }
300
301 _ = wh.Admit(ctx, webhooktesting.NewAttribute(ns, nil, test.IsDryRun), objectInterfaces)
302 wd, ok := request.LatencyTrackersFrom(ctx)
303 if !ok {
304 if test.InitContext {
305 t.Errorf("expected webhook duration to be initialized")
306 }
307 return
308 }
309 if !test.InitContext {
310 t.Errorf("expected webhook duration to not be initialized")
311 return
312 }
313 if wd.MutatingWebhookTracker.GetLatency() != test.ExpectedDurationSum {
314 t.Errorf("expected admit duration %q got %q", test.ExpectedDurationSum, wd.MutatingWebhookTracker.GetLatency())
315 }
316 if wd.ValidatingWebhookTracker.GetLatency() != 0 {
317 t.Errorf("expected validate duraion to be equal to 0 got %q", wd.ValidatingWebhookTracker.GetLatency())
318 }
319 })
320 }
321 }