-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhttpproxy_controller.go
More file actions
1820 lines (1621 loc) · 68.6 KB
/
Copy pathhttpproxy_controller.go
File metadata and controls
1820 lines (1621 loc) · 68.6 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
// SPDX-License-Identifier: AGPL-3.0-only
package controller
import (
"context"
"errors"
"fmt"
"net"
"net/url"
"slices"
"strconv"
"strings"
envoygatewayv1alpha1 "github.com/envoyproxy/gateway/api/v1alpha1"
v1 "k8s.io/api/core/v1"
discoveryv1 "k8s.io/api/discovery/v1"
"k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
apimeta "k8s.io/apimachinery/pkg/api/meta"
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/sets"
"k8s.io/utils/ptr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/cluster"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/log"
gatewayv1 "sigs.k8s.io/gateway-api/apis/v1"
mcbuilder "sigs.k8s.io/multicluster-runtime/pkg/builder"
mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager"
"sigs.k8s.io/multicluster-runtime/pkg/multicluster"
mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile"
mcsource "sigs.k8s.io/multicluster-runtime/pkg/source"
networkingv1alpha "go.datum.net/network-services-operator/api/v1alpha"
networkingv1alpha1 "go.datum.net/network-services-operator/api/v1alpha1"
"go.datum.net/network-services-operator/internal/config"
downstreamclient "go.datum.net/network-services-operator/internal/downstreamclient"
conditionutil "go.datum.net/network-services-operator/internal/util/condition"
gatewayutil "go.datum.net/network-services-operator/internal/util/gateway"
"go.datum.net/network-services-operator/internal/util/resourcename"
dnsv1alpha1 "go.miloapis.com/dns-operator/api/v1alpha1"
)
// HTTPProxyReconciler reconciles a HTTPProxy object
type HTTPProxyReconciler struct {
mgr mcmanager.Manager
Config config.NetworkServicesOperator
DownstreamCluster cluster.Cluster
}
type desiredHTTPProxyResources struct {
gateway *gatewayv1.Gateway
httpRoute *gatewayv1.HTTPRoute
endpointSlices []*discoveryv1.EndpointSlice
httpRouteFilters []*envoygatewayv1alpha1.HTTPRouteFilter
}
const httpProxyFinalizer = "networking.datumapis.com/httpproxy-cleanup"
const connectorOfflineFilterPrefix = "connector-offline"
// BackendCertHostnameAnnotation is set on the upstream EndpointSlice by the
// HTTPProxy controller to record the hostname expected on the backend's TLS
// certificate. The gateway controller reads it when building a
// BackendTLSPolicy so SAN validation continues to target the real backend
// FQDN even when URLRewrite.Hostname has been redirected to a user-supplied
// Host header override.
const BackendCertHostnameAnnotation = "networking.datumapis.com/backend-cert-hostname"
const (
SchemeHTTP = "http"
SchemeHTTPS = "https"
DefaultHTTPPort = 80
DefaultHTTPSPort = 443
)
// +kubebuilder:rbac:groups=networking.datumapis.com,resources=httpproxies,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=networking.datumapis.com,resources=httpproxies/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=networking.datumapis.com,resources=httpproxies/finalizers,verbs=update
// +kubebuilder:rbac:groups=networking.datumapis.com,resources=connectors,verbs=get;list;watch
// +kubebuilder:rbac:groups=gateway.envoyproxy.io,resources=httproutefilters,verbs=get;list;watch;create;update;patch;delete
// HTTPProxy controller reads cert-manager Certificate resources in the downstream cluster for status; ensure downstream role has cert-manager.io/certificates get;list;watch.
func (r *HTTPProxyReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (_ ctrl.Result, err error) {
logger := log.FromContext(ctx, "cluster", req.ClusterName)
ctx = log.IntoContext(ctx, logger)
cl, err := r.mgr.GetCluster(ctx, req.ClusterName)
if err != nil {
return ctrl.Result{}, err
}
var httpProxy networkingv1alpha.HTTPProxy
if err := cl.GetClient().Get(ctx, req.NamespacedName, &httpProxy); err != nil {
if apierrors.IsNotFound(err) {
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
if !httpProxy.DeletionTimestamp.IsZero() {
if controllerutil.ContainsFinalizer(&httpProxy, httpProxyFinalizer) {
if err := r.cleanupConnectorEnvoyPatchPolicy(ctx, cl.GetClient(), string(req.ClusterName), &httpProxy); err != nil {
return ctrl.Result{}, err
}
controllerutil.RemoveFinalizer(&httpProxy, httpProxyFinalizer)
if err := cl.GetClient().Update(ctx, &httpProxy); err != nil {
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
logger.Info("reconciling httpproxy")
defer logger.Info("reconcile complete")
if !controllerutil.ContainsFinalizer(&httpProxy, httpProxyFinalizer) {
controllerutil.AddFinalizer(&httpProxy, httpProxyFinalizer)
if err := cl.GetClient().Update(ctx, &httpProxy); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
httpProxyCopy := httpProxy.DeepCopy()
acceptedCondition := &metav1.Condition{
Type: networkingv1alpha.HTTPProxyConditionAccepted,
Status: metav1.ConditionFalse,
Reason: networkingv1alpha.HTTPProxyReasonPending,
ObservedGeneration: httpProxy.Generation,
Message: "The HTTPProxy has not been scheduled",
}
programmedCondition := &metav1.Condition{
Type: networkingv1alpha.HTTPProxyConditionProgrammed,
Status: metav1.ConditionFalse,
Reason: networkingv1alpha.HTTPProxyReasonPending,
ObservedGeneration: httpProxy.Generation,
Message: "The HTTPProxy has not been programmed",
}
tunnelMetadataCondition := &metav1.Condition{
Type: networkingv1alpha.HTTPProxyConditionConnectorMetadataProgrammed,
Status: metav1.ConditionFalse,
Reason: networkingv1alpha.HTTPProxyReasonPending,
ObservedGeneration: httpProxy.Generation,
Message: "Waiting for envoy to be configured",
}
setTunnelMetadataCondition := false
defer func() {
apimeta.SetStatusCondition(&httpProxyCopy.Status.Conditions, *acceptedCondition)
apimeta.SetStatusCondition(&httpProxyCopy.Status.Conditions, *programmedCondition)
if setTunnelMetadataCondition {
apimeta.SetStatusCondition(&httpProxyCopy.Status.Conditions, *tunnelMetadataCondition)
} else {
apimeta.RemoveStatusCondition(&httpProxyCopy.Status.Conditions, networkingv1alpha.HTTPProxyConditionConnectorMetadataProgrammed)
}
if !equality.Semantic.DeepEqual(httpProxy.Status, httpProxyCopy.Status) {
httpProxy.Status = httpProxyCopy.Status
if statusErr := cl.GetClient().Status().Update(ctx, &httpProxy); statusErr != nil {
err = errors.Join(err, fmt.Errorf("failed updating httpproxy status: %w", statusErr))
}
logger.Info("httpproxy status updated")
}
}()
desiredResources, err := r.collectDesiredResources(ctx, cl.GetClient(), &httpProxy)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to collect desired resources: %w", err)
}
// Maintain a Gateway for the HTTPProxy, handle conflicts in names by updating the
// Programmed condition with info about the conflict.
gateway := desiredResources.gateway.DeepCopy()
result, err := controllerutil.CreateOrUpdate(ctx, cl.GetClient(), gateway, func() error {
if hasControllerConflict(gateway, &httpProxy) {
// return already exists error - a gateway exists with the name we want to
// use, but it's owned by a different resource.
return apierrors.NewAlreadyExists(gatewayv1.Resource(KindGateway), gateway.Name)
}
if err := controllerutil.SetControllerReference(&httpProxy, gateway, cl.GetScheme()); err != nil {
return fmt.Errorf("failed to set controller on gateway: %w", err)
}
// Special handling for default gateway listeners, as the hostnames will be
// updated by the controller. Only required on updates.
if !gateway.CreationTimestamp.IsZero() {
defaultHTTPListener := gatewayutil.GetListenerByName(gateway.Spec.Listeners, gatewayutil.DefaultHTTPListenerName)
if defaultHTTPListener != nil {
gatewayutil.SetListener(desiredResources.gateway, *defaultHTTPListener)
}
defaultHTTPSListener := gatewayutil.GetListenerByName(gateway.Spec.Listeners, gatewayutil.DefaultHTTPSListenerName)
if defaultHTTPSListener != nil {
gatewayutil.SetListener(desiredResources.gateway, *defaultHTTPSListener)
}
}
gateway.Spec = desiredResources.gateway.Spec
return nil
})
if err != nil {
if apierrors.IsAlreadyExists(err) {
programmedCondition.Status = metav1.ConditionFalse
programmedCondition.Reason = networkingv1alpha.HTTPProxyReasonConflict
programmedCondition.Message = fmt.Sprintf("Underlying Gateway with the name %q already exists and is owned by a different resource.", gateway.Name)
return ctrl.Result{}, nil
}
return ctrl.Result{}, fmt.Errorf("failed updating gateway resource: %w", err)
}
logger.Info("processed gateway", jsonKeyName, gateway.Name, "result", result)
// Maintain an HTTPRoute for all rules in the HTTPProxy
if len(desiredResources.httpRouteFilters) == 0 {
if err := cleanupConnectorOfflineHTTPRouteFilter(ctx, cl.GetClient(), &httpProxy); err != nil {
return ctrl.Result{}, err
}
} else {
for _, desiredFilter := range desiredResources.httpRouteFilters {
httpRouteFilter := desiredFilter.DeepCopy()
result, err := controllerutil.CreateOrUpdate(ctx, cl.GetClient(), httpRouteFilter, func() error {
if err := controllerutil.SetControllerReference(&httpProxy, httpRouteFilter, cl.GetScheme()); err != nil {
return fmt.Errorf("failed to set controller on HTTPRouteFilter: %w", err)
}
httpRouteFilter.Spec = desiredFilter.Spec
return nil
})
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed updating httproutefilter resource: %w", err)
}
logger.Info("processed httproutefilter", jsonKeyName, httpRouteFilter.Name, "result", result)
}
}
httpRoute := desiredResources.httpRoute.DeepCopy()
result, err = controllerutil.CreateOrUpdate(ctx, cl.GetClient(), httpRoute, func() error {
if hasControllerConflict(httpRoute, &httpProxy) {
// return already exists error - an httproute exists with the name we want to
// use, but it's owned by a different resource.
return apierrors.NewAlreadyExists(gatewayv1.Resource("HTTPRoute"), httpRoute.Name)
}
if err := controllerutil.SetControllerReference(&httpProxy, httpRoute, cl.GetScheme()); err != nil {
return fmt.Errorf("failed to set controller on httproute: %w", err)
}
httpRoute.Spec = desiredResources.httpRoute.Spec
return nil
})
if err != nil {
if apierrors.IsAlreadyExists(err) {
programmedCondition.Status = metav1.ConditionFalse
programmedCondition.Reason = networkingv1alpha.HTTPProxyReasonConflict
programmedCondition.Message = fmt.Sprintf("Underlying HTTPRoute with the name %q already exists and is owned by a different resource.", httpRoute.Name)
return ctrl.Result{}, nil
}
return ctrl.Result{}, fmt.Errorf("failed updating httproute resource: %w", err)
}
logger.Info("processed httproute", jsonKeyName, httpRoute.Name, "result", result)
for _, desiredEndpointSlice := range desiredResources.endpointSlices {
endpointSlice := desiredEndpointSlice.DeepCopy()
result, err := controllerutil.CreateOrUpdate(ctx, cl.GetClient(), endpointSlice, func() error {
if hasControllerConflict(endpointSlice, &httpProxy) {
// return already exists error - an endpointslice exists with the name we want to
// use, but it's owned by a different resource.
return apierrors.NewAlreadyExists(discoveryv1.Resource("EndpointSlice"), endpointSlice.Name)
}
if err := controllerutil.SetControllerReference(&httpProxy, endpointSlice, cl.GetScheme()); err != nil {
return fmt.Errorf("failed to set controller reference on endpointslice: %w", err)
}
endpointSlice.AddressType = desiredEndpointSlice.AddressType
endpointSlice.Endpoints = desiredEndpointSlice.Endpoints
endpointSlice.Ports = desiredEndpointSlice.Ports
// Keep the backend cert hostname annotation in sync. The gateway
// controller reads this to build the BackendTLSPolicy when the
// URLRewrite filter carries a user Host override instead of the
// real backend FQDN.
if v, ok := desiredEndpointSlice.Annotations[BackendCertHostnameAnnotation]; ok {
if endpointSlice.Annotations == nil {
endpointSlice.Annotations = map[string]string{}
}
endpointSlice.Annotations[BackendCertHostnameAnnotation] = v
} else {
delete(endpointSlice.Annotations, BackendCertHostnameAnnotation)
}
return nil
})
if err != nil {
if apierrors.IsAlreadyExists(err) {
programmedCondition.Status = metav1.ConditionFalse
programmedCondition.Reason = networkingv1alpha.HTTPProxyReasonConflict
programmedCondition.Message = fmt.Sprintf("Underlying EndpointSlice with the name %q already exists and is owned by a different resource.", endpointSlice.Name)
return ctrl.Result{}, nil
}
return ctrl.Result{}, fmt.Errorf("failed to create or update endpointslice: %w", err)
}
logger.Info("processed endpointslice", "result", result, jsonKeyName, desiredEndpointSlice.Name)
}
// Gate connector EPP emission behind the feature flag. When disabled the
// extension server handles connector xDS mutation via PostTranslateModify;
// NSO emits ZERO connector EPPs and does NOT delete existing ones.
// patchPolicy=nil and hasConnectorBackends=false causes the
// ConnectorMetadataProgrammed condition to be cleared (not tracked by NSO
// when the extension server owns this path).
var patchPolicy *envoygatewayv1alpha1.EnvoyPatchPolicy
var hasConnectorBackends bool
if r.Config.Gateway.IsEPPEmissionEnabled() {
patchPolicy, hasConnectorBackends, err = r.reconcileConnectorEnvoyPatchPolicy(
ctx,
cl.GetClient(),
string(req.ClusterName),
&httpProxy,
gateway,
)
if err != nil {
programmedCondition.Status = metav1.ConditionFalse
programmedCondition.Reason = networkingv1alpha.HTTPProxyReasonPending
programmedCondition.Message = err.Error()
return ctrl.Result{}, err
}
}
httpProxyCopy.Status.Addresses = gateway.Status.Addresses
if c := apimeta.FindStatusCondition(gateway.Status.Conditions, string(gatewayv1.GatewayConditionAccepted)); c != nil {
logger.Info("gateway accepted status", "status", c.Status)
if c.Status == metav1.ConditionTrue {
acceptedCondition.Status = metav1.ConditionTrue
acceptedCondition.Reason = networkingv1alpha.HTTPProxyReasonAccepted
acceptedCondition.Message = "The HTTPProxy has been scheduled"
} else {
acceptedCondition.Reason = c.Reason
}
}
if c := apimeta.FindStatusCondition(gateway.Status.Conditions, string(gatewayv1.GatewayConditionProgrammed)); c != nil {
if c.Status == metav1.ConditionTrue {
programmedCondition.Status = metav1.ConditionTrue
programmedCondition.Reason = networkingv1alpha.HTTPProxyReasonProgrammed
programmedCondition.Message = "The HTTPProxy has been programmed"
} else {
programmedCondition.Reason = c.Reason
}
}
if hasConnectorBackends {
connectorPolicyReady, connectorPolicyMessage := downstreamPatchPolicyReady(
patchPolicy,
r.Config.Gateway.DownstreamGatewayClassName,
)
if !connectorPolicyReady {
programmedCondition.Status = metav1.ConditionFalse
programmedCondition.Reason = networkingv1alpha.HTTPProxyReasonPending
if connectorPolicyMessage == "" {
connectorPolicyMessage = "Waiting for downstream EnvoyPatchPolicy to be accepted and programmed"
}
programmedCondition.Message = connectorPolicyMessage
tunnelMetadataCondition.Status = metav1.ConditionFalse
tunnelMetadataCondition.Reason = networkingv1alpha.HTTPProxyReasonPending
tunnelMetadataCondition.Message = connectorPolicyMessage
} else {
tunnelMetadataCondition.Status = metav1.ConditionTrue
tunnelMetadataCondition.Reason = networkingv1alpha.HTTPProxyReasonConnectorMetadataApplied
tunnelMetadataCondition.Message = "Connector tunnel metadata applied"
}
setTunnelMetadataCondition = true
} else {
apimeta.RemoveStatusCondition(&httpProxyCopy.Status.Conditions, networkingv1alpha.HTTPProxyConditionConnectorMetadataProgrammed)
}
r.reconcileHTTPProxyHostnameStatus(ctx, cl.GetClient(), gateway, httpProxyCopy, string(req.ClusterName))
return ctrl.Result{}, nil
}
func (r *HTTPProxyReconciler) reconcileHTTPProxyHostnameStatus(
ctx context.Context,
cl client.Client,
gateway *gatewayv1.Gateway,
httpProxyCopy *networkingv1alpha.HTTPProxy,
clusterName string,
) {
logger := log.FromContext(ctx)
gatewayAcceptedCondition := apimeta.FindStatusCondition(gateway.Status.Conditions, string(gatewayv1.GatewayConditionAccepted))
if gatewayAcceptedCondition == nil {
// Should never happen due to defaulting, but just in case
logger.Info("accepted condition not found on gateway")
return
} else if gatewayAcceptedCondition.ObservedGeneration != gateway.Generation {
logger.Info(
"observed generation on accepted condition does not match generation on gateway, delaying processing",
"gateway_generation", gateway.Generation,
"condition_generation", gatewayAcceptedCondition.ObservedGeneration,
)
return
}
logger.Info("updating hostname status")
// CanonicalHostname is the platform-managed hostname we create for the HTTPProxy.
httpProxyCopy.Status.CanonicalHostname = gatewayCanonicalHostnameForConfig(r.Config.Gateway, gateway)
currentListenerStatus := map[gatewayv1.SectionName]gatewayv1.ListenerStatus{}
for _, listener := range gateway.Status.Listeners {
currentListenerStatus[listener.Name] = *listener.DeepCopy()
}
acceptedHostnames := sets.New[gatewayv1.Hostname]()
nonAcceptedHostnames := sets.New[string]()
inUseHostnames := sets.New[string]()
for _, listener := range gateway.Spec.Listeners {
if listener.Hostname == nil {
// Should only happen shortly after creation, before the default hostnames
// are assigned
continue
}
listenerStatus, ok := currentListenerStatus[listener.Name]
if !ok {
logger.Info("listener status not found", "listener_name", listener.Name)
continue
}
listenerAcceptedCondition := apimeta.FindStatusCondition(listenerStatus.Conditions, string(gatewayv1.ListenerConditionAccepted))
if listenerAcceptedCondition != nil {
if listenerAcceptedCondition.Status == metav1.ConditionTrue {
acceptedHostnames.Insert(*listener.Hostname)
} else if listenerAcceptedCondition.Reason == networkingv1alpha.HostnameInUseReason {
inUseHostnames.Insert(string(*listener.Hostname))
} else {
nonAcceptedHostnames.Insert(string(*listener.Hostname))
}
} else {
nonAcceptedHostnames.Insert(string(*listener.Hostname))
}
}
acceptedHostnamesSlice := acceptedHostnames.UnsortedList()
slices.Sort(acceptedHostnamesSlice)
hostnames := make([]gatewayv1.Hostname, 0, len(acceptedHostnamesSlice))
//nolint:staticcheck // SA1019: Hostnames is deprecated but still populated for backwards compatibility
httpProxyCopy.Status.Hostnames = append(hostnames, acceptedHostnamesSlice...)
if len(httpProxyCopy.Spec.Hostnames) > 0 {
hostnamesVerifiedCondition := conditionutil.FindStatusConditionOrDefault(httpProxyCopy.Status.Conditions, &metav1.Condition{
Type: networkingv1alpha.HTTPProxyConditionHostnamesVerified,
Status: metav1.ConditionFalse,
})
hostnamesVerifiedCondition.ObservedGeneration = httpProxyCopy.Generation
if nonAcceptedHostnames.Len() > 0 {
nonAcceptedHostnamesSlice := nonAcceptedHostnames.UnsortedList()
slices.Sort(nonAcceptedHostnamesSlice)
hostnamesVerifiedCondition.Status = metav1.ConditionFalse
hostnamesVerifiedCondition.Reason = networkingv1alpha.UnverifiedHostnamesPresent
hostnamesVerifiedCondition.Message = fmt.Sprintf("unverified hostnames present, check status of Domains in the same namespace: %s", strings.Join(nonAcceptedHostnamesSlice, ","))
} else if acceptedHostnames.Len() == len(httpProxyCopy.Spec.Hostnames) || acceptedHostnames.Len() == len(httpProxyCopy.Spec.Hostnames)+1 {
// acceptedHostnames may contain the default listener hostname if it has
// not been removed by the user.
hostnamesVerifiedCondition.Status = metav1.ConditionTrue
hostnamesVerifiedCondition.Reason = networkingv1alpha.HTTPProxyReasonHostnamesVerified
hostnamesVerifiedCondition.Message = "All hostnames have been accepted and programmed"
} else {
hostnamesVerifiedCondition.Status = metav1.ConditionFalse
hostnamesVerifiedCondition.Reason = networkingv1alpha.HTTPProxyReasonPending
hostnamesVerifiedCondition.Message = "Pending downstream Gateway status updates"
}
apimeta.SetStatusCondition(&httpProxyCopy.Status.Conditions, *hostnamesVerifiedCondition)
if inUseHostnames.Len() > 0 {
inUseHostnamesSlice := inUseHostnames.UnsortedList()
slices.Sort(inUseHostnamesSlice)
apimeta.SetStatusCondition(&httpProxyCopy.Status.Conditions, metav1.Condition{
Type: networkingv1alpha.HTTPProxyConditionHostnamesInUse,
Status: metav1.ConditionTrue,
ObservedGeneration: httpProxyCopy.Generation,
Reason: networkingv1alpha.HostnameInUseReason,
Message: fmt.Sprintf("Hostnames are already attached to another resource: %s", strings.Join(inUseHostnamesSlice, ",")),
})
} else {
apimeta.RemoveStatusCondition(&httpProxyCopy.Status.Conditions, networkingv1alpha.HTTPProxyConditionHostnamesInUse)
}
} else {
apimeta.RemoveStatusCondition(&httpProxyCopy.Status.Conditions, networkingv1alpha.HTTPProxyConditionHostnamesVerified)
apimeta.RemoveStatusCondition(&httpProxyCopy.Status.Conditions, networkingv1alpha.HTTPProxyConditionHostnamesInUse)
}
// Build per-hostname statuses
availabilityStatuses := buildAvailabilityStatuses(acceptedHostnames, inUseHostnames, httpProxyCopy.Generation)
dnsStatuses := r.buildDNSStatuses(ctx, cl, gateway, httpProxyCopy.Generation)
certificateStatuses := r.buildCertificateStatuses(ctx, cl, clusterName, gateway, httpProxyCopy)
previousHostnameStatuses := httpProxyCopy.Status.HostnameStatuses
httpProxyCopy.Status.HostnameStatuses = mergeHostnameStatuses(availabilityStatuses, dnsStatuses, certificateStatuses)
preserveHostnameConditionTransitions(httpProxyCopy.Status.HostnameStatuses, previousHostnameStatuses)
r.setCertificatesReadyCondition(httpProxyCopy, certificateStatuses, gateway)
}
// SetupWithManager sets up the controller with the Manager.
func (r *HTTPProxyReconciler) SetupWithManager(mgr mcmanager.Manager) error {
r.mgr = mgr
builder := mcbuilder.ControllerManagedBy(mgr).
For(&networkingv1alpha.HTTPProxy{}).
Owns(&gatewayv1.Gateway{}).
Owns(&gatewayv1.HTTPRoute{}).
Owns(&discoveryv1.EndpointSlice{}).
// Watch Connectors and reconcile HTTPProxies that reference them.
// This ensures EnvoyPatchPolicy headers are updated when a Connector's
// publicKey.id changes (e.g., after connector restart/reconnect).
Watches(
&networkingv1alpha1.Connector{},
func(clusterName multicluster.ClusterName, cl cluster.Cluster) handler.TypedEventHandler[client.Object, mcreconcile.Request] {
return handler.TypedEnqueueRequestsFromMapFunc(func(ctx context.Context, obj client.Object) []mcreconcile.Request {
logger := log.FromContext(ctx)
connector, ok := obj.(*networkingv1alpha1.Connector)
if !ok {
return nil
}
// List all HTTPProxies in the same namespace
var httpProxies networkingv1alpha.HTTPProxyList
if err := cl.GetClient().List(ctx, &httpProxies, client.InNamespace(connector.Namespace)); err != nil {
logger.Error(err, "failed to list HTTPProxies for Connector watch", "connector", connector.Name)
return nil
}
var requests []mcreconcile.Request
for i := range httpProxies.Items {
httpProxy := &httpProxies.Items[i]
// Check if this HTTPProxy references the changed Connector
if httpProxyReferencesConnector(httpProxy, connector.Name) {
requests = append(requests, mcreconcile.Request{
ClusterName: clusterName,
Request: ctrl.Request{
NamespacedName: client.ObjectKeyFromObject(httpProxy),
},
})
}
}
if len(requests) > 0 {
logger.Info("Connector changed, requeueing HTTPProxies",
"connector", connector.Name,
"httpProxyCount", len(requests))
}
return requests
})
},
)
if r.DownstreamCluster != nil {
downstreamPolicySource := mcsource.TypedKind(
&envoygatewayv1alpha1.EnvoyPatchPolicy{},
downstreamclient.TypedEnqueueRequestForUpstreamOwner[*envoygatewayv1alpha1.EnvoyPatchPolicy](&networkingv1alpha.HTTPProxy{}),
)
downstreamPolicyClusterSource, _, _ := downstreamPolicySource.ForCluster("", r.DownstreamCluster)
builder = builder.WatchesRawSource(downstreamPolicyClusterSource)
// Watch downstream cert-manager Certificates so HTTPProxy certificate status
// is updated when certificates become ready or fail.
downstreamCertificateSource := mcsource.TypedKind(
newUnstructuredForGVK(certificateGVK),
r.enqueueHTTPProxyForDownstreamCertificate(),
)
downstreamCertificateClusterSource, _, _ := downstreamCertificateSource.ForCluster("", r.DownstreamCluster)
builder = builder.WatchesRawSource(downstreamCertificateClusterSource)
}
return builder.Named("httpproxy").Complete(r)
}
// enqueueHTTPProxyForDownstreamCertificate returns a watch handler that enqueues
// the HTTPProxy (same name/namespace as the owning Gateway) when a downstream
// cert-manager Certificate changes, so certificate status is updated.
func (r *HTTPProxyReconciler) enqueueHTTPProxyForDownstreamCertificate() func(clusterName multicluster.ClusterName, cl cluster.Cluster) handler.TypedEventHandler[*unstructured.Unstructured, mcreconcile.Request] {
return func(_ multicluster.ClusterName, cl cluster.Cluster) handler.TypedEventHandler[*unstructured.Unstructured, mcreconcile.Request] {
return handler.TypedEnqueueRequestsFromMapFunc(func(ctx context.Context, cert *unstructured.Unstructured) []mcreconcile.Request {
logger := log.FromContext(ctx)
ownerRef := metav1.GetControllerOf(cert)
if ownerRef == nil {
return nil
}
if ownerRef.Kind != KindGateway {
return nil
}
gatewayKey := client.ObjectKey{Namespace: cert.GetNamespace(), Name: ownerRef.Name}
var gateway gatewayv1.Gateway
if err := cl.GetClient().Get(ctx, gatewayKey, &gateway); err != nil {
if apierrors.IsNotFound(err) {
return nil
}
logger.Error(err, "failed to get Gateway owner of Certificate", "certificate", cert.GetName(), "gateway", gatewayKey)
return nil
}
labels := gateway.GetLabels()
upstreamNs := labels[downstreamclient.UpstreamOwnerNamespaceLabel]
upstreamName := labels[downstreamclient.UpstreamOwnerNameLabel]
upstreamCluster := labels[downstreamclient.UpstreamOwnerClusterNameLabel]
if upstreamNs == "" || upstreamName == "" || upstreamCluster == "" {
return nil
}
clusterName := multicluster.ClusterName(downstreamclient.UpstreamClusterNameFromLabel(upstreamCluster))
return []mcreconcile.Request{{
ClusterName: clusterName,
Request: ctrl.Request{NamespacedName: types.NamespacedName{Namespace: upstreamNs, Name: upstreamName}},
}}
})
}
}
// httpProxyReferencesConnector checks if an HTTPProxy has any backends
// that reference the given Connector name.
func httpProxyReferencesConnector(httpProxy *networkingv1alpha.HTTPProxy, connectorName string) bool {
for _, rule := range httpProxy.Spec.Rules {
for _, backend := range rule.Backends {
if backend.Connector != nil && backend.Connector.Name == connectorName {
return true
}
}
}
return false
}
// extractHostHeaderOverride returns the Host header value from a
// RequestHeaderModifier filter, if present. Header names are matched
// case-insensitively per RFC 7230. The returned bool indicates whether a
// Host header override was found.
//
// Envoy Gateway does not accept Host header manipulation via
// RequestHeaderModifier — it must go through URLRewrite.Hostname instead.
// collectDesiredResources uses this helper to translate the user-facing
// RequestHeaderModifier{Host} shape (which round-trips with datumctl and
// the cloud portal) into the URLRewrite{Hostname} that Envoy actually
// honours at egress.
func extractHostHeaderOverride(filters []gatewayv1.HTTPRouteFilter) (string, bool) {
for _, filter := range filters {
if filter.Type != gatewayv1.HTTPRouteFilterRequestHeaderModifier || filter.RequestHeaderModifier == nil {
continue
}
for _, h := range filter.RequestHeaderModifier.Set {
if strings.EqualFold(string(h.Name), "Host") {
return h.Value, true
}
}
}
return "", false
}
// stripHostFromRequestHeaderModifier returns the filter list with any
// Host entry removed from each RequestHeaderModifier's Set list. If a
// RequestHeaderModifier ends up empty (no add/set/remove), the filter
// itself is dropped. This keeps Envoy Gateway from rejecting the route
// because of an "empty" RequestHeaderModifier after we've moved the
// Host override into URLRewrite.
func stripHostFromRequestHeaderModifier(filters []gatewayv1.HTTPRouteFilter) []gatewayv1.HTTPRouteFilter {
out := make([]gatewayv1.HTTPRouteFilter, 0, len(filters))
for _, filter := range filters {
if filter.Type != gatewayv1.HTTPRouteFilterRequestHeaderModifier || filter.RequestHeaderModifier == nil {
out = append(out, filter)
continue
}
modifier := filter.RequestHeaderModifier
filtered := make([]gatewayv1.HTTPHeader, 0, len(modifier.Set))
for _, h := range modifier.Set {
if strings.EqualFold(string(h.Name), "Host") {
continue
}
filtered = append(filtered, h)
}
if len(filtered) == 0 && len(modifier.Add) == 0 && len(modifier.Remove) == 0 {
// Drop the now-empty RequestHeaderModifier filter entirely.
continue
}
newFilter := filter
newModifier := *modifier
newModifier.Set = filtered
newFilter.RequestHeaderModifier = &newModifier
out = append(out, newFilter)
}
return out
}
func (r *HTTPProxyReconciler) collectDesiredResources(
ctx context.Context,
cl client.Client,
httpProxy *networkingv1alpha.HTTPProxy,
) (*desiredHTTPProxyResources, error) {
gateway := &gatewayv1.Gateway{
ObjectMeta: metav1.ObjectMeta{
Namespace: httpProxy.Namespace,
Name: httpProxy.Name,
},
Spec: gatewayv1.GatewaySpec{
GatewayClassName: r.Config.HTTPProxy.GatewayClassName,
},
}
// Hostname fields will be nil on the default listeners until the gateway
// controller updates them. There's special handling for this in the
// CreateOrUpdate logic for maintaining the gateway.
gatewayutil.SetDefaultListeners(gateway, r.Config.Gateway)
// Add listeners for each hostname
for i, hostname := range httpProxy.Spec.Hostnames {
gateway.Spec.Listeners = append(gateway.Spec.Listeners, gatewayv1.Listener{
Name: gatewayv1.SectionName(fmt.Sprintf("%s-hostname-%d", SchemeHTTP, i)),
Protocol: gatewayv1.HTTPProtocolType,
Port: DefaultHTTPPort,
Hostname: ptr.To(hostname),
AllowedRoutes: &gatewayv1.AllowedRoutes{
Namespaces: &gatewayv1.RouteNamespaces{
From: ptr.To(gatewayv1.NamespacesFromSame),
},
},
})
gateway.Spec.Listeners = append(gateway.Spec.Listeners, gatewayv1.Listener{
Name: gatewayv1.SectionName(fmt.Sprintf("%s-hostname-%d", SchemeHTTPS, i)),
Protocol: gatewayv1.HTTPSProtocolType,
Port: DefaultHTTPSPort,
Hostname: ptr.To(hostname),
AllowedRoutes: &gatewayv1.AllowedRoutes{
Namespaces: &gatewayv1.RouteNamespaces{
From: ptr.To(gatewayv1.NamespacesFromSame),
},
},
TLS: &gatewayv1.ListenerTLSConfig{
Mode: ptr.To(gatewayv1.TLSModeTerminate),
Options: r.Config.Gateway.ListenerTLSOptions,
},
})
}
httpRoute := &gatewayv1.HTTPRoute{
ObjectMeta: metav1.ObjectMeta{
Namespace: httpProxy.Namespace,
Name: httpProxy.Name,
},
Spec: gatewayv1.HTTPRouteSpec{
CommonRouteSpec: gatewayv1.CommonRouteSpec{
ParentRefs: []gatewayv1.ParentReference{
{
Name: gatewayv1.ObjectName(gateway.Name),
},
},
},
},
}
var desiredEndpointSlices []*discoveryv1.EndpointSlice
var desiredRouteFilters []*envoygatewayv1alpha1.HTTPRouteFilter
desiredRouteRules := make([]gatewayv1.HTTPRouteRule, len(httpProxy.Spec.Rules))
for ruleIndex, rule := range httpProxy.Spec.Rules {
ruleFilters := slices.Clone(rule.Filters)
backendRefs := make([]gatewayv1.HTTPBackendRef, len(rule.Backends))
offlineRuleSet := false
// Validation will prevent this from occurring, unless the maximum items for
// backends is adjusted. The following error has been placed here so that
// if/when that occurs, we're sure to address obvious programming changes
// required (which should happen anyways, but just to be safe...).
if len(rule.Backends) > 1 {
return nil, fmt.Errorf("invalid number of backends for rule - expected 1 got %d", len(rule.Backends))
}
for backendIndex, backend := range rule.Backends {
if backend.Connector != nil {
ready, err := connectorReady(ctx, cl, httpProxy.Namespace, backend.Connector.Name)
if err != nil {
return nil, err
}
if !ready {
// Connector is offline: keep the route rule with no backends so EG
// can translate it (creating virtual_hosts). The connector EPP
// (buildConnectorOfflineEnvoyPatches) inserts a direct_response CONNECT
// route at the front, which is the canonical offline-503 mechanism.
// Do NOT add an ExtensionRef→HTTPRouteFilter.DirectResponse here:
// EG v1.7.3 cannot translate that filter shape and the HTTPRoute
// status would show UnsupportedValue, preventing EPP programming.
desiredRouteRules[ruleIndex] = gatewayv1.HTTPRouteRule{
Name: rule.Name,
Matches: rule.Matches,
Filters: ruleFilters,
BackendRefs: nil,
}
offlineRuleSet = true
break
}
}
appProtocol := SchemeHTTP
backendPort := DefaultHTTPPort
u, err := url.Parse(backend.Endpoint)
if err != nil {
return nil, fmt.Errorf("failed parsing endpoint for backend %d in rule %d: %w", backendIndex, ruleIndex, err)
}
if u.Scheme == SchemeHTTPS {
backendPort = DefaultHTTPSPort
appProtocol = SchemeHTTPS
}
if endpointPort := u.Port(); endpointPort != "" {
backendPort, err = strconv.Atoi(endpointPort)
if err != nil {
return nil, fmt.Errorf("failed parsing endpoint port for backend %d in rule %d: %w", backendIndex, ruleIndex, err)
}
}
// TODO(jreese) Move away from FQDN and EndpointSlices
//
// The FQDN AddressType has been deprecated, but as we control the
// programming of an HTTPProxy, we can easily transition to an alternative
// once we have one. This is in an effort to not block MVP goals.
addressType := discoveryv1.AddressTypeFQDN
host := u.Hostname()
endpointHost := host
isIPAddress := false
if backend.Connector != nil {
// Connector backends don't rely on EndpointSlice addresses; use a safe placeholder.
endpointHost = "connector.local"
addressType = discoveryv1.AddressTypeFQDN
} else if ip := net.ParseIP(host); ip != nil {
isIPAddress = true
if i := ip.To4(); i != nil && len(i) == net.IPv4len {
addressType = discoveryv1.AddressTypeIPv4
} else {
addressType = discoveryv1.AddressTypeIPv6
}
}
// Resolve the user's Host header override, if any. Envoy Gateway
// rejects RequestHeaderModifier filters that touch Host; the Host
// rewrite must be expressed as URLRewrite.Hostname instead. We
// translate the user-facing RequestHeaderModifier{Host} shape
// (which is what datumctl and the cloud portal write) into the
// URLRewrite.Hostname value Envoy will honour at egress, then
// strip the now-redundant Host entry from the RequestHeaderModifier
// so EG doesn't see the conflicting combination.
userHostOverride, hasUserHost := extractHostHeaderOverride(ruleFilters)
if !hasUserHost {
userHostOverride, hasUserHost = extractHostHeaderOverride(backend.Filters)
}
if hasUserHost {
ruleFilters = stripHostFromRequestHeaderModifier(ruleFilters)
backend.Filters = stripHostFromRequestHeaderModifier(backend.Filters)
}
// Track the backend cert hostname separately from the Host
// rewrite value. The two can diverge when the user sets a Host
// override — URLRewrite.Hostname carries the user's value to
// Envoy, while certHostname (propagated via an EndpointSlice
// annotation and read by the gateway controller) is used for
// BackendTLSPolicy SAN validation against the real backend.
var certHostname string
// For HTTPS endpoints with IP addresses, require tls.hostname for certificate validation
// and use it as the Host header for the upstream request.
if u.Scheme == SchemeHTTPS && isIPAddress {
if backend.TLS == nil || backend.TLS.Hostname == nil || *backend.TLS.Hostname == "" {
return nil, fmt.Errorf("HTTPS endpoint with IP address requires tls.hostname for backend %d in rule %d", backendIndex, ruleIndex)
}
certHostname = *backend.TLS.Hostname
rewriteHostname := certHostname
if hasUserHost {
rewriteHostname = userHostOverride
}
// Use tls.hostname (or the user override) for the Host header rewrite
hostnameRewriteFound := false
for i, filter := range ruleFilters {
if filter.Type == gatewayv1.HTTPRouteFilterURLRewrite {
ruleFilters[i].URLRewrite.Hostname = ptr.To(gatewayv1.PreciseHostname(rewriteHostname))
hostnameRewriteFound = true
break
}
}
if !hostnameRewriteFound {
ruleFilters = append(ruleFilters, gatewayv1.HTTPRouteFilter{
Type: gatewayv1.HTTPRouteFilterURLRewrite,
URLRewrite: &gatewayv1.HTTPURLRewriteFilter{
Hostname: ptr.To(gatewayv1.PreciseHostname(rewriteHostname)),
},
})
}
} else if !isIPAddress && backend.Connector == nil {
// For FQDN endpoints, rewrite the Host header to match the
// backend hostname — or to the user's override if they set
// one via RequestHeaderModifier.
certHostname = host
rewriteHostname := host
if hasUserHost {
rewriteHostname = userHostOverride
}
hostnameRewriteFound := false
for i, filter := range ruleFilters {
if filter.Type == gatewayv1.HTTPRouteFilterURLRewrite {
ruleFilters[i].URLRewrite.Hostname = ptr.To(gatewayv1.PreciseHostname(rewriteHostname))
hostnameRewriteFound = true
break
}
}
if !hostnameRewriteFound {
ruleFilters = append(ruleFilters, gatewayv1.HTTPRouteFilter{
Type: gatewayv1.HTTPRouteFilterURLRewrite,
URLRewrite: &gatewayv1.HTTPURLRewriteFilter{
Hostname: ptr.To(gatewayv1.PreciseHostname(rewriteHostname)),
},
})
}
}
epAnnotations := map[string]string{}
if certHostname != "" {
// Surface the backend cert hostname so the gateway controller
// can build the BackendTLSPolicy without relying on the
// URLRewrite filter (which may now carry a user-supplied Host
// override instead of the real backend FQDN).
epAnnotations[BackendCertHostnameAnnotation] = certHostname
}
endpointSlice := &discoveryv1.EndpointSlice{
ObjectMeta: metav1.ObjectMeta{
Namespace: httpProxy.Namespace,
Name: fmt.Sprintf("%s-%d-%d", httpProxy.Name, ruleIndex, backendIndex),
Annotations: epAnnotations,
},
AddressType: addressType,
Endpoints: []discoveryv1.Endpoint{
{
Addresses: []string{
endpointHost,
},
Conditions: discoveryv1.EndpointConditions{
Ready: ptr.To(true),
Serving: ptr.To(true),
Terminating: ptr.To(false),
},
},
},
Ports: []discoveryv1.EndpointPort{
{
Name: ptr.To(fmt.Sprintf("httpproxy-%d-%d", ruleIndex, backendIndex)),
Protocol: ptr.To(v1.ProtocolTCP),
AppProtocol: ptr.To(appProtocol),
Port: ptr.To(int32(backendPort)),
},
},
}
desiredEndpointSlices = append(desiredEndpointSlices, endpointSlice)
backendRefs[backendIndex] = gatewayv1.HTTPBackendRef{
BackendRef: gatewayv1.BackendRef{
BackendObjectReference: gatewayv1.BackendObjectReference{
Group: ptr.To(gatewayv1.Group("discovery.k8s.io")),
Kind: ptr.To(gatewayv1.Kind("EndpointSlice")),
Name: gatewayv1.ObjectName(endpointSlice.Name),
Port: ptr.To(gatewayv1.PortNumber(backendPort)),
},
},
Filters: backend.Filters,
}
}