-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathstatus.go
More file actions
1028 lines (937 loc) · 42.9 KB
/
status.go
File metadata and controls
1028 lines (937 loc) · 42.9 KB
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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package route
import (
"context"
"fmt"
"github.com/go-logr/logr"
"github.com/samber/lo"
corev1 "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/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/client"
configurationv1 "github.com/kong/kong-operator/v2/api/configuration/v1"
"github.com/kong/kong-operator/v2/controller/hybridgateway/metadata"
"github.com/kong/kong-operator/v2/controller/hybridgateway/utils"
"github.com/kong/kong-operator/v2/controller/pkg/log"
gwtypes "github.com/kong/kong-operator/v2/internal/types"
)
// SetStatusConditions updates the status conditions for a specific ParentReference managed by the given controller.
// It finds the ParentStatus entry that matches both the ParentReference and controllerName, then updates or adds
// the provided conditions. If no matching ParentStatus exists, it creates a new one.
//
// The function performs intelligent condition management:
// - Only updates conditions that have actually changed (ignoring LastTransitionTime)
// - Automatically sets LastTransitionTime when conditions are modified
// - Removes stale conditions that are not in the provided set (e.g., when resources are deleted)
// - Only manages ParentStatus entries owned by the specified controller
//
// Parameters:
// - route: The HTTPRoute to update
// - pRef: The ParentReference to match against
// - controllerName: The controller name that should own the ParentStatus entry
// - conditions: Variable number of conditions to set or update (any existing conditions not in this list will be removed)
//
// Returns:
// - bool: true if any conditions were added, modified, or removed, false if no changes were made
//
// This function respects controller ownership and will not modify ParentStatus entries
// managed by other controllers, making it safe for use in multi-controller environments.
func SetStatusConditions(route *gwtypes.HTTPRoute, pRef gwtypes.ParentReference, controllerName string, conditions ...metav1.Condition) bool {
updated := false
// Find the ParentStatus for the given ParentRef that is managed by our controller.
var targetParentStatus *gwtypes.RouteParentStatus
for i := range route.Status.Parents {
if string(route.Status.Parents[i].ControllerName) == controllerName &&
isParentRefEqual(route.Status.Parents[i].ParentRef, pRef) {
targetParentStatus = &route.Status.Parents[i]
break
}
}
// If ParentStatus doesn't exist for our controller, create it.
if targetParentStatus == nil {
route.Status.Parents = append(route.Status.Parents, gwtypes.RouteParentStatus{
ParentRef: pRef,
ControllerName: gwtypes.GatewayController(controllerName),
Conditions: conditions,
})
// We are done, return.
return true
}
// Build a map of new condition types for quick lookup.
newConditionTypes := make(map[string]bool)
for _, cond := range conditions {
newConditionTypes[cond.Type] = true
}
// Remove conditions that are not in the new set (stale conditions).
filteredConditions := []metav1.Condition{}
for _, existingCondition := range targetParentStatus.Conditions {
if newConditionTypes[existingCondition.Type] {
// Keep this condition, it will be updated below.
filteredConditions = append(filteredConditions, existingCondition)
} else {
// Remove this stale condition.
updated = true
}
}
targetParentStatus.Conditions = filteredConditions
// Process each condition.
for _, newCondition := range conditions {
// Find existing condition of the same type.
existingConditionIndex := -1
for i, existingCondition := range targetParentStatus.Conditions {
if existingCondition.Type == newCondition.Type {
existingConditionIndex = i
break
}
}
// Compare conditions and update if different.
if existingConditionIndex >= 0 {
existingCondition := &targetParentStatus.Conditions[existingConditionIndex]
if !isConditionEqual(*existingCondition, newCondition) {
// Update existing condition.
existingCondition.Status = newCondition.Status
existingCondition.Reason = newCondition.Reason
existingCondition.Message = newCondition.Message
existingCondition.ObservedGeneration = newCondition.ObservedGeneration
existingCondition.LastTransitionTime = metav1.Now()
updated = true
}
} else {
// Add new condition.
newCondition.LastTransitionTime = metav1.Now()
targetParentStatus.Conditions = append(targetParentStatus.Conditions, newCondition)
updated = true
}
}
return updated
}
// CleanupOrphanedParentStatus removes ParentStatus entries from the route status that are no longer
// relevant (i.e., not present in the route's current parentRefs) and are managed by the specified controller.
// This function helps maintain a clean status by removing stale entries when parentRefs are removed from the route spec.
//
// Parameters:
// - route: The HTTPRoute to clean up
// - controllerName: The controller name that should own the ParentStatus entries to be cleaned
//
// Returns:
// - bool: true if any ParentStatus entries were removed, false if no changes were made
//
// This function only removes ParentStatus entries owned by the specified controller, leaving
// entries from other controllers untouched, making it safe for use in multi-controller environments.
func CleanupOrphanedParentStatus(logger logr.Logger, route *gwtypes.HTTPRoute, controllerName string) bool {
if len(route.Status.Parents) == 0 {
return false
}
// Create a set of current parentRefs for quick lookup.
currentParentRefs := make(map[string]bool)
for _, pRef := range route.Spec.ParentRefs {
// Create a unique key for each parentRef.
key := parentRefKey(pRef)
currentParentRefs[key] = true
}
// Filter out orphaned ParentStatus entries.
filteredParents := []gwtypes.RouteParentStatus{}
removed := false
for _, parentStatus := range route.Status.Parents {
// Only process entries owned by our controller.
if string(parentStatus.ControllerName) != controllerName {
// Keep entries from other controllers.
filteredParents = append(filteredParents, parentStatus)
continue
}
// Check if this ParentStatus corresponds to a current parentRef.
key := parentRefKey(parentStatus.ParentRef)
if currentParentRefs[key] {
// Keep relevant entries.
filteredParents = append(filteredParents, parentStatus)
} else {
// Mark as removed (orphaned entry).
log.Debug(logger, "Removing orphaned ParentStatus entry", "parentRef", parentStatus.ParentRef, "controller", controllerName)
removed = true
}
}
// Update the route status if we removed any entries
if removed {
route.Status.Parents = filteredParents
}
return removed
}
// RemoveStatusForParentRef removes the ParentStatus entry for the specified ParentReference and controllerName from the route's status.
//
// This function iterates through all ParentStatus entries in the route's status and removes any entry that matches both the given
// ParentReference and controllerName. It is useful for cleaning up status when a parent reference is deleted or no longer relevant.
//
// Parameters:
// - route: The HTTPRoute whose status should be updated
// - pRef: The ParentReference to match for removal
// - controllerName: The controller name that must match for removal
//
// Returns:
// - bool: true if a matching ParentStatus entry was removed, false otherwise
func RemoveStatusForParentRef(logger logr.Logger, route *gwtypes.HTTPRoute, pRef gwtypes.ParentReference, controllerName string) bool {
if len(route.Status.Parents) == 0 {
return false
}
removed := false
filteredParents := []gwtypes.RouteParentStatus{}
for _, parentStatus := range route.Status.Parents {
if string(parentStatus.ControllerName) == controllerName && isParentRefEqual(parentStatus.ParentRef, pRef) {
// Skip this entry (remove it).
log.Debug(logger, "Removing ParentStatus entry for ParentReference", "parentRef", parentStatus.ParentRef, "controller", controllerName)
removed = true
continue
}
filteredParents = append(filteredParents, parentStatus)
}
if removed {
route.Status.Parents = filteredParents
}
return removed
}
// parentRefKey generates a unique key for a ParentReference to enable comparison.
func parentRefKey(pRef gwtypes.ParentReference) string {
var group, kind, namespace, sectionName string
var port string
if pRef.Group != nil {
group = string(*pRef.Group)
}
if pRef.Kind != nil {
kind = string(*pRef.Kind)
}
if pRef.Namespace != nil {
namespace = string(*pRef.Namespace)
}
if pRef.SectionName != nil {
sectionName = string(*pRef.SectionName)
}
if pRef.Port != nil {
port = fmt.Sprintf("%d", *pRef.Port)
}
return fmt.Sprintf("%s/%s/%s/%s/%s/%s", group, kind, namespace, string(pRef.Name), sectionName, port)
}
// isParentRefEqual compares two ParentReference objects for equality.
func isParentRefEqual(a, b gwtypes.ParentReference) bool {
// Compare Group
if (a.Group == nil) != (b.Group == nil) {
return false
}
if a.Group != nil && b.Group != nil && *a.Group != *b.Group {
return false
}
// Compare Kind
if (a.Kind == nil) != (b.Kind == nil) {
return false
}
if a.Kind != nil && b.Kind != nil && *a.Kind != *b.Kind {
return false
}
// Compare Name
if a.Name != b.Name {
return false
}
// Compare Namespace
if (a.Namespace == nil) != (b.Namespace == nil) {
return false
}
if a.Namespace != nil && b.Namespace != nil && *a.Namespace != *b.Namespace {
return false
}
// Compare SectionName
if (a.SectionName == nil) != (b.SectionName == nil) {
return false
}
if a.SectionName != nil && b.SectionName != nil && *a.SectionName != *b.SectionName {
return false
}
// Compare Port
if (a.Port == nil) != (b.Port == nil) {
return false
}
if a.Port != nil && b.Port != nil && *a.Port != *b.Port {
return false
}
return true
}
// isConditionEqual compares two conditions to see if they are functionally equivalent
// (ignoring LastTransitionTime since that's updated automatically).
func isConditionEqual(a, b metav1.Condition) bool {
return a.Type == b.Type &&
a.Status == b.Status &&
a.Reason == b.Reason &&
a.Message == b.Message &&
a.ObservedGeneration == b.ObservedGeneration
}
// BuildAcceptedCondition builds the "Accepted" condition for a given HTTPRoute and ParentReference.
// It validates whether the route can be accepted by the gateway by checking multiple criteria
// in sequence, returning the first failure condition encountered or a success condition if all checks pass.
//
// The function performs the following validation steps:
// 1. Filters listeners that match the ParentReference (section name, port, protocol)
// 2. Checks if the route namespace is allowed by the gateway listeners
// 3. Validates that route hostnames intersect with listener hostnames
//
// Parameters:
// - ctx: The context for API calls
// - logger: Logger for debugging information
// - cl: The Kubernetes client for API operations
// - gateway: The Gateway object associated with the ParentReference
// - route: The HTTPRoute to validate for acceptance
// - pRef: The ParentReference being evaluated
//
// Returns:
// - *metav1.Condition: The "Accepted" condition with appropriate status, reason, and message
// - error: Any error that occurred during validation (e.g., failed to retrieve namespace)
//
// The function returns a condition with status "False" if any validation step fails,
// or status "True" if the route is accepted by the gateway. The condition includes
// specific reasons and messages to help diagnose acceptance issues.
func BuildAcceptedCondition(ctx context.Context, logger logr.Logger, cl client.Client, gateway *gwtypes.Gateway,
route *gwtypes.HTTPRoute, pRef gwtypes.ParentReference) (*metav1.Condition, error) {
// Begin by excluding listeners that do not match the specified section name.
listeners, cond := FilterMatchingListeners(logger, gateway, pRef, gateway.Spec.Listeners)
if cond != nil {
log.Debug(logger, "No matching listeners for ParentReference", "parentRef", pRef, "gateway", gateway.Name)
// Return the condition indicating no matching listeners.
return SetConditionMeta(*cond, route), nil
}
// If we have listeners that match, we check the allowed routes.
// We need to get the namespace of the route to check against the allowed routes.
routeNamespace := corev1.Namespace{}
if err := cl.Get(ctx, client.ObjectKey{Name: route.Namespace}, &routeNamespace); err != nil {
return nil, fmt.Errorf("failed to get namespace %s for route %s while building accepted condition for gateway %s: %w",
route.Namespace, client.ObjectKeyFromObject(route), client.ObjectKeyFromObject(gateway), err)
}
// Prepare the RouteGroupKind for the HTTPRoute.
rgk := GetRouteGroupKind(route)
// Filter listeners by allowed routes.
listeners, cond, err := FilterListenersByAllowedRoutes(logger, gateway, pRef, listeners, rgk, &routeNamespace)
if err != nil {
return nil, err
}
if cond != nil {
log.Debug(logger, "Listeners do not allow route", "parentRef", pRef, "gateway", gateway.Name, "reason", cond.Reason)
return SetConditionMeta(*cond, route), nil
}
// If we have listeners that allow the route, we check the hostnames.
_, cond = FilterListenersByHostnames(logger, listeners, route.Spec.Hostnames)
if cond != nil {
log.Debug(logger, "Listeners do not match hostnames", "parentRef", pRef, "gateway", gateway.Name, "reason", cond.Reason)
return SetConditionMeta(*cond, route), nil
}
// If we have listeners that match the hostnames, we can accept the route.
log.Debug(logger, "Route accepted by gateway", "route", route.Name, "gateway", gateway.Name)
cond = &metav1.Condition{
Type: string(gwtypes.RouteConditionAccepted),
Status: metav1.ConditionTrue,
Reason: string(gwtypes.RouteReasonAccepted),
Message: "The route is accepted by the gateway",
}
return SetConditionMeta(*cond, route), nil
}
// BuildProgrammedCondition evaluates the programmed status of all resources associated with a route and gateway.
// For each expected GroupVersionKind (GVK), it lists resources owned by the route and gateway, checks if each is programmed,
// and generates a corresponding condition (True if programmed, False otherwise).
//
// The function deduplicates conditions by type, keeping the most severe status for each resource type.
//
// Parameters:
// - ctx: Context for API calls.
// - logger: Logger for debugging information.
// - cl: Kubernetes client for resource operations.
// - route: The HTTPRoute whose resources are being checked.
// - pRef: The ParentReference (gateway) associated with the route.
// - expectedGVKs: Slice of GVKs representing the resource types to check.
//
// Returns:
// - []metav1.Condition: Slice of conditions, one per resource type, indicating programmed status.
// - error: Any error encountered during resource listing or evaluation.
//
// This function provides granular feedback for each resource type, allowing users to see exactly which
// resources are not programmed and why, improving troubleshooting and status visibility.
func BuildProgrammedCondition(ctx context.Context, logger logr.Logger, cl client.Client, route *gwtypes.HTTPRoute,
pRef gwtypes.ParentReference, expectedGVKs []schema.GroupVersionKind) ([]metav1.Condition, error) {
var conditions []metav1.Condition
// Skip setting programmed conditions for KongPlugins because they lack a status field.
expectedGVKs = FilterOutGVKByKind(expectedGVKs, "KongPlugin")
// For each expected GVK, list resources owned by the route and gateway.
for _, gvk := range expectedGVKs {
list := &unstructured.UnstructuredList{}
list.SetGroupVersionKind(gvk)
selector := metadata.LabelSelectorForOwnedResources(route, &pRef)
// List all resources of this GVK owned by the route object in the same namespace.
if err := cl.List(ctx, list, selector); err != nil {
return nil, fmt.Errorf("unable to list objects with gvk %s: %w", gvk.String(), err)
}
for _, item := range list.Items {
// Check if the item is programmed.
prog := isProgrammed(&item)
log.Debug(logger, "Resource programmed status", "gvk", gvk.String(), "name", item.GetName(), "namespace", item.GetNamespace(), "programmed", prog)
conditions = append(conditions, *SetConditionMeta(GetProgrammedConditionForGVK(gvk, prog), route))
}
}
// Before returning, deduplicate conditions by type, keeping the most severe status.
return DeduplicateConditionsByType(conditions), nil
}
// BuildResolvedRefsCondition evaluates all BackendRefs and ExtensionRefs in an HTTPRoute to determine if their
// references are valid and permitted.
// It checks that each BackendRef:
// - Has a supported group/kind
// - Exists in the target namespace
// - Is permitted by ReferenceGrant if referencing a different namespace
//
// It checks that each ExtensionRef (from filters):
// - Has a supported group/kind
// - Exists in the route's namespace (ExtensionRefs are always local to the route namespace)
//
// Returns a condition indicating whether all references are resolved, or details about the first failure encountered.
//
// Parameters:
// - ctx: Context for API calls
// - logger: Logger for debugging information
// - cl: Kubernetes client for resource operations
// - route: The HTTPRoute whose BackendRefs and ExtensionRefs are being checked
//
// Returns:
// - *metav1.Condition: Condition indicating resolved refs status
// - error: Any error encountered during evaluation
func BuildResolvedRefsCondition(ctx context.Context, logger logr.Logger, cl client.Client, route *gwtypes.HTTPRoute) (*metav1.Condition, error) {
conditionSet := false
cond := &metav1.Condition{
Type: string(gwtypes.RouteConditionResolvedRefs),
Status: metav1.ConditionTrue,
Reason: string(gwtypes.RouteReasonResolvedRefs),
Message: "All references resolved",
}
for _, rule := range route.Spec.Rules {
for _, bRef := range rule.BackendRefs {
// BackendRef namespace.
bRefNamespace := route.Namespace
if bRef.Namespace != nil && *bRef.Namespace != "" {
bRefNamespace = string(*bRef.Namespace)
}
// BackendRef group/kind (default to core/Service when unset).
bRefGroup, bRefKind := backendRefGroupKind(bRef.Group, bRef.Kind)
bRefGK := bRefKind
if bRefGroup != "" {
bRefGK = fmt.Sprintf("%s/%s", bRefGroup, bRefKind)
}
// Check if the group kind is supported for the reference.
if !IsBackendRefSupported(bRef.Group, bRef.Kind) {
log.Debug(logger, "Unsupported BackendRef group/kind", "group", bRef.Group, "kind", bRef.Kind)
cond.Reason = string(gwtypes.RouteReasonInvalidKind)
cond.Status = metav1.ConditionFalse
cond.Message = fmt.Sprintf("Unsupported BackendRef %s/%s group/kind: %s", bRefNamespace, bRef.Name, bRefGK)
conditionSet = true
break
}
// Check if the referenced object exists.
service := &corev1.Service{}
err := cl.Get(ctx, client.ObjectKey{Namespace: bRefNamespace, Name: string(bRef.Name)}, service)
if err != nil {
if apierrors.IsNotFound(err) {
log.Debug(logger, "BackendRef not found", "namespace", bRefNamespace, "name", bRef.Name)
cond.Reason = string(gwtypes.RouteReasonBackendNotFound)
cond.Status = metav1.ConditionFalse
cond.Message = fmt.Sprintf("BackendRef %s/%s not found", bRefNamespace, bRef.Name)
conditionSet = true
break
}
return nil, fmt.Errorf("failed to get BackendRef %s/%s: %w", bRefNamespace, bRef.Name, err)
}
// Check if the referenced object is permitted by the reference grant if in a different namespace.
if bRefNamespace != route.Namespace {
// Use CheckReferenceGrant helper to check if the reference is permitted.
permitted, found, err := CheckReferenceGrant(ctx, cl, &bRef, route.Namespace)
if err != nil {
return nil, fmt.Errorf("failed to check ReferenceGrant for BackendRef %s/%s: %w", bRefNamespace, bRef.Name, err)
}
if !found {
log.Debug(logger, "No ReferenceGrants found in backend ref namespace", "namespace", bRefNamespace)
cond.Reason = string(gwtypes.RouteReasonRefNotPermitted)
cond.Status = metav1.ConditionFalse
cond.Message = fmt.Sprintf("No ReferenceGrants found in namespace %s for BackendRef %s/%s", bRefNamespace, bRefNamespace, bRef.Name)
conditionSet = true
break
}
if !permitted {
log.Debug(logger, "BackendRef not permitted by ReferenceGrant", "namespace", bRefNamespace, "name", bRef.Name)
cond.Reason = string(gwtypes.RouteReasonRefNotPermitted)
cond.Status = metav1.ConditionFalse
cond.Message = fmt.Sprintf("BackendRef %s/%s not permitted by any ReferenceGrant", bRefNamespace, bRef.Name)
conditionSet = true
break
}
}
}
if conditionSet {
break
}
for _, filter := range rule.Filters {
// Only process filters of type ExtensionRef
if filter.Type != gwtypes.HTTPRouteFilterExtensionRef {
continue
}
if filter.ExtensionRef == nil {
log.Debug(logger, "ExtensionRef is nil in filter but type is ExtensionRef, skipping")
continue
}
// ExtensionRef is always in the same namespace as the route.
extRefNamespace := route.Namespace
// Check if the group kind is supported for the reference.
if !IsExtensionRefSupported(filter.ExtensionRef.Group, filter.ExtensionRef.Kind) {
log.Debug(logger, "Unsupported ExtensionRef group/kind", "group", filter.ExtensionRef.Group, "kind", filter.ExtensionRef.Kind)
cond.Reason = string(gwtypes.RouteReasonInvalidKind)
cond.Status = metav1.ConditionFalse
cond.Message = fmt.Sprintf("Unsupported ExtensionRef %s/%s group/kind: %s/%s", extRefNamespace, filter.ExtensionRef.Name, filter.ExtensionRef.Group, filter.ExtensionRef.Kind)
conditionSet = true
break
}
// Check if the referenced object exists.
kongPlugin := configurationv1.KongPlugin{}
err := cl.Get(ctx, client.ObjectKey{Namespace: extRefNamespace, Name: string(filter.ExtensionRef.Name)}, &kongPlugin)
if err != nil {
if apierrors.IsNotFound(err) {
log.Debug(logger, "ExtensionRef not found", "namespace", extRefNamespace, "name", filter.ExtensionRef.Name)
cond.Reason = string(gwtypes.RouteReasonBackendNotFound)
cond.Status = metav1.ConditionFalse
cond.Message = fmt.Sprintf("ExtensionRef %s/%s not found", extRefNamespace, filter.ExtensionRef.Name)
conditionSet = true
break
}
return nil, fmt.Errorf("failed to get ExtensionRef %s/%s: %w", extRefNamespace, filter.ExtensionRef.Name, err)
}
}
}
return SetConditionMeta(*cond, route), nil
}
// The function safely navigates the object's status.conditions array to find a condition with:
// - type: "Programmed"
// - status: "True"
//
// Parameters:
// - obj: An unstructured Kubernetes object that may contain status conditions
//
// Returns:
// - bool: true if the object has a "Programmed" condition with status "True", false otherwise
//
// The function returns false in the following cases:
// - The object has no status.conditions field
// - An error occurs while accessing the conditions
// - No "Programmed" condition is found
// - The "Programmed" condition exists but status is not "True"
//
// This function is commonly used to check if Kong resources (Services, Routes, Upstreams, etc.)
// have been successfully programmed into the Kong data plane.
func isProgrammed(obj *unstructured.Unstructured) bool {
conditions, found, err := unstructured.NestedSlice(obj.Object, "status", "conditions")
if err != nil || !found {
return false
}
for _, conditionInterface := range conditions {
condition, ok := conditionInterface.(map[string]any)
if !ok {
continue
}
conditionType, found, err := unstructured.NestedString(condition, "type")
if err != nil || !found {
continue
}
if conditionType == "Programmed" {
status, found, err := unstructured.NestedString(condition, "status")
if err != nil || !found {
continue
}
return status == "True"
}
}
return false
}
// FilterMatchingListeners filters the provided listeners to find those that match the given ParentReference
// based on section name, port, and protocol requirements. Only listeners that are both matching and ready
// are returned.
//
// The function performs the following checks for each listener:
// 1. Matches the section name specified in the ParentReference (if any)
// 2. Matches the port specified in the ParentReference (if any)
// 3. Supports HTTP/HTTPS protocol with appropriate TLS termination mode
// 4. Is in a "Programmed" (ready) state according to the Gateway status
//
// Parameters:
// - gw: The Gateway object containing the listeners and their status
// - logger: Logger for debugging information
// - pRef: The ParentReference specifying matching criteria
// - listeners: The list of listeners from the Gateway spec to filter
//
// Returns:
// - []gwtypes.Listener: List of listeners that match criteria and are ready
// - *metav1.Condition: Condition indicating why no listeners matched (nil if matches found)
//
// The returned condition will have status "False" with reason "NoMatchingParent" if no listeners
// match the criteria. If listeners match but are not ready, the message will indicate this distinction.
func FilterMatchingListeners(logger logr.Logger, gw *gwtypes.Gateway, pRef gwtypes.ParentReference, listeners []gwtypes.Listener) ([]gwtypes.Listener, *metav1.Condition) {
var matchingListeners []gwtypes.Listener
var matchedNotReady bool
for _, listener := range listeners {
// Check if the listener name matches the section name of the parent reference.
if pRef.SectionName != nil && *pRef.SectionName != listener.Name {
continue
}
// Check if the parent reference port matches the listener port, if specified.
if pRef.Port != nil && *pRef.Port != listener.Port {
continue
}
// Check if the protocol matches.
// HTTPRoutes support Terminate only
// Note: this is a guess we are doing as the upstream documentation is unclear at the moment.
// see https://github.com/kubernetes-sigs/gateway-api/issues/1474
if listener.Protocol != gwtypes.HTTPProtocolType && listener.Protocol != gwtypes.HTTPSProtocolType {
continue
}
if listener.TLS != nil && *listener.TLS.Mode != gwtypes.TLSModeTerminate {
continue
}
// At this point, the listener matches the parent reference.
log.Debug(logger, "Listener matches ParentReference criteria", "listener", listener.Name, "parentRef", pRef)
// Now check if the listener is ready.
for _, ls := range gw.Status.Listeners {
if ls.Name == listener.Name {
for _, cond := range ls.Conditions {
if cond.Type == string(gwtypes.ListenerConditionProgrammed) {
if cond.Status == metav1.ConditionTrue {
log.Debug(logger, "Listener is ready (programmed)", "listener", listener.Name)
matchingListeners = append(matchingListeners, listener)
} else {
log.Debug(logger, "Listener matched but is not ready", "listener", listener.Name)
// Listener is not ready, and we track that at least one listener matched but is not ready.
matchedNotReady = true
}
}
}
}
}
}
// If we found no matching listeners, determine the appropriate condition to return.
if len(matchingListeners) == 0 {
// If we had at least one listener that matched but was not ready, return a condition indicating that.
msg := string(gwtypes.RouteReasonNoMatchingParent)
if matchedNotReady {
msg = "A Gateway Listener matches this route but is not ready"
}
log.Debug(logger, "No matching listeners found for ParentReference", "parentRef", pRef, "matchedNotReady", matchedNotReady)
return nil, &metav1.Condition{
Type: string(gwtypes.RouteConditionAccepted),
Status: metav1.ConditionFalse,
Reason: string(gwtypes.RouteReasonNoMatchingParent),
Message: msg,
}
}
// Return the list of matching and ready listeners that can be used for further processing.
log.Debug(logger, "Matching and ready listeners found", "parentRef", pRef, "count", len(matchingListeners))
return matchingListeners, nil
}
// FilterListenersByAllowedRoutes filters the provided listeners to find those that allow the given HTTPRoute based on its kind and namespace.
// The function checks each listener's AllowedRoutes configuration to determine if the route is permitted.
//
// The function performs the following validation steps:
// 1. Checks if the route kind is allowed by the listener's AllowedRoutes.Kinds
// 2. Checks if the route namespace is allowed by the listener's AllowedRoutes.Namespaces configuration
// 3. Handles different namespace selection modes (All, Same, Selector)
//
// Parameters:
// - gw: The Gateway object containing the listeners
// - logger: Logger for debugging information
// - pRef: The ParentReference being evaluated
// - listeners: The list of listeners to filter
// - rgk: The RouteGroupKind of the route being validated
// - routeNamespace: The namespace object of the route
//
// Returns:
// - []gwtypes.Listener: List of listeners that allow this route
// - *metav1.Condition: Condition indicating why no listeners allow the route (nil if matches found)
// - error: Any error that occurred during validation (e.g., invalid label selector)
func FilterListenersByAllowedRoutes(logger logr.Logger, gw *gwtypes.Gateway, pRef gwtypes.ParentReference, listeners []gwtypes.Listener, rgk gwtypes.RouteGroupKind, routeNamespace *corev1.Namespace) ([]gwtypes.Listener, *metav1.Condition, error) {
var matchingListeners []gwtypes.Listener
for _, listener := range listeners {
if listener.AllowedRoutes == nil {
// If AllowedRoutes is nil, all routes are allowed.
log.Debug(logger, "Listener allows all routes (AllowedRoutes is nil)", "listener", listener.Name)
matchingListeners = append(matchingListeners, listener)
continue
}
// Check if the route kind is allowed.
if len(listener.AllowedRoutes.Kinds) > 0 {
matched := false
for _, allowedKind := range listener.AllowedRoutes.Kinds {
if (allowedKind.Group != nil && *allowedKind.Group != *rgk.Group) || allowedKind.Kind != rgk.Kind {
continue
} else {
log.Debug(logger, "Listener allows route kind", "listener", listener.Name, "allowedKind", allowedKind, "routeKind", rgk)
matched = true
break
}
}
if !matched {
log.Debug(logger, "Listener does not allow route kind", "listener", listener.Name, "routeKind", rgk)
// If no allowed kind matched, we can't use this listener.
continue
}
}
// Check if the route namespace is allowed.
if listener.AllowedRoutes.Namespaces == nil || listener.AllowedRoutes.Namespaces.From == nil {
// If Namespaces or From is nil, all namespaces are allowed.
log.Debug(logger, "Listener allows all namespaces (Namespaces or From is nil)", "listener", listener.Name)
matchingListeners = append(matchingListeners, listener)
continue
}
switch *listener.AllowedRoutes.Namespaces.From {
case gwtypes.NamespacesFromAll:
// All namespaces are allowed.
log.Debug(logger, "Listener allows all namespaces (NamespacesFromAll)", "listener", listener.Name)
matchingListeners = append(matchingListeners, listener)
case gwtypes.NamespacesFromSame:
// Only the same namespace as the gateway is allowed.
if (pRef.Namespace != nil && string(*pRef.Namespace) == routeNamespace.Name) || (pRef.Namespace == nil && gw.Namespace == routeNamespace.Name) {
log.Debug(logger, "Listener allows same namespace as gateway", "listener", listener.Name, "routeNamespace", routeNamespace.Name)
matchingListeners = append(matchingListeners, listener)
}
case gwtypes.NamespacesFromSelector:
// Only namespaces matching the selector are allowed.
if listener.AllowedRoutes.Namespaces.Selector == nil {
log.Debug(logger, "Listener has NamespacesFromSelector but selector is nil", "listener", listener.Name)
// If Selector is nil, no namespaces are allowed.
continue
}
selector, err := metav1.LabelSelectorAsSelector(listener.AllowedRoutes.Namespaces.Selector)
if err != nil {
log.Error(logger, err, "Failed to convert AllowedRoutes.Namespaces.Selector", "listener", listener.Name, "selector", listener.AllowedRoutes.Namespaces.Selector)
return nil, nil, fmt.Errorf("failed to convert AllowedRoutes.Namespaces.Selector %s to selector for listener %s for gateway %s: %w",
listener.AllowedRoutes.Namespaces.Selector, listener.Name, client.ObjectKeyFromObject(gw), err)
}
if selector.Matches(labels.Set(routeNamespace.Labels)) {
log.Debug(logger, "Listener allows route namespace by selector", "listener", listener.Name, "routeNamespace", routeNamespace.Name)
matchingListeners = append(matchingListeners, listener)
}
default:
// Unknown value for From, skip this listener.
return nil, nil, fmt.Errorf("unknown value for AllowedRoutes.Namespaces.From: %s for listener %s for gateway %s",
*listener.AllowedRoutes.Namespaces.From, listener.Name, client.ObjectKeyFromObject(gw))
}
}
// If we found no matching listeners, return a condition indicating the reason.
if len(matchingListeners) == 0 {
log.Debug(logger, "No listeners allow this route", "parentRef", pRef, "routeKind", rgk, "routeNamespace", routeNamespace.Name)
return nil, &metav1.Condition{
Type: string(gwtypes.RouteConditionAccepted),
Status: metav1.ConditionFalse,
Reason: string(gwtypes.RouteReasonNotAllowedByListeners),
Message: "No Gateway Listener allows this route",
}, nil
}
// Return the list of matching listeners that can be used for further processing.
log.Debug(logger, "Listeners found that allow this route", "parentRef", pRef, "count", len(matchingListeners))
return matchingListeners, nil, nil
}
// FilterListenersByHostnames filters the provided listeners to find those that match any of the given hostnames.
// The function checks if there is an intersection between the listener's hostname and the route's hostnames.
// If a listener has no hostname specified, it matches all hostnames (wildcard behavior).
//
// The function performs hostname intersection validation:
// 1. If listener has no hostname, it accepts all route hostnames
// 2. For each route hostname, checks if it intersects with the listener hostname
// 3. Uses hostname intersection logic to handle wildcards and exact matches
//
// Parameters:
// - listeners: The list of listeners to filter based on hostname matching
// - logger: Logger for debugging information
// - hostnames: The list of hostnames from the HTTPRoute spec to match against
//
// Returns:
// - []gwtypes.Listener: List of listeners that have hostname intersection with the route
// - *metav1.Condition: Condition indicating why no listeners matched hostnames (nil if matches found)
//
// The returned condition will have status "False" with reason "NoMatchingListenerHostname" if no listeners
// have hostname intersection with the route. If matching listeners are found, the condition will be nil.
func FilterListenersByHostnames(logger logr.Logger, listeners []gwtypes.Listener, hostnames []gwtypes.Hostname) ([]gwtypes.Listener, *metav1.Condition) {
var matchingListeners []gwtypes.Listener
for _, listener := range listeners {
// If the listener has no hostname, it matches all hostnames.
if listener.Hostname == nil || *listener.Hostname == "" {
log.Debug(logger, "Listener matches all hostnames (wildcard)", "listener", listener.Name)
matchingListeners = append(matchingListeners, listener)
continue
}
// Check if any of the route hostnames match the listener hostname.
for _, hostname := range hostnames {
routeHostname := string(hostname)
if intersection := utils.HostnameIntersection(string(*listener.Hostname), routeHostname); intersection != "" {
log.Debug(logger, "Listener matches route hostname", "listener", listener.Name, "listenerHostname", *listener.Hostname, "routeHostname", routeHostname)
matchingListeners = append(matchingListeners, listener)
break
}
log.Debug(logger, "Listener does not match route hostname", "listener", listener.Name, "listenerHostname", *listener.Hostname, "routeHostname", routeHostname)
}
}
if len(matchingListeners) == 0 {
log.Debug(logger, "No listeners match route hostnames", "hostnames", hostnames)
return nil, &metav1.Condition{
Type: string(gwtypes.RouteConditionAccepted),
Status: metav1.ConditionFalse,
Reason: string(gwtypes.RouteReasonNoMatchingListenerHostname),
Message: "No Gateway Listener hostname matches this route",
}
}
log.Debug(logger, "Listeners found that match route hostnames", "count", len(matchingListeners), "hostnames", hostnames)
return matchingListeners, nil
}
// GetRouteGroupKind returns the RouteGroupKind for a given route object, ensuring the group is set to the Gateway API default if empty.
// This function extracts the GroupVersionKind from the route object and converts it to the Gateway API RouteGroupKind format.
// If the group is empty, it defaults to gwtypes.GroupName which is the standard Gateway API group.
//
// Parameters:
// - route: The route object (HTTPRoute, GRPCRoute, etc.) to extract GroupKind information from
//
// Returns:
// - gwtypes.RouteGroupKind: The RouteGroupKind with proper group and kind set for Gateway API validation
//
// This function is typically used when validating routes against Gateway listeners' AllowedRoutes configuration.
func GetRouteGroupKind(route client.Object) gwtypes.RouteGroupKind {
gvk := route.GetObjectKind().GroupVersionKind()
group := gvk.Group
if group == "" {
group = gwtypes.GroupName
}
grp := gwtypes.Group(group)
return gwtypes.RouteGroupKind{
Group: &grp,
Kind: gwtypes.Kind(gvk.Kind),
}
}
// SetConditionMeta sets the ObservedGeneration and LastTransitionTime fields on a condition using the given route.
// This function populates metadata fields that are required for proper condition tracking in Kubernetes resources.
//
// The function sets:
// - ObservedGeneration: Set to the route's current generation to indicate which version was observed
// - LastTransitionTime: Set to the current timestamp to track when the condition was last updated
//
// Parameters:
// - cond: The condition to update with metadata
// - route: The HTTPRoute object to extract generation information from
//
// Returns:
// - *metav1.Condition: Pointer to the updated condition with metadata fields set
//
// This function is typically called before setting conditions in route status to ensure proper
// condition metadata tracking according to Kubernetes conventions.
func SetConditionMeta(cond metav1.Condition, route *gwtypes.HTTPRoute) *metav1.Condition {
cond.ObservedGeneration = route.Generation
cond.LastTransitionTime = metav1.Now()
return &cond
}
// FilterOutGVKByKind returns a new slice of GVKs with the specified kind removed.
// It matches Kind == kindToFilter and filters those out.
func FilterOutGVKByKind(expectedGVKs []schema.GroupVersionKind, kindToFilter string) []schema.GroupVersionKind {
var filtered []schema.GroupVersionKind
for _, gvk := range expectedGVKs {
if gvk.Kind != kindToFilter {
filtered = append(filtered, gvk)
}
}
return filtered
}
// backendRefGroupKind returns the effective group and kind for a BackendRef,
// applying Gateway API defaults: kind defaults to "Service" and group defaults
// to "" (core) when nil or empty.
func backendRefGroupKind(group *gwtypes.Group, kind *gwtypes.Kind) (string, string) {
g := string(lo.FromPtr(group))
k := string(lo.FromPtr(kind))
if k == "" {
k = "Service"
}
return g, k
}
// IsBackendRefSupported returns true if the BackendRef group and kind are supported by Gateway API.
// Only core "Service" is supported.
func IsBackendRefSupported(group *gwtypes.Group, kind *gwtypes.Kind) bool {
g, k := backendRefGroupKind(group, kind)
return (g == "" || g == "core") && k == "Service"
}
// IsExtensionRefSupported returns true if the ExtensionRef group and kind are supported by the Kong Gateway API implementation.
// Only "configuration.konghq.com/v1" group and "KongPlugin" kind are supported.
func IsExtensionRefSupported(group gwtypes.Group, kind gwtypes.Kind) bool {
return group == "configuration.konghq.com" && kind == "KongPlugin"
}
// IsHTTPReferenceGranted checks if a ReferenceGrant permits an HTTPRoute to reference a backend in another namespace.
// It validates that the ReferenceGrant's 'from' section matches the HTTPRoute and source namespace,
// and that the 'to' section matches the backend's group, kind, and name.
// Returns true if the reference is permitted, false otherwise.
//
// Parameters:
// - grantSpec: The ReferenceGrant spec to check
// - backendRef: The HTTPBackendRef being referenced
// - fromNamespace: The namespace of the HTTPRoute making the reference
//
// Returns:
// - bool: true if the reference is permitted by the grant, false otherwise
func IsHTTPReferenceGranted(grantSpec gwtypes.ReferenceGrantSpec, backendRef gwtypes.HTTPBackendRef, fromNamespace string) bool {
bRefGroup, bRefKind := backendRefGroupKind(backendRef.Group, backendRef.Kind)
for _, from := range grantSpec.From {
if from.Group != gwtypes.GroupName || from.Kind != "HTTPRoute" || fromNamespace != string(from.Namespace) {
continue
}
for _, to := range grantSpec.To {
toGroup := string(to.Group)
if toGroup == "" {
toGroup = "core"
}
if bRefGroup == "" {
bRefGroup = "core"
}
if gwtypes.Group(bRefGroup) == gwtypes.Group(toGroup) &&
gwtypes.Kind(bRefKind) == to.Kind &&
(to.Name == nil || *to.Name == backendRef.Name) {
return true
}
}
}
return false
}
// CheckReferenceGrant checks if a cross-namespace BackendRef is permitted by ReferenceGrants.
// This function assumes the BackendRef is cross-namespace and requires the namespace to be explicitly set.
//
// The function performs the following checks:
// 1. Validates that the BackendRef has a namespace set (required for cross-namespace checks)
// 2. Lists all ReferenceGrants in the target namespace
// 3. Checks if any ReferenceGrant permits the HTTPRoute to access the BackendRef
//
// Returns:
// - permitted: true if a ReferenceGrant allows the cross-namespace access
// - found: true if ReferenceGrants exist in the target namespace (regardless of permission)
// - err: any error that occurred during ReferenceGrant lookup
//
// Note: This function does NOT check if namespaces are the same - it assumes cross-namespace