Debian Codegraph @

pkg/endpoints/discovery/aggregated/handler_test.go

raw
1 /*
2 Copyright 2022 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 aggregated_test
18
19 import (
20 "encoding/json"
21 "fmt"
22 "math/rand"
23 "net/http"
24 "net/http/httptest"
25
26 "sort"
27 "strconv"
28 "strings"
29 "sync"
30 "testing"
31
32 "github.com/stretchr/testify/assert"
33 "github.com/stretchr/testify/require"
34 "sigs.k8s.io/randfill"
35
36 apidiscoveryv2 "k8s.io/api/apidiscovery/v2"
37 apidiscoveryv2beta1 "k8s.io/api/apidiscovery/v2beta1"
38 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
39 "k8s.io/apimachinery/pkg/runtime"
40 "k8s.io/apimachinery/pkg/runtime/schema"
41 runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer"
42 utilruntime "k8s.io/apimachinery/pkg/util/runtime"
43 "k8s.io/apimachinery/pkg/version"
44 apidiscoveryv2conversion "k8s.io/apiserver/pkg/apis/apidiscovery/v2"
45 discoveryendpoint "k8s.io/apiserver/pkg/endpoints/discovery/aggregated"
46 genericfeatures "k8s.io/apiserver/pkg/features"
47 utilfeature "k8s.io/apiserver/pkg/util/feature"
48 featuregatetesting "k8s.io/component-base/featuregate/testing"
49 )
50
51 var scheme = runtime.NewScheme()
52 var codecs = runtimeserializer.NewCodecFactory(scheme)
53
54 const discoveryPath = "/apis"
55
56 func init() {
57 utilruntime.Must(apidiscoveryv2.AddToScheme(scheme))
58 utilruntime.Must(apidiscoveryv2beta1.AddToScheme(scheme))
59 // Register conversion for apidiscovery
60 utilruntime.Must(apidiscoveryv2conversion.RegisterConversions(scheme))
61 codecs = runtimeserializer.NewCodecFactory(scheme)
62 }
63
64 func fuzzAPIGroups(atLeastNumGroups, maxNumGroups int, seed int64) apidiscoveryv2.APIGroupDiscoveryList {
65 fuzzer := randfill.NewWithSeed(seed)
66 fuzzer.NumElements(atLeastNumGroups, maxNumGroups)
67 fuzzer.NilChance(0)
68 fuzzer.Funcs(func(o *apidiscoveryv2.APIGroupDiscovery, c randfill.Continue) {
69 c.FillNoCustom(o)
70
71 // The ResourceManager will just not serve the group if its versions
72 // list is empty
73 atLeastOne := apidiscoveryv2.APIVersionDiscovery{}
74 c.Fill(&atLeastOne)
75 o.Versions = append(o.Versions, atLeastOne)
76 sort.Slice(o.Versions[:], func(i, j int) bool {
77 return version.CompareKubeAwareVersionStrings(o.Versions[i].Version, o.Versions[j].Version) > 0
78 })
79
80 o.TypeMeta = metav1.TypeMeta{}
81 var name string
82 c.Fill(&name)
83 o.ObjectMeta = metav1.ObjectMeta{
84 Name: name,
85 }
86 })
87
88 var apis []apidiscoveryv2.APIGroupDiscovery
89 fuzzer.Fill(&apis)
90 sort.Slice(apis[:], func(i, j int) bool {
91 return apis[i].Name < apis[j].Name
92 })
93
94 return apidiscoveryv2.APIGroupDiscoveryList{
95 TypeMeta: metav1.TypeMeta{
96 Kind: "APIGroupDiscoveryList",
97 APIVersion: "apidiscovery.k8s.io/v2",
98 },
99 Items: apis,
100 }
101 }
102
103 func fetchPathV2Beta1(handler http.Handler, acceptPrefix string, path string, etag string) (*http.Response, []byte, *apidiscoveryv2beta1.APIGroupDiscoveryList) {
104 acceptSuffix := ";g=apidiscovery.k8s.io;v=v2beta1;as=APIGroupDiscoveryList"
105 r, bytes := fetchPathHelper(handler, acceptPrefix+acceptSuffix, path, etag)
106 var decoded *apidiscoveryv2beta1.APIGroupDiscoveryList
107 if len(bytes) > 0 {
108 decoded = &apidiscoveryv2beta1.APIGroupDiscoveryList{}
109 err := runtime.DecodeInto(codecs.UniversalDecoder(), bytes, decoded)
110 if err != nil {
111 panic(fmt.Sprintf("failed to decode response: %v", err))
112 }
113
114 }
115 return r, bytes, decoded
116 }
117
118 func fetchPath(handler http.Handler, acceptPrefix string, path string, etag string) (*http.Response, []byte, *apidiscoveryv2.APIGroupDiscoveryList) {
119 acceptSuffix := ";g=apidiscovery.k8s.io;v=v2;as=APIGroupDiscoveryList,"
120 acceptSuffixV2Beta1 := ";g=apidiscovery.k8s.io;v=v2beta1;as=APIGroupDiscoveryList,"
121 r, bytes := fetchPathHelper(handler, acceptPrefix+acceptSuffix+","+acceptPrefix+acceptSuffixV2Beta1, path, etag)
122 var decoded *apidiscoveryv2.APIGroupDiscoveryList
123 if len(bytes) > 0 {
124 decoded = &apidiscoveryv2.APIGroupDiscoveryList{}
125 err := runtime.DecodeInto(codecs.UniversalDecoder(), bytes, decoded)
126 if err != nil {
127 panic(fmt.Sprintf("failed to decode response: %v", err))
128 }
129 }
130 return r, bytes, decoded
131 }
132
133 func fetchPathHelper(handler http.Handler, accept string, path string, etag string) (*http.Response, []byte) {
134 // Expect json-formatted apis group list
135 w := httptest.NewRecorder()
136 req := httptest.NewRequest("GET", discoveryPath, nil)
137
138 // Ask for JSON response
139 req.Header.Set("Accept", accept)
140
141 if etag != "" {
142 // Quote provided etag if unquoted
143 quoted := etag
144 if !strings.HasPrefix(etag, "\"") {
145 quoted = strconv.Quote(etag)
146 }
147 req.Header.Set("If-None-Match", quoted)
148 }
149
150 handler.ServeHTTP(w, req)
151
152 bytes := w.Body.Bytes()
153 return w.Result(), bytes
154 }
155
156 // Add all builtin APIServices to the manager and check the output
157 func TestBasicResponse(t *testing.T) {
158 manager := discoveryendpoint.NewResourceManager("apis")
159
160 apis := fuzzAPIGroups(1, 3, 10)
161 manager.SetGroups(apis.Items)
162
163 response, body, decoded := fetchPath(manager, "application/json", discoveryPath, "")
164
165 jsonFormatted, err := json.Marshal(&apis)
166 require.NoError(t, err, "json marshal should always succeed")
167
168 assert.Equal(t, http.StatusOK, response.StatusCode, "response should be 200 OK")
169 assert.Equal(t, "application/json;g=apidiscovery.k8s.io;v=v2;as=APIGroupDiscoveryList", response.Header.Get("Content-Type"), "Content-Type response header should be as requested in Accept header if supported")
170 assert.NotEmpty(t, response.Header.Get("ETag"), "E-Tag should be set")
171
172 assert.NoError(t, err, "decode should always succeed")
173 assert.EqualValues(t, &apis, decoded, "decoded value should equal input")
174 assert.Equal(t, string(jsonFormatted)+"\n", string(body), "response should be the api group list")
175 }
176
177 // Test that protobuf is outputted correctly
178 func TestBasicResponseProtobuf(t *testing.T) {
179 manager := discoveryendpoint.NewResourceManager("apis")
180
181 apis := fuzzAPIGroups(1, 3, 10)
182 manager.SetGroups(apis.Items)
183
184 response, _, decoded := fetchPath(manager, "application/vnd.kubernetes.protobuf", discoveryPath, "")
185 assert.Equal(t, http.StatusOK, response.StatusCode, "response should be 200 OK")
186 assert.Equal(t, "application/vnd.kubernetes.protobuf;g=apidiscovery.k8s.io;v=v2;as=APIGroupDiscoveryList", response.Header.Get("Content-Type"), "Content-Type response header should be as requested in Accept header if supported")
187 assert.NotEmpty(t, response.Header.Get("ETag"), "E-Tag should be set")
188 assert.EqualValues(t, &apis, decoded, "decoded value should equal input")
189 }
190
191 // V2Beta1 should still be served
192 func TestV2Beta1SkewSupport(t *testing.T) {
193 featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.AggregatedDiscoveryRemoveBetaType, false)
194 manager := discoveryendpoint.NewResourceManager("apis")
195
196 apis := fuzzAPIGroups(1, 3, 10)
197 manager.SetGroups(apis.Items)
198
199 converted, err := scheme.ConvertToVersion(&apis, &schema.GroupVersion{Group: "apidiscovery.k8s.io", Version: "v2beta1"})
200 if err != nil {
201 t.Fatal(err)
202 }
203
204 v2beta1apis := converted.(*apidiscoveryv2beta1.APIGroupDiscoveryList)
205
206 response, body, decoded := fetchPathV2Beta1(manager, "application/json", discoveryPath, "")
207
208 jsonFormatted, err := json.Marshal(v2beta1apis)
209 require.NoError(t, err, "json marshal should always succeed")
210
211 assert.Equal(t, http.StatusOK, response.StatusCode, "response should be 200 OK")
212 assert.Equal(t, "application/json;g=apidiscovery.k8s.io;v=v2beta1;as=APIGroupDiscoveryList", response.Header.Get("Content-Type"), "Content-Type response header should be as requested in Accept header if supported")
213 assert.NotEmpty(t, response.Header.Get("ETag"), "E-Tag should be set")
214
215 assert.NoError(t, err, "decode should always succeed")
216 assert.EqualValues(t, v2beta1apis, decoded, "decoded value should equal input")
217 assert.Equal(t, string(jsonFormatted)+"\n", string(body), "response should be the api group list")
218 }
219
220 // Test that an etag associated with the service only depends on the apiresources
221 // e.g.: Multiple services with the same contents should have the same etag.
222 func TestEtagConsistent(t *testing.T) {
223 // Create 2 managers, add a bunch of services to each
224 manager1 := discoveryendpoint.NewResourceManager("apis")
225 manager2 := discoveryendpoint.NewResourceManager("apis")
226
227 apis := fuzzAPIGroups(1, 3, 11)
228 manager1.SetGroups(apis.Items)
229 manager2.SetGroups(apis.Items)
230
231 // Make sure etag of each is the same
232 res1_initial, _, _ := fetchPath(manager1, "application/json", discoveryPath, "")
233 res2_initial, _, _ := fetchPath(manager2, "application/json", discoveryPath, "")
234
235 assert.NotEmpty(t, res1_initial.Header.Get("ETag"), "Etag should be populated")
236 assert.NotEmpty(t, res2_initial.Header.Get("ETag"), "Etag should be populated")
237 assert.Equal(t, res1_initial.Header.Get("ETag"), res2_initial.Header.Get("ETag"), "etag should be deterministic")
238
239 // Then add one service to only one.
240 // Make sure etag is changed, but other is the same
241 apis = fuzzAPIGroups(1, 1, 11)
242 for _, group := range apis.Items {
243 for _, version := range group.Versions {
244 manager1.AddGroupVersion(group.Name, version)
245 }
246 }
247
248 res1_addedToOne, _, _ := fetchPath(manager1, "application/json", discoveryPath, "")
249 res2_addedToOne, _, _ := fetchPath(manager2, "application/json", discoveryPath, "")
250
251 assert.NotEmpty(t, res1_addedToOne.Header.Get("ETag"), "Etag should be populated")
252 assert.NotEmpty(t, res2_addedToOne.Header.Get("ETag"), "Etag should be populated")
253 assert.NotEqual(t, res1_initial.Header.Get("ETag"), res1_addedToOne.Header.Get("ETag"), "ETag should be changed since version was added")
254 assert.Equal(t, res2_initial.Header.Get("ETag"), res2_addedToOne.Header.Get("ETag"), "ETag should be unchanged since data was unchanged")
255
256 // Then add service to other one
257 // Make sure etag is the same
258 for _, group := range apis.Items {
259 for _, version := range group.Versions {
260 manager2.AddGroupVersion(group.Name, version)
261 }
262 }
263
264 res1_addedToBoth, _, _ := fetchPath(manager1, "application/json", discoveryPath, "")
265 res2_addedToBoth, _, _ := fetchPath(manager2, "application/json", discoveryPath, "")
266
267 assert.NotEmpty(t, res1_addedToOne.Header.Get("ETag"), "Etag should be populated")
268 assert.NotEmpty(t, res2_addedToOne.Header.Get("ETag"), "Etag should be populated")
269 assert.Equal(t, res1_addedToBoth.Header.Get("ETag"), res2_addedToBoth.Header.Get("ETag"), "ETags should be equal since content is equal")
270 assert.NotEqual(t, res2_initial.Header.Get("ETag"), res2_addedToBoth.Header.Get("ETag"), "ETag should be changed since data was changed")
271
272 // Remove the group version from both. Initial E-Tag should be restored
273 for _, group := range apis.Items {
274 for _, version := range group.Versions {
275 manager1.RemoveGroupVersion(metav1.GroupVersion{
276 Group: group.Name,
277 Version: version.Version,
278 })
279 manager2.RemoveGroupVersion(metav1.GroupVersion{
280 Group: group.Name,
281 Version: version.Version,
282 })
283 }
284 }
285
286 res1_removeFromBoth, _, _ := fetchPath(manager1, "application/json", discoveryPath, "")
287 res2_removeFromBoth, _, _ := fetchPath(manager2, "application/json", discoveryPath, "")
288
289 assert.NotEmpty(t, res1_addedToOne.Header.Get("ETag"), "Etag should be populated")
290 assert.NotEmpty(t, res2_addedToOne.Header.Get("ETag"), "Etag should be populated")
291 assert.Equal(t, res1_removeFromBoth.Header.Get("ETag"), res2_removeFromBoth.Header.Get("ETag"), "ETags should be equal since content is equal")
292 assert.Equal(t, res1_initial.Header.Get("ETag"), res1_removeFromBoth.Header.Get("ETag"), "ETag should be equal to initial value since added content was removed")
293 }
294
295 // Test that if a request comes in with an If-None-Match header with an incorrect
296 // E-Tag, that fresh content is returned.
297 func TestEtagNonMatching(t *testing.T) {
298 manager := discoveryendpoint.NewResourceManager("apis")
299 apis := fuzzAPIGroups(1, 3, 12)
300 manager.SetGroups(apis.Items)
301
302 // fetch the document once
303 initial, _, _ := fetchPath(manager, "application/json", discoveryPath, "")
304 assert.NotEmpty(t, initial.Header.Get("ETag"), "ETag should be populated")
305
306 // Send another request with a wrong e-tag. The same response should
307 // get sent again
308 second, _, _ := fetchPath(manager, "application/json", discoveryPath, "wrongetag")
309
310 assert.Equal(t, http.StatusOK, initial.StatusCode, "response should be 200 OK")
311 assert.Equal(t, http.StatusOK, second.StatusCode, "response should be 200 OK")
312 assert.Equal(t, initial.Header.Get("ETag"), second.Header.Get("ETag"), "ETag of both requests should be equal")
313 }
314
315 // Test that if a request comes in with an If-None-Match header with a correct
316 // E-Tag, that 304 Not Modified is returned
317 func TestEtagMatching(t *testing.T) {
318 manager := discoveryendpoint.NewResourceManager("apis")
319 apis := fuzzAPIGroups(1, 3, 12)
320 manager.SetGroups(apis.Items)
321
322 // fetch the document once
323 initial, initialBody, _ := fetchPath(manager, "application/json", discoveryPath, "")
324 assert.NotEmpty(t, initial.Header.Get("ETag"), "ETag should be populated")
325 assert.NotEmpty(t, initialBody, "body should not be empty")
326
327 // Send another request with a wrong e-tag. The same response should
328 // get sent again
329 second, secondBody, _ := fetchPath(manager, "application/json", discoveryPath, initial.Header.Get("ETag"))
330
331 assert.Equal(t, http.StatusOK, initial.StatusCode, "initial response should be 200 OK")
332 assert.Equal(t, http.StatusNotModified, second.StatusCode, "second response should be 304 Not Modified")
333 assert.Equal(t, initial.Header.Get("ETag"), second.Header.Get("ETag"), "ETag of both requests should be equal")
334 assert.Empty(t, secondBody, "body should be empty when returning 304 Not Modified")
335 }
336
337 // Test that if a request comes in with an If-None-Match header with an old
338 // E-Tag, that fresh content is returned
339 func TestEtagOutdated(t *testing.T) {
340 manager := discoveryendpoint.NewResourceManager("apis")
341 apis := fuzzAPIGroups(1, 3, 15)
342 manager.SetGroups(apis.Items)
343
344 // fetch the document once
345 initial, initialBody, _ := fetchPath(manager, "application/json", discoveryPath, "")
346 assert.NotEmpty(t, initial.Header.Get("ETag"), "ETag should be populated")
347 assert.NotEmpty(t, initialBody, "body should not be empty")
348
349 // Then add some services so the etag changes
350 apis = fuzzAPIGroups(1, 3, 14)
351 for _, group := range apis.Items {
352 for _, version := range group.Versions {
353 manager.AddGroupVersion(group.Name, version)
354 }
355 }
356
357 // Send another request with the old e-tag. Response should not be 304 Not Modified
358 second, secondBody, _ := fetchPath(manager, "application/json", discoveryPath, initial.Header.Get("ETag"))
359
360 assert.Equal(t, http.StatusOK, initial.StatusCode, "initial response should be 200 OK")
361 assert.Equal(t, http.StatusOK, second.StatusCode, "second response should be 304 Not Modified")
362 assert.NotEqual(t, initial.Header.Get("ETag"), second.Header.Get("ETag"), "ETag of both requests should be unequal since contents differ")
363 assert.NotEmpty(t, secondBody, "body should be not empty when returning 304 Not Modified")
364 }
365
366 // Test that an api service can be added or removed
367 func TestAddRemove(t *testing.T) {
368 manager := discoveryendpoint.NewResourceManager("apis")
369 apis := fuzzAPIGroups(1, 3, 15)
370 for _, group := range apis.Items {
371 for _, version := range group.Versions {
372 manager.AddGroupVersion(group.Name, version)
373 }
374 }
375
376 _, _, initialDocument := fetchPath(manager, "application/json", discoveryPath, "")
377
378 for _, group := range apis.Items {
379 for _, version := range group.Versions {
380 manager.RemoveGroupVersion(metav1.GroupVersion{
381 Group: group.Name,
382 Version: version.Version,
383 })
384 }
385 }
386
387 _, _, secondDocument := fetchPath(manager, "application/json", discoveryPath, "")
388
389 require.NotNil(t, initialDocument, "initial document should parse")
390 require.NotNil(t, secondDocument, "second document should parse")
391 assert.Len(t, initialDocument.Items, len(apis.Items), "initial document should have set number of groups")
392 assert.Empty(t, secondDocument.Items, "second document should have no groups")
393 }
394
395 // Show that updating an existing service replaces and does not add the entry
396 // and instead replaces it
397 func TestUpdateService(t *testing.T) {
398 manager := discoveryendpoint.NewResourceManager("apis")
399 apis := fuzzAPIGroups(1, 3, 15)
400 for _, group := range apis.Items {
401 for _, version := range group.Versions {
402 manager.AddGroupVersion(group.Name, version)
403 }
404 }
405
406 _, _, initialDocument := fetchPath(manager, "application/json", discoveryPath, "")
407
408 assert.Equal(t, initialDocument, &apis, "should have returned expected document")
409
410 b, err := json.Marshal(apis)
411 if err != nil {
412 t.Error(err)
413 }
414 var newapis apidiscoveryv2.APIGroupDiscoveryList
415 err = json.Unmarshal(b, &newapis)
416 if err != nil {
417 t.Error(err)
418 }
419
420 newapis.Items[0].Versions[0].Resources[0].Resource = "changed a resource name!"
421 for _, group := range newapis.Items {
422 for _, version := range group.Versions {
423 manager.AddGroupVersion(group.Name, version)
424 }
425 }
426
427 _, _, secondDocument := fetchPath(manager, "application/json", discoveryPath, "")
428 assert.Equal(t, secondDocument, &newapis, "should have returned expected document")
429 assert.NotEqual(t, secondDocument, initialDocument, "should have returned expected document")
430 }
431
432 func TestMultipleSources(t *testing.T) {
433 type pair struct {
434 manager discoveryendpoint.ResourceManager
435 apis apidiscoveryv2.APIGroupDiscoveryList
436 }
437
438 pairs := []pair{}
439
440 defaultManager := discoveryendpoint.NewResourceManager("apis")
441 for i := 0; i < 10; i++ {
442 name := discoveryendpoint.Source(100 * i)
443 manager := defaultManager.WithSource(name)
444 apis := fuzzAPIGroups(1, 3, int64(15+i))
445
446 // Give the groups deterministic names
447 for i := range apis.Items {
448 apis.Items[i].Name = fmt.Sprintf("%v.%v.com", i, name)
449 }
450
451 pairs = append(pairs, pair{manager, apis})
452 }
453
454 expectedResult := []apidiscoveryv2.APIGroupDiscovery{}
455
456 groupCounter := 0
457 for _, p := range pairs {
458 for gi, g := range p.apis.Items {
459 for vi, v := range g.Versions {
460 p.manager.AddGroupVersion(g.Name, v)
461
462 // Use index for priority so we dont have to do any sorting
463 // Use negative index since it is sorted descending
464 p.manager.SetGroupVersionPriority(metav1.GroupVersion{Group: g.Name, Version: v.Version}, -gi-groupCounter, -vi)
465 }
466
467 expectedResult = append(expectedResult, g)
468 }
469
470 groupCounter += len(p.apis.Items)
471 }
472
473 // Show discovery document is what we expect
474 _, _, initialDocument := fetchPath(defaultManager, "application/json", discoveryPath, "")
475
476 require.Len(t, initialDocument.Items, len(expectedResult))
477 require.Equal(t, expectedResult, initialDocument.Items)
478 }
479
480 // Shows that if you have multiple sources including Default source using
481 // with the same group name the groups added by the "Default" source are used
482 func TestSourcePrecedence(t *testing.T) {
483 defaultManager := discoveryendpoint.NewResourceManager("apis")
484 otherManager := defaultManager.WithSource(500)
485 apis := fuzzAPIGroups(1, 3, int64(15))
486 for _, g := range apis.Items {
487 for i, v := range g.Versions {
488 v.Freshness = apidiscoveryv2.DiscoveryFreshnessCurrent
489 g.Versions[i] = v
490 otherManager.AddGroupVersion(g.Name, v)
491 }
492 }
493
494 _, _, initialDocument := fetchPath(defaultManager, "application/json", discoveryPath, "")
495 require.Equal(t, apis.Items, initialDocument.Items)
496
497 // Add the first groupversion under default.
498 // No versions should appear in discovery document except this one
499 overrideVersion := initialDocument.Items[0].Versions[0]
500 overrideVersion.Freshness = apidiscoveryv2.DiscoveryFreshnessStale
501 defaultManager.AddGroupVersion(initialDocument.Items[0].Name, overrideVersion)
502
503 _, _, maskedDocument := fetchPath(defaultManager, "application/json", discoveryPath, "")
504 masked := initialDocument.DeepCopy()
505 masked.Items[0].Versions[0].Freshness = apidiscoveryv2.DiscoveryFreshnessStale
506
507 require.Equal(t, masked.Items, maskedDocument.Items)
508
509 // Wipe out default group. The other versions from the other group should now
510 // appear since the group is not being overridden by defaults ource
511 defaultManager.RemoveGroup(apis.Items[0].Name)
512
513 _, _, resetDocument := fetchPath(defaultManager, "application/json", discoveryPath, "")
514 require.Equal(t, resetDocument.Items, initialDocument.Items)
515 }
516
517 // Show the discovery manager is capable of serving requests to multiple users
518 // with unchanging data
519 func TestConcurrentRequests(t *testing.T) {
520 manager := discoveryendpoint.NewResourceManager("apis")
521 apis := fuzzAPIGroups(1, 3, 15)
522 manager.SetGroups(apis.Items)
523
524 waitGroup := sync.WaitGroup{}
525
526 numReaders := 100
527 numRequestsPerReader := 100
528
529 // Spawn a bunch of readers that will keep sending requests to the server
530 for i := 0; i < numReaders; i++ {
531 waitGroup.Add(1)
532 go func() {
533 defer waitGroup.Done()
534 etag := ""
535 for j := 0; j < numRequestsPerReader; j++ {
536 usedEtag := etag
537 if j%2 == 0 {
538 // Disable use of etag for every second request
539 usedEtag = ""
540 }
541 response, body, document := fetchPath(manager, "application/json", discoveryPath, usedEtag)
542
543 if usedEtag != "" {
544 assert.Equal(t, http.StatusNotModified, response.StatusCode, "response should be Not Modified if etag was used")
545 assert.Empty(t, body, "body should be empty if etag used")
546 } else {
547 assert.Equal(t, http.StatusOK, response.StatusCode, "response should be OK if etag was unused")
548 assert.Equal(t, &apis, document, "document should be equal")
549 }
550
551 etag = response.Header.Get("ETag")
552 }
553 }()
554 }
555 waitGroup.Wait()
556 }
557
558 // Show the handler is capable of serving many concurrent readers and many
559 // concurrent writers without tripping up. Good to run with go '-race' detector
560 // since there are not many "correctness" checks
561 func TestAbuse(t *testing.T) {
562 manager := discoveryendpoint.NewResourceManager("apis")
563
564 numReaders := 100
565 numRequestsPerReader := 1000
566
567 numWriters := 10
568 numWritesPerWriter := 1000
569
570 waitGroup := sync.WaitGroup{}
571
572 // Spawn a bunch of writers that randomly add groups, remove groups, and
573 // reset the list of groups
574 for i := 0; i < numWriters; i++ {
575 source := rand.NewSource(int64(i))
576
577 waitGroup.Add(1)
578 go func() {
579 defer waitGroup.Done()
580
581 // track list of groups we've added so that we can remove them
582 // randomly
583 var addedGroups []metav1.GroupVersion
584
585 for j := 0; j < numWritesPerWriter; j++ {
586 switch source.Int63() % 3 {
587 case 0:
588 // Add a fuzzed group
589 apis := fuzzAPIGroups(1, 2, 15)
590 for _, group := range apis.Items {
591 for _, version := range group.Versions {
592 manager.AddGroupVersion(group.Name, version)
593 addedGroups = append(addedGroups, metav1.GroupVersion{
594 Group: group.Name,
595 Version: version.Version,
596 })
597 }
598 }
599 case 1:
600 // Remove a group that we have added
601 if len(addedGroups) > 0 {
602 manager.RemoveGroupVersion(addedGroups[0])
603 addedGroups = addedGroups[1:]
604 } else {
605 // Send a request and try to remove a group someone else
606 // might have added
607 _, _, document := fetchPath(manager, "application/json", discoveryPath, "")
608 assert.NotNil(t, document, "manager should always succeed in returning a document")
609
610 if len(document.Items) > 0 {
611 manager.RemoveGroupVersion(metav1.GroupVersion{
612 Group: document.Items[0].Name,
613 Version: document.Items[0].Versions[0].Version,
614 })
615 }
616
617 }
618 case 2:
619 manager.SetGroups(nil)
620 addedGroups = nil
621 default:
622 panic("unreachable")
623 }
624 }
625 }()
626 }
627
628 // Spawn a bunch of readers that will keep sending requests to the server
629 // and making sure the response makes sense
630 for i := 0; i < numReaders; i++ {
631 waitGroup.Add(1)
632 go func() {
633 defer waitGroup.Done()
634
635 etag := ""
636 for j := 0; j < numRequestsPerReader; j++ {
637 response, body, document := fetchPath(manager, "application/json", discoveryPath, etag)
638
639 if response.StatusCode == http.StatusNotModified {
640 assert.Equal(t, etag, response.Header.Get("ETag"))
641 assert.Empty(t, body, "body should be empty if etag used")
642 assert.Nil(t, document)
643 } else {
644 assert.Equal(t, http.StatusOK, response.StatusCode, "response should be OK if etag was unused")
645 assert.NotNil(t, document)
646 }
647
648 etag = response.Header.Get("ETag")
649 }
650 }()
651 }
652
653 waitGroup.Wait()
654 }
655
656 func TestVersionSortingNoPriority(t *testing.T) {
657 manager := discoveryendpoint.NewResourceManager("apis")
658
659 manager.AddGroupVersion("default", apidiscoveryv2.APIVersionDiscovery{
660 Version: "v1alpha1",
661 })
662 manager.AddGroupVersion("default", apidiscoveryv2.APIVersionDiscovery{
663 Version: "v2beta1",
664 })
665 manager.AddGroupVersion("default", apidiscoveryv2.APIVersionDiscovery{
666 Version: "v1",
667 })
668 manager.AddGroupVersion("default", apidiscoveryv2.APIVersionDiscovery{
669 Version: "v1beta1",
670 })
671 manager.AddGroupVersion("default", apidiscoveryv2.APIVersionDiscovery{
672 Version: "v2",
673 })
674
675 response, _, decoded := fetchPath(manager, "application/json", discoveryPath, "")
676 assert.Equal(t, http.StatusOK, response.StatusCode, "response should be 200 OK")
677
678 versions := decoded.Items[0].Versions
679
680 // Ensure that v1 is sorted before v1alpha1
681 assert.Equal(t, "v2", versions[0].Version)
682 assert.Equal(t, "v1", versions[1].Version)
683 assert.Equal(t, "v2beta1", versions[2].Version)
684 assert.Equal(t, "v1beta1", versions[3].Version)
685 assert.Equal(t, "v1alpha1", versions[4].Version)
686 }
687
688 func TestVersionSortingWithPriority(t *testing.T) {
689 manager := discoveryendpoint.NewResourceManager("apis")
690
691 manager.AddGroupVersion("default", apidiscoveryv2.APIVersionDiscovery{
692 Version: "v1",
693 })
694 manager.SetGroupVersionPriority(metav1.GroupVersion{Group: "default", Version: "v1"}, 1000, 100)
695 manager.AddGroupVersion("default", apidiscoveryv2.APIVersionDiscovery{
696 Version: "v1alpha1",
697 })
698 manager.SetGroupVersionPriority(metav1.GroupVersion{Group: "default", Version: "v1alpha1"}, 1000, 200)
699
700 response, _, decoded := fetchPath(manager, "application/json", discoveryPath, "")
701 assert.Equal(t, http.StatusOK, response.StatusCode, "response should be 200 OK")
702
703 versions := decoded.Items[0].Versions
704
705 // Ensure that reverse alpha sort order can be overridden by setting group version priorities.
706 assert.Equal(t, "v1alpha1", versions[0].Version)
707 assert.Equal(t, "v1", versions[1].Version)
708 }
709
710 // if two apiservices declare conflicting priorities for their group priority, take the higher one.
711 func TestGroupVersionSortingConflictingPriority(t *testing.T) {
712 manager := discoveryendpoint.NewResourceManager("apis")
713
714 manager.AddGroupVersion("default", apidiscoveryv2.APIVersionDiscovery{
715 Version: "v1",
716 })
717 manager.SetGroupVersionPriority(metav1.GroupVersion{Group: "default", Version: "v1"}, 1000, 100)
718 manager.AddGroupVersion("test", apidiscoveryv2.APIVersionDiscovery{
719 Version: "v1alpha1",
720 })
721 manager.SetGroupVersionPriority(metav1.GroupVersion{Group: "test", Version: "v1alpha1"}, 500, 100)
722 manager.AddGroupVersion("test", apidiscoveryv2.APIVersionDiscovery{
723 Version: "v1alpha2",
724 })
725 manager.SetGroupVersionPriority(metav1.GroupVersion{Group: "test", Version: "v1alpha1"}, 2000, 100)
726
727 response, _, decoded := fetchPath(manager, "application/json", discoveryPath, "")
728 assert.Equal(t, http.StatusOK, response.StatusCode, "response should be 200 OK")
729
730 groups := decoded.Items
731
732 // Ensure that reverse alpha sort order can be overridden by setting group version priorities.
733 assert.Equal(t, "test", groups[0].Name)
734 assert.Equal(t, "default", groups[1].Name)
735 }
736
737 // Show that the GroupPriorityMinimum is not sticky if a higher group version is removed
738 // after a lower one is added
739 func TestStatelessGroupPriorityMinimum(t *testing.T) {
740 manager := discoveryendpoint.NewResourceManager("apis")
741
742 stableGroup := "stable.example.com"
743 experimentalGroup := "experimental.example.com"
744
745 manager.AddGroupVersion(stableGroup, apidiscoveryv2.APIVersionDiscovery{
746 Version: "v1",
747 })
748 manager.SetGroupVersionPriority(metav1.GroupVersion{Group: stableGroup, Version: "v1"}, 1000, 100)
749
750 manager.AddGroupVersion(experimentalGroup, apidiscoveryv2.APIVersionDiscovery{
751 Version: "v1",
752 })
753 manager.SetGroupVersionPriority(metav1.GroupVersion{Group: experimentalGroup, Version: "v1"}, 100, 100)
754
755 manager.AddGroupVersion(experimentalGroup, apidiscoveryv2.APIVersionDiscovery{
756 Version: "v1alpha1",
757 })
758 manager.SetGroupVersionPriority(metav1.GroupVersion{Group: experimentalGroup, Version: "v1alpha1"}, 10000, 100)
759
760 // Expect v1alpha1's group priority to be used and sort it first in the list
761 response, _, decoded := fetchPath(manager, "application/json", discoveryPath, "")
762 assert.Equal(t, http.StatusOK, response.StatusCode, "response should be 200 OK")
763 assert.Equal(t, "experimental.example.com", decoded.Items[0].Name)
764 assert.Equal(t, "stable.example.com", decoded.Items[1].Name)
765
766 // Remove v1alpha1 and expect the new lower priority to take hold
767 manager.RemoveGroupVersion(metav1.GroupVersion{Group: experimentalGroup, Version: "v1alpha1"})
768
769 response, _, decoded = fetchPath(manager, "application/json", discoveryPath, "")
770 assert.Equal(t, http.StatusOK, response.StatusCode, "response should be 200 OK")
771
772 assert.Equal(t, "stable.example.com", decoded.Items[0].Name)
773 assert.Equal(t, "experimental.example.com", decoded.Items[1].Name)
774 }