-
Notifications
You must be signed in to change notification settings - Fork 347
/
translator.go
1254 lines (1104 loc) · 40.8 KB
/
translator.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
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 gatewayapi
import (
"fmt"
"net/netip"
"sort"
"strings"
"golang.org/x/exp/slices"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
"sigs.k8s.io/gateway-api/apis/v1alpha2"
"sigs.k8s.io/gateway-api/apis/v1beta1"
"github.com/envoyproxy/gateway/internal/ir"
)
const (
KindGateway = "Gateway"
KindHTTPRoute = "HTTPRoute"
KindService = "Service"
KindSecret = "Secret"
// OwningGatewayNamespaceLabel is the owner reference label used for managed infra.
// The value should be the namespace of the accepted Envoy Gateway.
OwningGatewayNamespaceLabel = "gateway.envoyproxy.io/owning-gateway-namespace"
// OwningGatewayNameLabel is the owner reference label used for managed infra.
// The value should be the name of the accepted Envoy Gateway.
OwningGatewayNameLabel = "gateway.envoyproxy.io/owning-gateway-name"
// minEphemeralPort is the first port in the ephemeral port range.
minEphemeralPort = 1024
// wellKnownPortShift is the constant added to the well known port (1-1023)
// to convert it into an ephemeral port.
wellKnownPortShift = 10000
)
type XdsIRMap map[string]*ir.Xds
type InfraIRMap map[string]*ir.Infra
// Resources holds the Gateway API and related
// resources that the translators needs as inputs.
type Resources struct {
Gateways []*v1beta1.Gateway
HTTPRoutes []*v1beta1.HTTPRoute
ReferenceGrants []*v1alpha2.ReferenceGrant
Namespaces []*v1.Namespace
Services []*v1.Service
Secrets []*v1.Secret
}
func (r *Resources) GetNamespace(name string) *v1.Namespace {
for _, ns := range r.Namespaces {
if ns.Name == name {
return ns
}
}
return nil
}
func (r *Resources) GetService(namespace, name string) *v1.Service {
for _, svc := range r.Services {
if svc.Namespace == namespace && svc.Name == name {
return svc
}
}
return nil
}
func (r *Resources) GetSecret(namespace, name string) *v1.Secret {
for _, secret := range r.Secrets {
if secret.Namespace == namespace && secret.Name == name {
return secret
}
}
return nil
}
// Translator translates Gateway API resources to IRs and computes status
// for Gateway API resources.
type Translator struct {
GatewayClassName v1beta1.ObjectName
}
type TranslateResult struct {
Gateways []*v1beta1.Gateway
HTTPRoutes []*v1beta1.HTTPRoute
XdsIR XdsIRMap
InfraIR InfraIRMap
}
func newTranslateResult(gateways []*GatewayContext, httpRoutes []*HTTPRouteContext, xdsIR XdsIRMap, infraIR InfraIRMap) *TranslateResult {
translateResult := &TranslateResult{
XdsIR: xdsIR,
InfraIR: infraIR,
}
for _, gateway := range gateways {
translateResult.Gateways = append(translateResult.Gateways, gateway.Gateway)
}
for _, httpRoute := range httpRoutes {
translateResult.HTTPRoutes = append(translateResult.HTTPRoutes, httpRoute.HTTPRoute)
}
return translateResult
}
func (t *Translator) Translate(resources *Resources) *TranslateResult {
xdsIR := make(XdsIRMap)
infraIR := make(InfraIRMap)
// Get Gateways belonging to our GatewayClass.
gateways := t.GetRelevantGateways(resources.Gateways)
// Process all Listeners for all relevant Gateways.
t.ProcessListeners(gateways, xdsIR, infraIR, resources)
// Process all relevant HTTPRoutes.
httpRoutes := t.ProcessHTTPRoutes(resources.HTTPRoutes, gateways, resources, xdsIR)
return newTranslateResult(gateways, httpRoutes, xdsIR, infraIR)
}
func (t *Translator) GetRelevantGateways(gateways []*v1beta1.Gateway) []*GatewayContext {
var relevant []*GatewayContext
for _, gateway := range gateways {
if gateway == nil {
panic("received nil gateway")
}
if gateway.Spec.GatewayClassName == t.GatewayClassName {
gc := &GatewayContext{
Gateway: gateway.DeepCopy(),
}
for _, listener := range gateway.Spec.Listeners {
l := gc.GetListenerContext(listener.Name)
// Reset attached route count since it will be recomputed during translation.
l.ResetAttachedRoutes()
}
relevant = append(relevant, gc)
}
}
return relevant
}
type portListeners struct {
listeners []*ListenerContext
protocols sets.String
hostnames map[string]int
}
func (t *Translator) ProcessListeners(gateways []*GatewayContext, xdsIR XdsIRMap, infraIR InfraIRMap, resources *Resources) {
// Iterate through all listeners and collect info about protocols
// and hostnames per port.
for _, gateway := range gateways {
portListenerInfo := map[v1beta1.PortNumber]*portListeners{}
for _, listener := range gateway.listeners {
if portListenerInfo[listener.Port] == nil {
portListenerInfo[listener.Port] = &portListeners{
protocols: sets.NewString(),
hostnames: map[string]int{},
}
}
portListenerInfo[listener.Port].listeners = append(portListenerInfo[listener.Port].listeners, listener)
var protocol string
switch listener.Protocol {
// HTTPS and TLS can co-exist on the same port
case v1beta1.HTTPSProtocolType, v1beta1.TLSProtocolType:
protocol = "https/tls"
default:
protocol = string(listener.Protocol)
}
portListenerInfo[listener.Port].protocols.Insert(protocol)
var hostname string
if listener.Hostname != nil {
hostname = string(*listener.Hostname)
}
portListenerInfo[listener.Port].hostnames[hostname]++
}
// Set Conflicted conditions for any listeners with conflicting specs.
for _, info := range portListenerInfo {
for _, listener := range info.listeners {
if len(info.protocols) > 1 {
listener.SetCondition(
v1beta1.ListenerConditionConflicted,
metav1.ConditionTrue,
v1beta1.ListenerReasonProtocolConflict,
"All listeners for a given port must use a compatible protocol",
)
}
var hostname string
if listener.Hostname != nil {
hostname = string(*listener.Hostname)
}
if info.hostnames[hostname] > 1 {
listener.SetCondition(
v1beta1.ListenerConditionConflicted,
metav1.ConditionTrue,
v1beta1.ListenerReasonHostnameConflict,
"All listeners for a given port must use a unique hostname",
)
}
}
}
}
// Iterate through all listeners to validate spec
// and compute status for each, and add valid ones
// to the Xds IR.
for _, gateway := range gateways {
// init IR per gateway
irKey := irStringKey(gateway.Gateway)
gwXdsIR := &ir.Xds{}
gwInfraIR := ir.NewInfra()
gwInfraIR.Proxy.Name = irKey
gwInfraIR.Proxy.GetProxyMetadata().Labels = GatewayOwnerLabels(gateway.Namespace, gateway.Name)
// save the IR references in the map before the translation starts
xdsIR[irKey] = gwXdsIR
infraIR[irKey] = gwInfraIR
// Infra IR proxy ports must be unique.
var foundPorts []int32
for _, listener := range gateway.listeners {
// Process protocol & supported kinds
switch listener.Protocol {
case v1beta1.HTTPProtocolType, v1beta1.HTTPSProtocolType:
if listener.AllowedRoutes == nil || len(listener.AllowedRoutes.Kinds) == 0 {
listener.SetSupportedKinds(v1beta1.RouteGroupKind{Group: GroupPtr(v1beta1.GroupName), Kind: KindHTTPRoute})
} else {
for _, kind := range listener.AllowedRoutes.Kinds {
if kind.Group != nil && string(*kind.Group) != v1beta1.GroupName {
listener.SetCondition(
v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalidRouteKinds,
fmt.Sprintf("Group is not supported, group must be %s", v1beta1.GroupName),
)
}
if kind.Kind != KindHTTPRoute {
listener.SetCondition(
v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalidRouteKinds,
fmt.Sprintf("Kind is not supported, kind must be %s", KindHTTPRoute),
)
}
}
}
default:
listener.SetCondition(
v1beta1.ListenerConditionDetached,
metav1.ConditionTrue,
v1beta1.ListenerReasonUnsupportedProtocol,
fmt.Sprintf("Protocol %s is unsupported, must be %s or %s.", listener.Protocol, v1beta1.HTTPProtocolType, v1beta1.HTTPSProtocolType),
)
}
// Validate allowed namespaces
if listener.AllowedRoutes != nil &&
listener.AllowedRoutes.Namespaces != nil &&
listener.AllowedRoutes.Namespaces.From != nil &&
*listener.AllowedRoutes.Namespaces.From == v1beta1.NamespacesFromSelector {
if listener.AllowedRoutes.Namespaces.Selector == nil {
listener.SetCondition(
v1beta1.ListenerConditionReady,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalid,
"The allowedRoutes.namespaces.selector field must be specified when allowedRoutes.namespaces.from is set to \"Selector\".",
)
} else {
selector, err := metav1.LabelSelectorAsSelector(listener.AllowedRoutes.Namespaces.Selector)
if err != nil {
listener.SetCondition(
v1beta1.ListenerConditionReady,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalid,
fmt.Sprintf("The allowedRoutes.namespaces.selector could not be parsed: %v.", err),
)
}
listener.namespaceSelector = selector
}
}
// Process TLS configuration
switch listener.Protocol {
case v1beta1.HTTPProtocolType:
if listener.TLS != nil {
listener.SetCondition(
v1beta1.ListenerConditionReady,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalid,
fmt.Sprintf("Listener must not have TLS set when protocol is %s.", listener.Protocol),
)
}
case v1beta1.HTTPSProtocolType:
if listener.TLS == nil {
listener.SetCondition(
v1beta1.ListenerConditionReady,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalid,
fmt.Sprintf("Listener must have TLS set when protocol is %s.", listener.Protocol),
)
break
}
if listener.TLS.Mode != nil && *listener.TLS.Mode != v1beta1.TLSModeTerminate {
listener.SetCondition(
v1beta1.ListenerConditionReady,
metav1.ConditionFalse,
"UnsupportedTLSMode",
fmt.Sprintf("TLS %s mode is not supported, TLS mode must be Terminate.", *listener.TLS.Mode),
)
break
}
if len(listener.TLS.CertificateRefs) != 1 {
listener.SetCondition(
v1beta1.ListenerConditionReady,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalid,
"Listener must have exactly 1 TLS certificate ref",
)
break
}
certificateRef := listener.TLS.CertificateRefs[0]
if certificateRef.Group != nil && string(*certificateRef.Group) != "" {
listener.SetCondition(
v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalidCertificateRef,
"Listener's TLS certificate ref group must be unspecified/empty.",
)
break
}
if certificateRef.Kind != nil && string(*certificateRef.Kind) != KindSecret {
listener.SetCondition(
v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalidCertificateRef,
fmt.Sprintf("Listener's TLS certificate ref kind must be %s.", KindSecret),
)
break
}
secretNamespace := listener.gateway.Namespace
if certificateRef.Namespace != nil && string(*certificateRef.Namespace) != "" && string(*certificateRef.Namespace) != listener.gateway.Namespace {
if !isValidCrossNamespaceRef(
crossNamespaceFrom{
group: string(v1beta1.GroupName),
kind: KindGateway,
namespace: listener.gateway.Namespace,
},
crossNamespaceTo{
group: "",
kind: KindSecret,
namespace: string(*certificateRef.Namespace),
name: string(certificateRef.Name),
},
resources.ReferenceGrants,
) {
listener.SetCondition(
v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalidCertificateRef,
fmt.Sprintf("Certificate ref to secret %s/%s not permitted by any ReferenceGrant", *certificateRef.Namespace, certificateRef.Name),
)
break
}
secretNamespace = string(*certificateRef.Namespace)
}
secret := resources.GetSecret(secretNamespace, string(certificateRef.Name))
if secret == nil {
listener.SetCondition(
v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalidCertificateRef,
fmt.Sprintf("Secret %s/%s does not exist.", listener.gateway.Namespace, certificateRef.Name),
)
break
}
if secret.Type != v1.SecretTypeTLS {
listener.SetCondition(
v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalidCertificateRef,
fmt.Sprintf("Secret %s/%s must be of type %s.", listener.gateway.Namespace, certificateRef.Name, v1.SecretTypeTLS),
)
break
}
if len(secret.Data[v1.TLSCertKey]) == 0 || len(secret.Data[v1.TLSPrivateKeyKey]) == 0 {
listener.SetCondition(
v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalidCertificateRef,
fmt.Sprintf("Secret %s/%s must contain %s and %s.", listener.gateway.Namespace, certificateRef.Name, v1.TLSCertKey, v1.TLSPrivateKeyKey),
)
break
}
listener.SetTLSSecret(secret)
}
lConditions := listener.GetConditions()
if len(lConditions) == 0 {
listener.SetCondition(v1beta1.ListenerConditionReady, metav1.ConditionTrue, v1beta1.ListenerReasonReady, "Listener is ready")
// Any condition on the listener apart from Ready=true indicates an error.
} else if !(lConditions[0].Type == string(v1beta1.ListenerConditionReady) && lConditions[0].Status == metav1.ConditionTrue) {
// set "Ready: false" if it's not set already.
var hasReadyCond bool
for _, existing := range lConditions {
if existing.Type == string(v1beta1.ListenerConditionReady) {
hasReadyCond = true
break
}
}
if !hasReadyCond {
listener.SetCondition(
v1beta1.ListenerConditionReady,
metav1.ConditionFalse,
v1beta1.ListenerReasonInvalid,
"Listener is invalid, see other Conditions for details.",
)
}
// skip computing IR
continue
}
servicePort := int32(listener.Port)
containerPort := servicePortToContainerPort(servicePort)
// Add the listener to the Xds IR.
irListener := &ir.HTTPListener{
Name: irListenerName(listener),
Address: "0.0.0.0",
Port: uint32(containerPort),
TLS: irTLSConfig(listener.tlsSecret),
}
if listener.Hostname != nil {
irListener.Hostnames = append(irListener.Hostnames, string(*listener.Hostname))
} else {
// Hostname specifies the virtual hostname to match for protocol types that define this concept.
// When unspecified, all hostnames are matched. This field is ignored for protocols that don’t require hostname based matching.
// see more https://gateway-api.sigs.k8s.io/references/spec/#gateway.networking.k8s.io/v1beta1.Listener.
irListener.Hostnames = append(irListener.Hostnames, "*")
}
gwXdsIR.HTTP = append(gwXdsIR.HTTP, irListener)
// Add the listener to the Infra IR. Infra IR ports must have a unique port number.
if !slices.Contains(foundPorts, servicePort) {
foundPorts = append(foundPorts, servicePort)
proto := ir.HTTPProtocolType
if listener.Protocol == v1beta1.HTTPSProtocolType {
proto = ir.HTTPSProtocolType
}
infraPort := ir.ListenerPort{
Name: irInfraPortName(listener),
Protocol: proto,
ServicePort: servicePort,
ContainerPort: containerPort,
}
// Only 1 listener is supported.
gwInfraIR.Proxy.Listeners[0].Ports = append(gwInfraIR.Proxy.Listeners[0].Ports, infraPort)
}
}
// sort result to ensure translation does not change across reboots.
sort.Slice(xdsIR[irKey].HTTP, func(i, j int) bool { return xdsIR[irKey].HTTP[i].Name < xdsIR[irKey].HTTP[j].Name })
}
}
// servicePortToContainerPort translates a service port into an ephemeral
// container port.
func servicePortToContainerPort(servicePort int32) int32 {
// If the service port is a privileged port (1-1023)
// add a constant to the value converting it into an ephemeral port.
// This allows the container to bind to the port without needing a
// CAP_NET_BIND_SERVICE capability.
if servicePort < minEphemeralPort {
return servicePort + wellKnownPortShift
}
return servicePort
}
// buildRuleRouteDest takes a backendRef and translates it into a destination or sets error statuses and
// returns the weight for the backend so that 500 error responses can be returned for invalid backends in
// the same proportion as the backend would have otherwise received
func buildRuleRouteDest(backendRef v1beta1.HTTPBackendRef,
parentRef *RouteParentContext,
httpRoute *HTTPRouteContext,
resources *Resources) (destination *ir.RouteDestination, backendWeight uint32) {
weight := uint32(1)
if backendRef.Weight != nil {
weight = uint32(*backendRef.Weight)
}
if backendRef.Group != nil && *backendRef.Group != "" {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonInvalidKind,
"Group is invalid, only the core API group (specified by omitting the group field or setting it to an empty string) is supported",
)
return nil, weight
}
if backendRef.Kind != nil && *backendRef.Kind != KindService {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonInvalidKind,
"Kind is invalid, only Service is supported",
)
return nil, weight
}
if backendRef.Namespace != nil && string(*backendRef.Namespace) != "" && string(*backendRef.Namespace) != httpRoute.Namespace {
if !isValidCrossNamespaceRef(
crossNamespaceFrom{
group: v1beta1.GroupName,
kind: KindHTTPRoute,
namespace: httpRoute.Namespace,
},
crossNamespaceTo{
group: "",
kind: KindService,
namespace: string(*backendRef.Namespace),
name: string(backendRef.Name),
},
resources.ReferenceGrants,
) {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonRefNotPermitted,
fmt.Sprintf("Backend ref to service %s/%s not permitted by any ReferenceGrant", *backendRef.Namespace, backendRef.Name),
)
return nil, weight
}
}
if backendRef.Port == nil {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
"PortNotSpecified",
"A valid port number corresponding to a port on the Service must be specified",
)
return nil, weight
}
service := resources.GetService(NamespaceDerefOr(backendRef.Namespace, httpRoute.Namespace), string(backendRef.Name))
if service == nil {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonBackendNotFound,
fmt.Sprintf("Service %s/%s not found", NamespaceDerefOr(backendRef.Namespace, httpRoute.Namespace), string(backendRef.Name)),
)
return nil, weight
}
var portFound bool
for _, port := range service.Spec.Ports {
if port.Port == int32(*backendRef.Port) {
portFound = true
break
}
}
if !portFound {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
"PortNotFound",
fmt.Sprintf("Port %d not found on service %s/%s", *backendRef.Port, NamespaceDerefOr(backendRef.Namespace, httpRoute.Namespace), string(backendRef.Name)),
)
return nil, weight
}
return &ir.RouteDestination{
Host: service.Spec.ClusterIP,
Port: uint32(*backendRef.Port),
Weight: weight,
}, weight
}
func (t *Translator) ProcessHTTPRoutes(httpRoutes []*v1beta1.HTTPRoute, gateways []*GatewayContext, resources *Resources, xdsIR XdsIRMap) []*HTTPRouteContext {
var relevantHTTPRoutes []*HTTPRouteContext
for _, h := range httpRoutes {
if h == nil {
panic("received nil httproute")
}
httpRoute := &HTTPRouteContext{HTTPRoute: h}
// Find out if this route attaches to one of our Gateway's listeners,
// and if so, get the list of listeners that allow it to attach for each
// parentRef.
var relevantRoute bool
for _, parentRef := range httpRoute.Spec.ParentRefs {
isRelevantParentRef, selectedListeners := GetReferencedListeners(parentRef, gateways)
// Parent ref is not to a Gateway that we control: skip it
if !isRelevantParentRef {
continue
}
relevantRoute = true
parentRefCtx := httpRoute.GetRouteParentContext(parentRef)
if !HasReadyListener(selectedListeners) {
parentRefCtx.SetCondition(v1beta1.RouteConditionAccepted, metav1.ConditionFalse, "NoReadyListeners", "There are no ready listeners for this parent ref")
continue
}
var allowedListeners []*ListenerContext
for _, listener := range selectedListeners {
if listener.AllowsKind(v1beta1.RouteGroupKind{Group: GroupPtr(v1beta1.GroupName), Kind: KindHTTPRoute}) && listener.AllowsNamespace(resources.GetNamespace(httpRoute.Namespace)) {
allowedListeners = append(allowedListeners, listener)
}
}
if len(allowedListeners) == 0 {
parentRefCtx.SetCondition(v1beta1.RouteConditionAccepted, metav1.ConditionFalse, v1beta1.RouteReasonNotAllowedByListeners, "No listeners included by this parent ref allowed this attachment.")
continue
}
parentRefCtx.SetListeners(allowedListeners...)
parentRefCtx.SetCondition(v1beta1.RouteConditionAccepted, metav1.ConditionTrue, v1beta1.RouteReasonAccepted, "Route is accepted")
}
if !relevantRoute {
continue
}
relevantHTTPRoutes = append(relevantHTTPRoutes, httpRoute)
for _, parentRef := range httpRoute.parentRefs {
// Skip parent refs that did not accept the route
if !parentRef.IsAccepted() {
continue
}
// Need to compute Route rules within the parentRef loop because
// any conditions that come out of it have to go on each RouteParentStatus,
// not on the Route as a whole.
var routeRoutes []*ir.HTTPRoute
// compute matches, filters, backends
for ruleIdx, rule := range httpRoute.Spec.Rules {
var ruleRoutes []*ir.HTTPRoute
// First see if there are any filters in the rules. Then apply those filters to any irRoutes.
var directResponse *ir.DirectResponse
var redirectResponse *ir.Redirect
addRequestHeaders := []ir.AddHeader{}
removeRequestHeaders := []string{}
// Process the filters for this route rule
for _, filter := range rule.Filters {
if directResponse != nil {
break // If an invalid filter type has been configured then skip processing any more filters
}
switch filter.Type {
case v1beta1.HTTPRouteFilterRequestRedirect:
// Can't have two redirects for the same route
if redirectResponse != nil {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"Cannot configure multiple requestRedirect filters for a single HTTPRouteRule",
)
continue
}
redirect := filter.RequestRedirect
if redirect == nil {
break
}
redir := &ir.Redirect{}
if redirect.Scheme != nil {
// Note that gateway API may support additional schemes in the future, but unknown values
// must result in an UnsupportedValue status
if *redirect.Scheme == "http" || *redirect.Scheme == "https" {
redir.Scheme = redirect.Scheme
} else {
errMsg := fmt.Sprintf("Scheme: %s is unsupported, only 'https' and 'http' are supported", *redirect.Scheme)
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
continue
}
}
if redirect.Hostname != nil {
if err := isValidHostname(string(*redirect.Hostname)); err != nil {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
err.Error(),
)
continue
} else {
redirectHost := string(*redirect.Hostname)
redir.Hostname = &redirectHost
}
}
if redirect.Path != nil {
switch redirect.Path.Type {
case v1beta1.FullPathHTTPPathModifier:
if redirect.Path.ReplaceFullPath != nil {
redir.Path = &ir.HTTPPathModifier{
FullReplace: redirect.Path.ReplaceFullPath,
}
}
case v1beta1.PrefixMatchHTTPPathModifier:
if redirect.Path.ReplacePrefixMatch != nil {
redir.Path = &ir.HTTPPathModifier{
PrefixMatchReplace: redirect.Path.ReplacePrefixMatch,
}
}
default:
errMsg := fmt.Sprintf("Redirect path type: %s is invalid, only \"ReplaceFullPath\" and \"ReplacePrefixMatch\" are supported", redirect.Path.Type)
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
continue
}
}
if redirect.StatusCode != nil {
redirectCode := int32(*redirect.StatusCode)
// Envoy supports 302, 303, 307, and 308, but gateway API only includes 301 and 302
if redirectCode == 301 || redirectCode == 302 {
redir.StatusCode = &redirectCode
} else {
errMsg := fmt.Sprintf("Status code %d is invalid, only 302 and 301 are supported", redirectCode)
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
continue
}
}
if redirect.Port != nil {
redirectPort := uint32(*redirect.Port)
redir.Port = &redirectPort
}
redirectResponse = redir
case v1beta1.HTTPRouteFilterRequestHeaderModifier:
// Make sure the header modifier config actually exists
headerModifier := filter.RequestHeaderModifier
if headerModifier == nil {
break
}
emptyFilterConfig := true // keep track of whether the provided config is empty or not
// Add request headers
if headersToAdd := headerModifier.Add; headersToAdd != nil {
if len(headersToAdd) > 0 {
emptyFilterConfig = false
}
for _, addHeader := range headersToAdd {
emptyFilterConfig = false
if addHeader.Name == "" {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"RequestHeaderModifier Filter cannot add a header with an empty name",
)
// try to process the rest of the headers and produce a valid config.
continue
}
// Per Gateway API specification on HTTPHeaderName, : and / are invalid characters in header names
if strings.Contains(string(addHeader.Name), "/") || strings.Contains(string(addHeader.Name), ":") {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
fmt.Sprintf("RequestHeaderModifier Filter cannot set headers with a '/' or ':' character in them. Header: %q", string(addHeader.Name)),
)
continue
}
// Check if the header is a duplicate
headerKey := string(addHeader.Name)
canAddHeader := true
for _, h := range addRequestHeaders {
if strings.EqualFold(h.Name, headerKey) {
canAddHeader = false
break
}
}
if !canAddHeader {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
fmt.Sprintf("RequestHeaderModifier Filter already configures request header: %s to be added, ignoring second entry", headerKey),
)
continue
}
newHeader := ir.AddHeader{
Name: headerKey,
Append: true,
Value: addHeader.Value,
}
addRequestHeaders = append(addRequestHeaders, newHeader)
}
}
// Set headers
if headersToSet := headerModifier.Set; headersToSet != nil {
if len(headersToSet) > 0 {
emptyFilterConfig = false
}
for _, setHeader := range headersToSet {
if setHeader.Name == "" {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"RequestHeaderModifier Filter cannot set a header with an empty name",
)
continue
}
// Per Gateway API specification on HTTPHeaderName, : and / are invalid characters in header names
if strings.Contains(string(setHeader.Name), "/") || strings.Contains(string(setHeader.Name), ":") {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
fmt.Sprintf("RequestHeaderModifier Filter cannot set headers with a '/' or ':' character in them. Header: '%s'", string(setHeader.Name)),
)
continue
}
// Check if the header to be set has already been configured
headerKey := string(setHeader.Name)
canAddHeader := true
for _, h := range addRequestHeaders {
if strings.EqualFold(h.Name, headerKey) {
canAddHeader = false
break
}
}
if !canAddHeader {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
fmt.Sprintf("RequestHeaderModifier Filter already configures request header: %s to be added/set, ignoring second entry", headerKey),
)
continue
}
newHeader := ir.AddHeader{
Name: string(setHeader.Name),
Append: false,
Value: setHeader.Value,
}
addRequestHeaders = append(addRequestHeaders, newHeader)
}
}
// Remove request headers
// As far as Envoy is concerned, it is ok to configure a header to be added/set and also in the list of
// headers to remove. It will remove the original header if present and then add/set the header after.
if headersToRemove := headerModifier.Remove; headersToRemove != nil {
if len(headersToRemove) > 0 {
emptyFilterConfig = false
}
for _, removedHeader := range headersToRemove {
if removedHeader == "" {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"RequestHeaderModifier Filter cannot remove a header with an empty name",
)
continue
}
canRemHeader := true
for _, h := range removeRequestHeaders {
if strings.EqualFold(h, removedHeader) {
canRemHeader = false
break
}
}
if !canRemHeader {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
fmt.Sprintf("RequestHeaderModifier Filter already configures request header: %s to be removed, ignoring second entry", removedHeader),
)
continue
}
removeRequestHeaders = append(removeRequestHeaders, removedHeader)
}
}
// Update the status if the filter failed to configure any valid headers to add/remove
if len(addRequestHeaders) == 0 && len(removeRequestHeaders) == 0 && !emptyFilterConfig {
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"RequestHeaderModifier Filter did not provide valid configuration to add/set/remove any headers",
)
}
default:
// "If a reference to a custom filter type cannot be resolved, the filter MUST NOT be skipped.
// Instead, requests that would have been processed by that filter MUST receive a HTTP error response."
errMsg := fmt.Sprintf("Unknown custom filter type: %s", filter.Type)
parentRef.SetCondition(
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
directResponse = &ir.DirectResponse{
Body: &errMsg,
StatusCode: 500,
}
}
}
// A rule is matched if any one of its matches
// is satisfied (i.e. a logical "OR"), so generate
// a unique Xds IR HTTPRoute per match.
for matchIdx, match := range rule.Matches {
irRoute := &ir.HTTPRoute{
Name: routeName(httpRoute, ruleIdx, matchIdx),
}
if match.Path != nil {
switch PathMatchTypeDerefOr(match.Path.Type, v1beta1.PathMatchPathPrefix) {
case v1beta1.PathMatchPathPrefix:
irRoute.PathMatch = &ir.StringMatch{
Prefix: match.Path.Value,
}
case v1beta1.PathMatchExact:
irRoute.PathMatch = &ir.StringMatch{
Exact: match.Path.Value,
}
}
}