-
Notifications
You must be signed in to change notification settings - Fork 97
/
resourcemanager.go
775 lines (646 loc) · 22.3 KB
/
resourcemanager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
// Utility functions for managing resources in Kubernetes. Inspiration and methods used from
// https://github.com/kubernetes-sigs/gateway-api/tree/main/conformance/utils.
/*
Copyright 2022 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package framework
import (
"bytes"
"context"
"embed"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"strings"
"time"
"k8s.io/client-go/util/retry"
apps "k8s.io/api/apps/v1"
core "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/client"
v1 "sigs.k8s.io/gateway-api/apis/v1"
)
// ResourceManager handles creating/updating/deleting Kubernetes resources.
type ResourceManager struct {
K8sClient client.Client
ClientGoClient kubernetes.Interface // used when k8sClient is not enough
FS embed.FS
TimeoutConfig TimeoutConfig
}
// ClusterInfo holds the cluster metadata.
type ClusterInfo struct {
K8sVersion string
// ID is the UID of kube-system namespace
ID string
MemoryPerNode string
GkeInstanceType string
GkeZone string
NodeCount int
CPUCountPerNode int64
MaxPodsPerNode int64
IsGKE bool
}
// Apply creates or updates Kubernetes resources defined as Go objects.
func (rm *ResourceManager) Apply(resources []client.Object) error {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.CreateTimeout)
defer cancel()
for _, resource := range resources {
var obj client.Object
unstructuredObj, ok := resource.(*unstructured.Unstructured)
if ok {
obj = unstructuredObj.DeepCopy()
} else {
t := reflect.TypeOf(resource).Elem()
obj = reflect.New(t).Interface().(client.Object)
}
if err := rm.K8sClient.Get(ctx, client.ObjectKeyFromObject(resource), obj); err != nil {
if !apierrors.IsNotFound(err) {
return fmt.Errorf("error getting resource: %w", err)
}
if err := rm.K8sClient.Create(ctx, resource); err != nil {
return fmt.Errorf("error creating resource: %w", err)
}
continue
}
// Some tests modify resources that are also modified by NGF (to update their status), so conflicts are possible
// For example, a Gateway resource.
err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
if err := rm.K8sClient.Get(ctx, client.ObjectKeyFromObject(resource), obj); err != nil {
return err
}
resource.SetResourceVersion(obj.GetResourceVersion())
return rm.K8sClient.Update(ctx, resource)
})
if err != nil {
return fmt.Errorf("error updating resource: %w", err)
}
}
return nil
}
// ApplyFromFiles creates or updates Kubernetes resources defined within the provided YAML files.
func (rm *ResourceManager) ApplyFromFiles(files []string, namespace string) error {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.CreateTimeout)
defer cancel()
handlerFunc := func(obj unstructured.Unstructured) error {
obj.SetNamespace(namespace)
nsName := types.NamespacedName{Namespace: obj.GetNamespace(), Name: obj.GetName()}
fetchedObj := obj.DeepCopy()
if err := rm.K8sClient.Get(ctx, nsName, fetchedObj); err != nil {
if !apierrors.IsNotFound(err) {
return fmt.Errorf("error getting resource: %w", err)
}
if err := rm.K8sClient.Create(ctx, &obj); err != nil {
return fmt.Errorf("error creating resource: %w", err)
}
return nil
}
// Some tests modify resources that are also modified by NGF (to update their status), so conflicts are possible
// For example, a Gateway resource.
err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
if err := rm.K8sClient.Get(ctx, nsName, fetchedObj); err != nil {
return err
}
obj.SetResourceVersion(fetchedObj.GetResourceVersion())
return rm.K8sClient.Update(ctx, &obj)
})
if err != nil {
return fmt.Errorf("error updating resource: %w", err)
}
return nil
}
return rm.readAndHandleObjects(handlerFunc, files)
}
// Delete deletes Kubernetes resources defined as Go objects.
func (rm *ResourceManager) Delete(resources []client.Object, opts ...client.DeleteOption) error {
for _, resource := range resources {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.DeleteTimeout)
defer cancel()
if err := rm.K8sClient.Delete(ctx, resource, opts...); err != nil && !apierrors.IsNotFound(err) {
return fmt.Errorf("error deleting resource: %w", err)
}
}
return nil
}
func (rm *ResourceManager) DeleteNamespace(name string) error {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.DeleteNamespaceTimeout)
defer cancel()
ns := &core.Namespace{}
if err := rm.K8sClient.Get(ctx, types.NamespacedName{Name: name}, ns); err != nil {
if apierrors.IsNotFound(err) {
return nil
}
return fmt.Errorf("error getting namespace: %w", err)
}
if err := rm.K8sClient.Delete(ctx, ns); err != nil {
return fmt.Errorf("error deleting namespace: %w", err)
}
// Because the namespace deletion is asynchronous, we need to wait for the namespace to be deleted.
return wait.PollUntilContextCancel(
ctx,
500*time.Millisecond,
true, /* poll immediately */
func(ctx context.Context) (bool, error) {
if err := rm.K8sClient.Get(ctx, types.NamespacedName{Name: name}, ns); err != nil {
if apierrors.IsNotFound(err) {
return true, nil
}
return false, fmt.Errorf("error getting namespace: %w", err)
}
return false, nil
})
}
// DeleteFromFiles deletes Kubernetes resources defined within the provided YAML files.
func (rm *ResourceManager) DeleteFromFiles(files []string, namespace string) error {
handlerFunc := func(obj unstructured.Unstructured) error {
obj.SetNamespace(namespace)
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.DeleteTimeout)
defer cancel()
if err := rm.K8sClient.Delete(ctx, &obj); err != nil && !apierrors.IsNotFound(err) {
return err
}
return nil
}
return rm.readAndHandleObjects(handlerFunc, files)
}
func (rm *ResourceManager) readAndHandleObjects(
handle func(unstructured.Unstructured) error,
files []string,
) error {
for _, file := range files {
data, err := rm.GetFileContents(file)
if err != nil {
return err
}
decoder := yaml.NewYAMLOrJSONDecoder(data, 4096)
for {
obj := unstructured.Unstructured{}
if err := decoder.Decode(&obj); err != nil {
if errors.Is(err, io.EOF) {
break
}
return fmt.Errorf("error decoding resource: %w", err)
}
if len(obj.Object) == 0 {
continue
}
if err := handle(obj); err != nil {
return err
}
}
}
return nil
}
// GetFileContents takes a string that can either be a local file
// path or an https:// URL to YAML manifests and provides the contents.
func (rm *ResourceManager) GetFileContents(file string) (*bytes.Buffer, error) {
if strings.HasPrefix(file, "http://") {
return nil, fmt.Errorf("data can't be retrieved from %s: http is not supported, use https", file)
} else if strings.HasPrefix(file, "https://") {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.ManifestFetchTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, file, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%d response when getting %s file contents", resp.StatusCode, file)
}
manifests := new(bytes.Buffer)
count, err := manifests.ReadFrom(resp.Body)
if err != nil {
return nil, err
}
if resp.ContentLength != -1 && count != resp.ContentLength {
return nil, fmt.Errorf("received %d bytes from %s, expected %d", count, file, resp.ContentLength)
}
return manifests, nil
}
if !strings.HasPrefix(file, "manifests/") {
file = "manifests/" + file
}
b, err := rm.FS.ReadFile(file)
if err != nil {
return nil, err
}
return bytes.NewBuffer(b), nil
}
// WaitForAppsToBeReady waits for all apps in the specified namespace to be ready,
// or until the ctx timeout is reached.
func (rm *ResourceManager) WaitForAppsToBeReady(namespace string) error {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.CreateTimeout)
defer cancel()
return rm.WaitForAppsToBeReadyWithCtx(ctx, namespace)
}
// WaitForAppsToBeReadyWithCtx waits for all apps in the specified namespace to be ready or
// until the provided context is canceled.
func (rm *ResourceManager) WaitForAppsToBeReadyWithCtx(ctx context.Context, namespace string) error {
if err := rm.WaitForPodsToBeReady(ctx, namespace); err != nil {
return err
}
if err := rm.waitForHTTPRoutesToBeReady(ctx, namespace); err != nil {
return err
}
if err := rm.waitForGRPCRoutesToBeReady(ctx, namespace); err != nil {
return err
}
return rm.waitForGatewaysToBeReady(ctx, namespace)
}
// WaitForPodsToBeReady waits for all Pods in the specified namespace to be ready or
// until the provided context is canceled.
func (rm *ResourceManager) WaitForPodsToBeReady(ctx context.Context, namespace string) error {
return wait.PollUntilContextCancel(
ctx,
500*time.Millisecond,
true, /* poll immediately */
func(ctx context.Context) (bool, error) {
var podList core.PodList
if err := rm.K8sClient.List(ctx, &podList, client.InNamespace(namespace)); err != nil {
return false, err
}
var podsReady int
for _, pod := range podList.Items {
for _, cond := range pod.Status.Conditions {
if cond.Type == core.PodReady && cond.Status == core.ConditionTrue {
podsReady++
}
}
}
return podsReady == len(podList.Items), nil
},
)
}
func (rm *ResourceManager) waitForGatewaysToBeReady(ctx context.Context, namespace string) error {
return wait.PollUntilContextCancel(
ctx,
500*time.Millisecond,
true, /* poll immediately */
func(ctx context.Context) (bool, error) {
var gatewayList v1.GatewayList
if err := rm.K8sClient.List(ctx, &gatewayList, client.InNamespace(namespace)); err != nil {
return false, err
}
for _, gw := range gatewayList.Items {
for _, cond := range gw.Status.Conditions {
if cond.Type == string(v1.GatewayConditionProgrammed) && cond.Status == metav1.ConditionTrue {
return true, nil
}
}
}
return false, nil
},
)
}
func (rm *ResourceManager) waitForHTTPRoutesToBeReady(ctx context.Context, namespace string) error {
return wait.PollUntilContextCancel(
ctx,
500*time.Millisecond,
true, /* poll immediately */
func(ctx context.Context) (bool, error) {
var routeList v1.HTTPRouteList
if err := rm.K8sClient.List(ctx, &routeList, client.InNamespace(namespace)); err != nil {
return false, err
}
var numParents, readyCount int
for _, route := range routeList.Items {
numParents += len(route.Spec.ParentRefs)
readyCount += countNumberOfReadyParents(route.Status.Parents)
}
return numParents == readyCount, nil
},
)
}
func (rm *ResourceManager) waitForGRPCRoutesToBeReady(ctx context.Context, namespace string) error {
// First, check if grpcroute even exists for v1. If not, ignore.
var routeList v1.GRPCRouteList
err := rm.K8sClient.List(ctx, &routeList, client.InNamespace(namespace))
if err != nil && strings.Contains(err.Error(), "no matches for kind") {
return nil
}
return wait.PollUntilContextCancel(
ctx,
500*time.Millisecond,
true, /* poll immediately */
func(ctx context.Context) (bool, error) {
var routeList v1.GRPCRouteList
if err := rm.K8sClient.List(ctx, &routeList, client.InNamespace(namespace)); err != nil {
return false, err
}
var numParents, readyCount int
for _, route := range routeList.Items {
numParents += len(route.Spec.ParentRefs)
readyCount += countNumberOfReadyParents(route.Status.Parents)
}
return numParents == readyCount, nil
},
)
}
// GetLBIPAddress gets the IP or Hostname from the Loadbalancer service.
func (rm *ResourceManager) GetLBIPAddress(namespace string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.CreateTimeout)
defer cancel()
var serviceList core.ServiceList
var address string
if err := rm.K8sClient.List(ctx, &serviceList, client.InNamespace(namespace)); err != nil {
return "", err
}
var nsName types.NamespacedName
for _, svc := range serviceList.Items {
if svc.Spec.Type == core.ServiceTypeLoadBalancer {
nsName = types.NamespacedName{Namespace: svc.GetNamespace(), Name: svc.GetName()}
if err := rm.waitForLBStatusToBeReady(ctx, nsName); err != nil {
return "", fmt.Errorf("error getting status from LoadBalancer service: %w", err)
}
}
}
if nsName.Name != "" {
var lbService core.Service
if err := rm.K8sClient.Get(ctx, nsName, &lbService); err != nil {
return "", fmt.Errorf("error getting LoadBalancer service: %w", err)
}
if lbService.Status.LoadBalancer.Ingress[0].IP != "" {
address = lbService.Status.LoadBalancer.Ingress[0].IP
} else if lbService.Status.LoadBalancer.Ingress[0].Hostname != "" {
address = lbService.Status.LoadBalancer.Ingress[0].Hostname
}
return address, nil
}
return "", nil
}
func (rm *ResourceManager) waitForLBStatusToBeReady(ctx context.Context, svcNsName types.NamespacedName) error {
return wait.PollUntilContextCancel(
ctx,
500*time.Millisecond,
true, /* poll immediately */
func(ctx context.Context) (bool, error) {
var svc core.Service
if err := rm.K8sClient.Get(ctx, svcNsName, &svc); err != nil {
return false, err
}
if len(svc.Status.LoadBalancer.Ingress) > 0 {
return true, nil
}
return false, nil
},
)
}
// GetClusterInfo retrieves node info and Kubernetes version from the cluster.
func (rm *ResourceManager) GetClusterInfo() (ClusterInfo, error) {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.GetTimeout)
defer cancel()
var nodes core.NodeList
ci := &ClusterInfo{}
if err := rm.K8sClient.List(ctx, &nodes); err != nil {
return *ci, fmt.Errorf("error getting nodes: %w", err)
}
ci.NodeCount = len(nodes.Items)
node := nodes.Items[0]
ci.K8sVersion = node.Status.NodeInfo.KubeletVersion
ci.CPUCountPerNode, _ = node.Status.Capacity.Cpu().AsInt64()
ci.MemoryPerNode = node.Status.Capacity.Memory().String()
ci.MaxPodsPerNode, _ = node.Status.Capacity.Pods().AsInt64()
providerID := node.Spec.ProviderID
if strings.Split(providerID, "://")[0] == "gce" {
ci.IsGKE = true
ci.GkeInstanceType = node.Labels["beta.kubernetes.io/instance-type"]
ci.GkeZone = node.Labels["topology.kubernetes.io/zone"]
}
var ns core.Namespace
key := types.NamespacedName{Name: "kube-system"}
if err := rm.K8sClient.Get(ctx, key, &ns); err != nil {
return *ci, fmt.Errorf("error getting kube-system namespace: %w", err)
}
ci.ID = string(ns.UID)
return *ci, nil
}
// GetPodNames returns the names of all Pods in the specified namespace that match the given labels.
func (rm *ResourceManager) GetPodNames(namespace string, labels client.MatchingLabels) ([]string, error) {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.GetTimeout)
defer cancel()
var podList core.PodList
if err := rm.K8sClient.List(
ctx,
&podList,
client.InNamespace(namespace),
labels,
); err != nil {
return nil, fmt.Errorf("error getting list of Pods: %w", err)
}
names := make([]string, 0, len(podList.Items))
for _, pod := range podList.Items {
names = append(names, pod.Name)
}
return names, nil
}
// GetPods returns all Pods in the specified namespace that match the given labels.
func (rm *ResourceManager) GetPods(namespace string, labels client.MatchingLabels) ([]core.Pod, error) {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.GetTimeout)
defer cancel()
var podList core.PodList
if err := rm.K8sClient.List(
ctx,
&podList,
client.InNamespace(namespace),
labels,
); err != nil {
return nil, fmt.Errorf("error getting list of Pods: %w", err)
}
return podList.Items, nil
}
// GetPod returns the Pod in the specified namespace with the given name.
func (rm *ResourceManager) GetPod(namespace, name string) (*core.Pod, error) {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.GetTimeout)
defer cancel()
var pod core.Pod
if err := rm.K8sClient.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, &pod); err != nil {
return nil, fmt.Errorf("error getting Pod: %w", err)
}
return &pod, nil
}
// GetPodLogs returns the logs from the specified Pod.
func (rm *ResourceManager) GetPodLogs(namespace, name string, opts *core.PodLogOptions) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.GetTimeout)
defer cancel()
req := rm.ClientGoClient.CoreV1().Pods(namespace).GetLogs(name, opts)
logs, err := req.Stream(ctx)
if err != nil {
return "", fmt.Errorf("error getting logs from Pod: %w", err)
}
defer logs.Close()
buf := new(bytes.Buffer)
if _, err := buf.ReadFrom(logs); err != nil {
return "", fmt.Errorf("error reading logs from Pod: %w", err)
}
return buf.String(), nil
}
// GetNGFDeployment returns the NGF Deployment in the specified namespace with the given release name.
func (rm *ResourceManager) GetNGFDeployment(namespace, releaseName string) (*apps.Deployment, error) {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.GetTimeout)
defer cancel()
var deployments apps.DeploymentList
if err := rm.K8sClient.List(
ctx,
&deployments,
client.InNamespace(namespace),
client.MatchingLabels{
"app.kubernetes.io/instance": releaseName,
},
); err != nil {
return nil, fmt.Errorf("error getting list of Deployments: %w", err)
}
if len(deployments.Items) != 1 {
return nil, fmt.Errorf("expected 1 NGF Deployment, got %d", len(deployments.Items))
}
deployment := deployments.Items[0]
return &deployment, nil
}
// ScaleDeployment scales the Deployment to the specified number of replicas.
func (rm *ResourceManager) ScaleDeployment(namespace, name string, replicas int32) error {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.UpdateTimeout)
defer cancel()
var deployment apps.Deployment
if err := rm.K8sClient.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, &deployment); err != nil {
return fmt.Errorf("error getting Deployment: %w", err)
}
deployment.Spec.Replicas = &replicas
if err := rm.K8sClient.Update(ctx, &deployment); err != nil {
return fmt.Errorf("error updating Deployment: %w", err)
}
return nil
}
// GetReadyNGFPodNames returns the name(s) of the NGF Pod(s).
func GetReadyNGFPodNames(
k8sClient client.Client,
namespace,
releaseName string,
timeout time.Duration,
) ([]string, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
var podList core.PodList
if err := k8sClient.List(
ctx,
&podList,
client.InNamespace(namespace),
client.MatchingLabels{
"app.kubernetes.io/instance": releaseName,
},
); err != nil {
return nil, fmt.Errorf("error getting list of Pods: %w", err)
}
if len(podList.Items) > 0 {
var names []string
for _, pod := range podList.Items {
for _, cond := range pod.Status.Conditions {
if cond.Type == core.PodReady && cond.Status == core.ConditionTrue {
names = append(names, pod.Name)
}
}
}
return names, nil
}
return nil, errors.New("unable to find NGF Pod(s)")
}
func countNumberOfReadyParents(parents []v1.RouteParentStatus) int {
readyCount := 0
for _, parent := range parents {
for _, cond := range parent.Conditions {
if cond.Type == string(v1.RouteConditionAccepted) && cond.Status == metav1.ConditionTrue {
readyCount++
}
}
}
return readyCount
}
func (rm *ResourceManager) WaitForAppsToBeReadyWithPodCount(namespace string, podCount int) error {
ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.CreateTimeout)
defer cancel()
return rm.WaitForAppsToBeReadyWithCtxWithPodCount(ctx, namespace, podCount)
}
func (rm *ResourceManager) WaitForAppsToBeReadyWithCtxWithPodCount(
ctx context.Context,
namespace string,
podCount int,
) error {
if err := rm.WaitForPodsToBeReadyWithCount(ctx, namespace, podCount); err != nil {
return err
}
if err := rm.waitForHTTPRoutesToBeReady(ctx, namespace); err != nil {
return err
}
if err := rm.waitForGRPCRoutesToBeReady(ctx, namespace); err != nil {
return err
}
return rm.waitForGatewaysToBeReady(ctx, namespace)
}
// WaitForPodsToBeReady waits for all Pods in the specified namespace to be ready or
// until the provided context is canceled.
func (rm *ResourceManager) WaitForPodsToBeReadyWithCount(ctx context.Context, namespace string, count int) error {
return wait.PollUntilContextCancel(
ctx,
500*time.Millisecond,
true, /* poll immediately */
func(ctx context.Context) (bool, error) {
var podList core.PodList
if err := rm.K8sClient.List(ctx, &podList, client.InNamespace(namespace)); err != nil {
return false, err
}
var podsReady int
for _, pod := range podList.Items {
for _, cond := range pod.Status.Conditions {
if cond.Type == core.PodReady && cond.Status == core.ConditionTrue {
podsReady++
}
}
}
return podsReady == count, nil
},
)
}
// WaitForGatewayObservedGeneration waits for the provided Gateway's ObservedGeneration to equal the expected value.
func (rm *ResourceManager) WaitForGatewayObservedGeneration(
ctx context.Context,
namespace,
name string,
generation int,
) error {
return wait.PollUntilContextCancel(
ctx,
500*time.Millisecond,
true, /* poll immediately */
func(ctx context.Context) (bool, error) {
var gw v1.Gateway
key := types.NamespacedName{Namespace: namespace, Name: name}
if err := rm.K8sClient.Get(ctx, key, &gw); err != nil {
return false, err
}
for _, cond := range gw.Status.Conditions {
if cond.ObservedGeneration == int64(generation) {
return true, nil
}
}
return false, nil
},
)
}