/
kubernetes.go
1739 lines (1427 loc) · 58.5 KB
/
kubernetes.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 gateway
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"net"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/hashicorp/go-multierror"
"github.com/mitchellh/hashstructure"
ptypes "github.com/traefik/paerser/types"
"github.com/traefik/traefik/v2/pkg/config/dynamic"
"github.com/traefik/traefik/v2/pkg/job"
"github.com/traefik/traefik/v2/pkg/log"
"github.com/traefik/traefik/v2/pkg/provider"
containousv1alpha1 "github.com/traefik/traefik/v2/pkg/provider/kubernetes/crd/traefikcontainous/v1alpha1"
traefikv1alpha1 "github.com/traefik/traefik/v2/pkg/provider/kubernetes/crd/traefikio/v1alpha1"
"github.com/traefik/traefik/v2/pkg/provider/kubernetes/k8s"
"github.com/traefik/traefik/v2/pkg/safe"
"github.com/traefik/traefik/v2/pkg/tls"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/utils/pointer"
"k8s.io/utils/strings/slices"
gatev1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
)
const (
providerName = "kubernetesgateway"
kindGateway = "Gateway"
kindTraefikService = "TraefikService"
kindHTTPRoute = "HTTPRoute"
kindTCPRoute = "TCPRoute"
kindTLSRoute = "TLSRoute"
)
// Provider holds configurations of the provider.
type Provider struct {
Endpoint string `description:"Kubernetes server endpoint (required for external cluster client)." json:"endpoint,omitempty" toml:"endpoint,omitempty" yaml:"endpoint,omitempty"`
Token string `description:"Kubernetes bearer token (not needed for in-cluster client)." json:"token,omitempty" toml:"token,omitempty" yaml:"token,omitempty" loggable:"false"`
CertAuthFilePath string `description:"Kubernetes certificate authority file path (not needed for in-cluster client)." json:"certAuthFilePath,omitempty" toml:"certAuthFilePath,omitempty" yaml:"certAuthFilePath,omitempty"`
Namespaces []string `description:"Kubernetes namespaces." json:"namespaces,omitempty" toml:"namespaces,omitempty" yaml:"namespaces,omitempty" export:"true"`
LabelSelector string `description:"Kubernetes label selector to select specific GatewayClasses." json:"labelSelector,omitempty" toml:"labelSelector,omitempty" yaml:"labelSelector,omitempty" export:"true"`
ThrottleDuration ptypes.Duration `description:"Kubernetes refresh throttle duration" json:"throttleDuration,omitempty" toml:"throttleDuration,omitempty" yaml:"throttleDuration,omitempty" export:"true"`
EntryPoints map[string]Entrypoint `json:"-" toml:"-" yaml:"-" label:"-" file:"-"`
lastConfiguration safe.Safe
routerTransform k8s.RouterTransform
}
func (p *Provider) SetRouterTransform(routerTransform k8s.RouterTransform) {
p.routerTransform = routerTransform
}
func (p *Provider) applyRouterTransform(ctx context.Context, rt *dynamic.Router, route *gatev1alpha2.HTTPRoute) {
if p.routerTransform == nil {
return
}
err := p.routerTransform.Apply(ctx, rt, route.Annotations)
if err != nil {
log.FromContext(ctx).WithError(err).Error("Apply router transform")
}
}
// Entrypoint defines the available entry points.
type Entrypoint struct {
Address string
HasHTTPTLSConf bool
}
func (p *Provider) newK8sClient(ctx context.Context) (*clientWrapper, error) {
// Label selector validation
_, err := labels.Parse(p.LabelSelector)
if err != nil {
return nil, fmt.Errorf("invalid label selector: %q", p.LabelSelector)
}
logger := log.FromContext(ctx)
logger.Infof("label selector is: %q", p.LabelSelector)
withEndpoint := ""
if p.Endpoint != "" {
withEndpoint = fmt.Sprintf(" with endpoint %s", p.Endpoint)
}
var client *clientWrapper
switch {
case os.Getenv("KUBERNETES_SERVICE_HOST") != "" && os.Getenv("KUBERNETES_SERVICE_PORT") != "":
logger.Infof("Creating in-cluster Provider client%s", withEndpoint)
client, err = newInClusterClient(p.Endpoint)
case os.Getenv("KUBECONFIG") != "":
logger.Infof("Creating cluster-external Provider client from KUBECONFIG %s", os.Getenv("KUBECONFIG"))
client, err = newExternalClusterClientFromFile(os.Getenv("KUBECONFIG"))
default:
logger.Infof("Creating cluster-external Provider client%s", withEndpoint)
client, err = newExternalClusterClient(p.Endpoint, p.Token, p.CertAuthFilePath)
}
if err != nil {
return nil, err
}
client.labelSelector = p.LabelSelector
return client, nil
}
// Init the provider.
func (p *Provider) Init() error {
return nil
}
// Provide allows the k8s provider to provide configurations to traefik using the given configuration channel.
func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error {
ctxLog := log.With(context.Background(), log.Str(log.ProviderName, providerName))
logger := log.FromContext(ctxLog)
k8sClient, err := p.newK8sClient(ctxLog)
if err != nil {
return err
}
pool.GoCtx(func(ctxPool context.Context) {
operation := func() error {
eventsChan, err := k8sClient.WatchAll(p.Namespaces, ctxPool.Done())
if err != nil {
logger.Errorf("Error watching kubernetes events: %v", err)
timer := time.NewTimer(1 * time.Second)
select {
case <-timer.C:
return err
case <-ctxPool.Done():
return nil
}
}
throttleDuration := time.Duration(p.ThrottleDuration)
throttledChan := throttleEvents(ctxLog, throttleDuration, pool, eventsChan)
if throttledChan != nil {
eventsChan = throttledChan
}
for {
select {
case <-ctxPool.Done():
return nil
case event := <-eventsChan:
// Note that event is the *first* event that came in during this throttling interval -- if we're hitting our throttle, we may have dropped events.
// This is fine, because we don't treat different event types differently.
// But if we do in the future, we'll need to track more information about the dropped events.
conf := p.loadConfigurationFromGateway(ctxLog, k8sClient)
confHash, err := hashstructure.Hash(conf, nil)
switch {
case err != nil:
logger.Error("Unable to hash the configuration")
case p.lastConfiguration.Get() == confHash:
logger.Debugf("Skipping Kubernetes event kind %T", event)
default:
p.lastConfiguration.Set(confHash)
configurationChan <- dynamic.Message{
ProviderName: providerName,
Configuration: conf,
}
}
// If we're throttling,
// we sleep here for the throttle duration to enforce that we don't refresh faster than our throttle.
// time.Sleep returns immediately if p.ThrottleDuration is 0 (no throttle).
time.Sleep(throttleDuration)
}
}
}
notify := func(err error, time time.Duration) {
logger.Errorf("Provider connection error: %v; retrying in %s", err, time)
}
err := backoff.RetryNotify(safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctxPool), notify)
if err != nil {
logger.Errorf("Cannot connect to Provider: %v", err)
}
})
return nil
}
// TODO Handle errors and update resources statuses (gatewayClass, gateway).
func (p *Provider) loadConfigurationFromGateway(ctx context.Context, client Client) *dynamic.Configuration {
logger := log.FromContext(ctx)
gatewayClassNames := map[string]struct{}{}
gatewayClasses, err := client.GetGatewayClasses()
if err != nil {
logger.Errorf("Cannot find GatewayClasses: %v", err)
return &dynamic.Configuration{
UDP: &dynamic.UDPConfiguration{
Routers: map[string]*dynamic.UDPRouter{},
Services: map[string]*dynamic.UDPService{},
},
TCP: &dynamic.TCPConfiguration{
Routers: map[string]*dynamic.TCPRouter{},
Services: map[string]*dynamic.TCPService{},
},
HTTP: &dynamic.HTTPConfiguration{
Routers: map[string]*dynamic.Router{},
Middlewares: map[string]*dynamic.Middleware{},
Services: map[string]*dynamic.Service{},
},
TLS: &dynamic.TLSConfiguration{},
}
}
for _, gatewayClass := range gatewayClasses {
if gatewayClass.Spec.ControllerName == "traefik.io/gateway-controller" {
gatewayClassNames[gatewayClass.Name] = struct{}{}
err := client.UpdateGatewayClassStatus(gatewayClass, metav1.Condition{
Type: string(gatev1alpha2.GatewayClassConditionStatusAccepted),
Status: metav1.ConditionTrue,
Reason: "Handled",
Message: "Handled by Traefik controller",
LastTransitionTime: metav1.Now(),
})
if err != nil {
logger.Errorf("Failed to update %s condition: %v", gatev1alpha2.GatewayClassConditionStatusAccepted, err)
}
}
}
cfgs := map[string]*dynamic.Configuration{}
// TODO check if we can only use the default filtering mechanism
for _, gateway := range client.GetGateways() {
ctxLog := log.With(ctx, log.Str("gateway", gateway.Name), log.Str("namespace", gateway.Namespace))
logger := log.FromContext(ctxLog)
if _, ok := gatewayClassNames[string(gateway.Spec.GatewayClassName)]; !ok {
continue
}
cfg, err := p.createGatewayConf(ctxLog, client, gateway)
if err != nil {
logger.Error(err)
continue
}
cfgs[gateway.Name+gateway.Namespace] = cfg
}
conf := provider.Merge(ctx, cfgs)
conf.TLS = &dynamic.TLSConfiguration{}
for _, cfg := range cfgs {
if conf.TLS == nil {
conf.TLS = &dynamic.TLSConfiguration{}
}
conf.TLS.Certificates = append(conf.TLS.Certificates, cfg.TLS.Certificates...)
for name, options := range cfg.TLS.Options {
if conf.TLS.Options == nil {
conf.TLS.Options = map[string]tls.Options{}
}
conf.TLS.Options[name] = options
}
for name, store := range cfg.TLS.Stores {
if conf.TLS.Stores == nil {
conf.TLS.Stores = map[string]tls.Store{}
}
conf.TLS.Stores[name] = store
}
}
return conf
}
func (p *Provider) createGatewayConf(ctx context.Context, client Client, gateway *gatev1alpha2.Gateway) (*dynamic.Configuration, error) {
conf := &dynamic.Configuration{
UDP: &dynamic.UDPConfiguration{
Routers: map[string]*dynamic.UDPRouter{},
Services: map[string]*dynamic.UDPService{},
},
TCP: &dynamic.TCPConfiguration{
Routers: map[string]*dynamic.TCPRouter{},
Services: map[string]*dynamic.TCPService{},
},
HTTP: &dynamic.HTTPConfiguration{
Routers: map[string]*dynamic.Router{},
Middlewares: map[string]*dynamic.Middleware{},
Services: map[string]*dynamic.Service{},
},
TLS: &dynamic.TLSConfiguration{},
}
tlsConfigs := make(map[string]*tls.CertAndStores)
// GatewayReasonListenersNotValid is used when one or more
// Listeners have an invalid or unsupported configuration
// and cannot be configured on the Gateway.
listenerStatuses := p.fillGatewayConf(ctx, client, gateway, conf, tlsConfigs)
gatewayStatus, errG := p.makeGatewayStatus(listenerStatuses)
err := client.UpdateGatewayStatus(gateway, gatewayStatus)
if err != nil {
return nil, fmt.Errorf("an error occurred while updating gateway status: %w", err)
}
if errG != nil {
return nil, fmt.Errorf("an error occurred while creating gateway status: %w", errG)
}
if len(tlsConfigs) > 0 {
conf.TLS.Certificates = append(conf.TLS.Certificates, getTLSConfig(tlsConfigs)...)
}
return conf, nil
}
func (p *Provider) fillGatewayConf(ctx context.Context, client Client, gateway *gatev1alpha2.Gateway, conf *dynamic.Configuration, tlsConfigs map[string]*tls.CertAndStores) []gatev1alpha2.ListenerStatus {
logger := log.FromContext(ctx)
listenerStatuses := make([]gatev1alpha2.ListenerStatus, len(gateway.Spec.Listeners))
allocatedListeners := make(map[string]struct{})
for i, listener := range gateway.Spec.Listeners {
listenerStatuses[i] = gatev1alpha2.ListenerStatus{
Name: listener.Name,
SupportedKinds: []gatev1alpha2.RouteGroupKind{},
Conditions: []metav1.Condition{},
}
supportedKinds, conditions := supportedRouteKinds(listener.Protocol)
if len(conditions) > 0 {
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, conditions...)
continue
}
listenerStatuses[i].SupportedKinds = supportedKinds
routeKinds, conditions := getAllowedRouteKinds(listener, supportedKinds)
if len(conditions) > 0 {
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, conditions...)
continue
}
listenerKey := makeListenerKey(listener)
if _, ok := allocatedListeners[listenerKey]; ok {
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionConflicted),
Status: metav1.ConditionTrue,
LastTransitionTime: metav1.Now(),
Reason: "DuplicateListener",
Message: "A listener with same protocol, port and hostname already exists",
})
continue
}
allocatedListeners[listenerKey] = struct{}{}
ep, err := p.entryPointName(listener.Port, listener.Protocol)
if err != nil {
// update "Detached" status with "PortUnavailable" reason
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionDetached),
Status: metav1.ConditionTrue,
LastTransitionTime: metav1.Now(),
Reason: string(gatev1alpha2.ListenerReasonPortUnavailable),
Message: fmt.Sprintf("Cannot find entryPoint for Gateway: %v", err),
})
continue
}
if (listener.Protocol == gatev1alpha2.HTTPProtocolType || listener.Protocol == gatev1alpha2.TCPProtocolType) && listener.TLS != nil {
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionDetached),
Status: metav1.ConditionTrue,
LastTransitionTime: metav1.Now(),
Reason: "InvalidTLSConfiguration", // TODO check the spec if a proper reason is introduced at some point
Message: "TLS configuration must no be defined when using HTTP or TCP protocol",
})
continue
}
// TLS
if listener.Protocol == gatev1alpha2.HTTPSProtocolType || listener.Protocol == gatev1alpha2.TLSProtocolType {
if listener.TLS == nil || (len(listener.TLS.CertificateRefs) == 0 && listener.TLS.Mode != nil && *listener.TLS.Mode != gatev1alpha2.TLSModePassthrough) {
// update "Detached" status with "UnsupportedProtocol" reason
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionDetached),
Status: metav1.ConditionTrue,
LastTransitionTime: metav1.Now(),
Reason: "InvalidTLSConfiguration", // TODO check the spec if a proper reason is introduced at some point
Message: fmt.Sprintf("No TLS configuration for Gateway Listener %s:%d and protocol %q",
listener.Name, listener.Port, listener.Protocol),
})
continue
}
var tlsModeType gatev1alpha2.TLSModeType
if listener.TLS.Mode != nil {
tlsModeType = *listener.TLS.Mode
}
isTLSPassthrough := tlsModeType == gatev1alpha2.TLSModePassthrough
if isTLSPassthrough && len(listener.TLS.CertificateRefs) > 0 {
// https://gateway-api.sigs.k8s.io/v1alpha2/references/spec/#gateway.networking.k8s.io/v1alpha2.GatewayTLSConfig
logger.Warnf("In case of Passthrough TLS mode, no TLS settings take effect as the TLS session from the client is NOT terminated at the Gateway")
}
// Allowed configurations:
// Protocol TLS -> Passthrough -> TLSRoute/TCPRoute
// Protocol TLS -> Terminate -> TLSRoute/TCPRoute
// Protocol HTTPS -> Terminate -> HTTPRoute
if listener.Protocol == gatev1alpha2.HTTPSProtocolType && isTLSPassthrough {
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionDetached),
Status: metav1.ConditionTrue,
LastTransitionTime: metav1.Now(),
Reason: string(gatev1alpha2.ListenerReasonUnsupportedProtocol),
Message: "HTTPS protocol is not supported with TLS mode Passthrough",
})
continue
}
if !isTLSPassthrough {
if len(listener.TLS.CertificateRefs) == 0 {
// update "ResolvedRefs" status true with "InvalidCertificateRef" reason
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: string(gatev1alpha2.ListenerReasonInvalidCertificateRef),
Message: "One TLS CertificateRef is required in Terminate mode",
})
continue
}
// TODO Should we support multiple certificates?
certificateRef := listener.TLS.CertificateRefs[0]
if certificateRef.Kind == nil || *certificateRef.Kind != "Secret" ||
certificateRef.Group == nil || (*certificateRef.Group != "" && *certificateRef.Group != "core") {
// update "ResolvedRefs" status true with "InvalidCertificateRef" reason
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: string(gatev1alpha2.ListenerReasonInvalidCertificateRef),
Message: fmt.Sprintf("Unsupported TLS CertificateRef group/kind: %v/%v", certificateRef.Group, certificateRef.Kind),
})
continue
}
// TODO Support ReferencePolicy to support cross namespace references.
if certificateRef.Namespace != nil && string(*certificateRef.Namespace) != gateway.Namespace {
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: string(gatev1alpha2.ListenerReasonInvalidCertificateRef),
Message: "Cross namespace secrets are not supported",
})
continue
}
configKey := gateway.Namespace + "/" + string(certificateRef.Name)
if _, tlsExists := tlsConfigs[configKey]; !tlsExists {
tlsConf, err := getTLS(client, certificateRef.Name, gateway.Namespace)
if err != nil {
// update "ResolvedRefs" status true with "InvalidCertificateRef" reason
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: string(gatev1alpha2.ListenerReasonInvalidCertificateRef),
Message: fmt.Sprintf("Error while retrieving certificate: %v", err),
})
continue
}
tlsConfigs[configKey] = tlsConf
}
}
}
for _, routeKind := range routeKinds {
switch routeKind.Kind {
case kindHTTPRoute:
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, p.gatewayHTTPRouteToHTTPConf(ctx, ep, listener, gateway, client, conf)...)
case kindTCPRoute:
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, gatewayTCPRouteToTCPConf(ctx, ep, listener, gateway, client, conf)...)
case kindTLSRoute:
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, gatewayTLSRouteToTCPConf(ctx, ep, listener, gateway, client, conf)...)
}
}
}
return listenerStatuses
}
func (p *Provider) makeGatewayStatus(listenerStatuses []gatev1alpha2.ListenerStatus) (gatev1alpha2.GatewayStatus, error) {
// As Status.Addresses are not implemented yet, we initialize an empty array to follow the API expectations.
gatewayStatus := gatev1alpha2.GatewayStatus{
Addresses: []gatev1alpha2.GatewayAddress{},
}
var result error
for i, listener := range listenerStatuses {
if len(listener.Conditions) == 0 {
// GatewayConditionReady "Ready", GatewayConditionReason "ListenerReady"
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionReady),
Status: metav1.ConditionTrue,
LastTransitionTime: metav1.Now(),
Reason: "ListenerReady",
Message: "No error found",
})
continue
}
for _, condition := range listener.Conditions {
result = multierror.Append(result, errors.New(condition.Message))
}
}
if result != nil {
// GatewayConditionReady "Ready", GatewayConditionReason "ListenersNotValid"
gatewayStatus.Conditions = append(gatewayStatus.Conditions, metav1.Condition{
Type: string(gatev1alpha2.GatewayConditionReady),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: string(gatev1alpha2.GatewayReasonListenersNotValid),
Message: "All Listeners must be valid",
})
return gatewayStatus, result
}
gatewayStatus.Listeners = listenerStatuses
gatewayStatus.Conditions = append(gatewayStatus.Conditions,
// update "Scheduled" status with "ResourcesAvailable" reason
metav1.Condition{
Type: string(gatev1alpha2.GatewayConditionScheduled),
Status: metav1.ConditionTrue,
Reason: "ResourcesAvailable",
Message: "Resources available",
LastTransitionTime: metav1.Now(),
},
// update "Ready" status with "ListenersValid" reason
metav1.Condition{
Type: string(gatev1alpha2.GatewayConditionReady),
Status: metav1.ConditionTrue,
Reason: "ListenersValid",
Message: "Listeners valid",
LastTransitionTime: metav1.Now(),
},
)
return gatewayStatus, nil
}
func (p *Provider) entryPointName(port gatev1alpha2.PortNumber, protocol gatev1alpha2.ProtocolType) (string, error) {
portStr := strconv.FormatInt(int64(port), 10)
for name, entryPoint := range p.EntryPoints {
if strings.HasSuffix(entryPoint.Address, ":"+portStr) {
// If the protocol is HTTP the entryPoint must have no TLS conf
// Not relevant for gatev1alpha2.TLSProtocolType && gatev1alpha2.TCPProtocolType
if protocol == gatev1alpha2.HTTPProtocolType && entryPoint.HasHTTPTLSConf {
continue
}
return name, nil
}
}
return "", fmt.Errorf("no matching entryPoint for port %d and protocol %q", port, protocol)
}
func supportedRouteKinds(protocol gatev1alpha2.ProtocolType) ([]gatev1alpha2.RouteGroupKind, []metav1.Condition) {
group := gatev1alpha2.Group(gatev1alpha2.GroupName)
switch protocol {
case gatev1alpha2.TCPProtocolType:
return []gatev1alpha2.RouteGroupKind{{Kind: kindTCPRoute, Group: &group}}, nil
case gatev1alpha2.HTTPProtocolType, gatev1alpha2.HTTPSProtocolType:
return []gatev1alpha2.RouteGroupKind{{Kind: kindHTTPRoute, Group: &group}}, nil
case gatev1alpha2.TLSProtocolType:
return []gatev1alpha2.RouteGroupKind{
{Kind: kindTCPRoute, Group: &group},
{Kind: kindTLSRoute, Group: &group},
}, nil
}
return nil, []metav1.Condition{{
Type: string(gatev1alpha2.ListenerConditionDetached),
Status: metav1.ConditionTrue,
LastTransitionTime: metav1.Now(),
Reason: string(gatev1alpha2.ListenerReasonUnsupportedProtocol),
Message: fmt.Sprintf("Unsupported listener protocol %q", protocol),
}}
}
func getAllowedRouteKinds(listener gatev1alpha2.Listener, supportedKinds []gatev1alpha2.RouteGroupKind) ([]gatev1alpha2.RouteGroupKind, []metav1.Condition) {
if listener.AllowedRoutes == nil || len(listener.AllowedRoutes.Kinds) == 0 {
return supportedKinds, nil
}
var (
routeKinds []gatev1alpha2.RouteGroupKind
conditions []metav1.Condition
)
uniqRouteKinds := map[gatev1alpha2.Kind]struct{}{}
for _, routeKind := range listener.AllowedRoutes.Kinds {
var isSupported bool
for _, kind := range supportedKinds {
if routeKind.Kind == kind.Kind && routeKind.Group != nil && *routeKind.Group == *kind.Group {
isSupported = true
break
}
}
if !isSupported {
conditions = append(conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionDetached),
Status: metav1.ConditionTrue,
LastTransitionTime: metav1.Now(),
Reason: string(gatev1alpha2.ListenerReasonInvalidRouteKinds),
Message: fmt.Sprintf("Listener protocol %q does not support RouteGroupKind %v/%s", listener.Protocol, routeKind.Group, routeKind.Kind),
})
continue
}
if _, exists := uniqRouteKinds[routeKind.Kind]; !exists {
routeKinds = append(routeKinds, routeKind)
uniqRouteKinds[routeKind.Kind] = struct{}{}
}
}
return routeKinds, conditions
}
func (p *Provider) gatewayHTTPRouteToHTTPConf(ctx context.Context, ep string, listener gatev1alpha2.Listener, gateway *gatev1alpha2.Gateway, client Client, conf *dynamic.Configuration) []metav1.Condition {
if listener.AllowedRoutes == nil {
// Should not happen due to validation.
return nil
}
namespaces, err := getRouteBindingSelectorNamespace(client, gateway.Namespace, listener.AllowedRoutes.Namespaces)
if err != nil {
// update "ResolvedRefs" status true with "InvalidRoutesRef" reason
return []metav1.Condition{{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: "InvalidRouteNamespacesSelector", // Should never happen as the selector is validated by kubernetes
Message: fmt.Sprintf("Invalid route namespaces selector: %v", err),
}}
}
routes, err := client.GetHTTPRoutes(namespaces)
if err != nil {
// update "ResolvedRefs" status true with "InvalidRoutesRef" reason
return []metav1.Condition{{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: string(gatev1alpha2.ListenerReasonRefNotPermitted),
Message: fmt.Sprintf("Cannot fetch HTTPRoutes: %v", err),
}}
}
if len(routes) == 0 {
log.FromContext(ctx).Debugf("No HTTPRoutes found")
return nil
}
var conditions []metav1.Condition
for _, route := range routes {
if !shouldAttach(gateway, listener, route.Namespace, route.Spec.CommonRouteSpec) {
continue
}
hostnames := matchingHostnames(listener, route.Spec.Hostnames)
if len(hostnames) == 0 && listener.Hostname != nil && *listener.Hostname != "" && len(route.Spec.Hostnames) > 0 {
// TODO update the corresponding route parent status
// https://gateway-api.sigs.k8s.io/v1alpha2/references/spec/#gateway.networking.k8s.io/v1alpha2.TLSRoute
continue
}
hostRule, err := hostRule(hostnames)
if err != nil {
conditions = append(conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: "InvalidRouteHostname", // TODO check the spec if a proper reason is introduced at some point
Message: fmt.Sprintf("Skipping HTTPRoute %s: invalid hostname: %v", route.Name, err),
})
continue
}
for _, routeRule := range route.Spec.Rules {
rule, err := extractRule(routeRule, hostRule)
if err != nil {
// update "ResolvedRefs" status true with "DroppedRoutes" reason
conditions = append(conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: "UnsupportedPathOrHeaderType", // TODO check the spec if a proper reason is introduced at some point
Message: fmt.Sprintf("Skipping HTTPRoute %s: cannot generate rule: %v", route.Name, err),
})
}
router := dynamic.Router{
Rule: rule,
EntryPoints: []string{ep},
}
if listener.Protocol == gatev1alpha2.HTTPSProtocolType && listener.TLS != nil {
// TODO support let's encrypt
router.TLS = &dynamic.RouterTLSConfig{}
}
// Adding the gateway desc and the entryPoint desc prevents overlapping of routers build from the same routes.
routerName := route.Name + "-" + gateway.Name + "-" + ep
routerKey, err := makeRouterKey(router.Rule, makeID(route.Namespace, routerName))
if err != nil {
// update "ResolvedRefs" status true with "DroppedRoutes" reason
conditions = append(conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: "InvalidRouterKey", // Should never happen
Message: fmt.Sprintf("Skipping HTTPRoute %s: cannot make router's key with rule %s: %v", route.Name, router.Rule, err),
})
// TODO update the RouteStatus condition / deduplicate conditions on listener
continue
}
if len(routeRule.BackendRefs) == 0 {
continue
}
// Traefik internal service can be used only if there is only one BackendRef service reference.
if len(routeRule.BackendRefs) == 1 && isInternalService(routeRule.BackendRefs[0].BackendRef) {
router.Service = string(routeRule.BackendRefs[0].Name)
} else {
wrrService, subServices, err := loadServices(client, route.Namespace, routeRule.BackendRefs)
if err != nil {
// update "ResolvedRefs" status true with "DroppedRoutes" reason
conditions = append(conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: "InvalidBackendRefs", // TODO check the spec if a proper reason is introduced at some point
Message: fmt.Sprintf("Cannot load HTTPRoute service %s/%s: %v", route.Namespace, route.Name, err),
})
// TODO update the RouteStatus condition / deduplicate conditions on listener
continue
}
for svcName, svc := range subServices {
conf.HTTP.Services[svcName] = svc
}
serviceName := provider.Normalize(routerKey + "-wrr")
conf.HTTP.Services[serviceName] = wrrService
router.Service = serviceName
}
rt := &router
p.applyRouterTransform(ctx, rt, route)
routerKey = provider.Normalize(routerKey)
conf.HTTP.Routers[routerKey] = rt
}
}
return conditions
}
func gatewayTCPRouteToTCPConf(ctx context.Context, ep string, listener gatev1alpha2.Listener, gateway *gatev1alpha2.Gateway, client Client, conf *dynamic.Configuration) []metav1.Condition {
if listener.AllowedRoutes == nil {
// Should not happen due to validation.
return nil
}
namespaces, err := getRouteBindingSelectorNamespace(client, gateway.Namespace, listener.AllowedRoutes.Namespaces)
if err != nil {
// update "ResolvedRefs" status true with "InvalidRoutesRef" reason
return []metav1.Condition{{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: "InvalidRouteNamespacesSelector", // TODO should never happen as the selector is validated by Kubernetes
Message: fmt.Sprintf("Invalid route namespaces selector: %v", err),
}}
}
routes, err := client.GetTCPRoutes(namespaces)
if err != nil {
// update "ResolvedRefs" status true with "InvalidRoutesRef" reason
return []metav1.Condition{{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: string(gatev1alpha2.ListenerReasonRefNotPermitted),
Message: fmt.Sprintf("Cannot fetch TCPRoutes: %v", err),
}}
}
if len(routes) == 0 {
log.FromContext(ctx).Debugf("No TCPRoutes found")
return nil
}
var conditions []metav1.Condition
for _, route := range routes {
if !shouldAttach(gateway, listener, route.Namespace, route.Spec.CommonRouteSpec) {
continue
}
router := dynamic.TCPRouter{
Rule: "HostSNI(`*`)", // Gateway listener hostname not available in TCP
EntryPoints: []string{ep},
}
if listener.Protocol == gatev1alpha2.TLSProtocolType && listener.TLS != nil {
// TODO support let's encrypt
router.TLS = &dynamic.RouterTCPTLSConfig{
Passthrough: listener.TLS.Mode != nil && *listener.TLS.Mode == gatev1alpha2.TLSModePassthrough,
}
}
// Adding the gateway desc and the entryPoint desc prevents overlapping of routers build from the same routes.
routerName := route.Name + "-" + gateway.Name + "-" + ep
routerKey, err := makeRouterKey("", makeID(route.Namespace, routerName))
if err != nil {
// update "ResolvedRefs" status true with "DroppedRoutes" reason
conditions = append(conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: "InvalidRouterKey", // Should never happen
Message: fmt.Sprintf("Skipping TCPRoute %s: cannot make router's key with rule %s: %v", route.Name, router.Rule, err),
})
// TODO update the RouteStatus condition / deduplicate conditions on listener
continue
}
routerKey = provider.Normalize(routerKey)
var ruleServiceNames []string
for i, rule := range route.Spec.Rules {
if rule.BackendRefs == nil {
// Should not happen due to validation.
// https://github.com/kubernetes-sigs/gateway-api/blob/v0.4.0/apis/v1alpha2/tcproute_types.go#L76
continue
}
wrrService, subServices, err := loadTCPServices(client, route.Namespace, rule.BackendRefs)
if err != nil {
// update "ResolvedRefs" status true with "DroppedRoutes" reason
conditions = append(conditions, metav1.Condition{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: "InvalidBackendRefs", // TODO check the spec if a proper reason is introduced at some point
Message: fmt.Sprintf("Cannot load TCPRoute service %s/%s: %v", route.Namespace, route.Name, err),
})
// TODO update the RouteStatus condition / deduplicate conditions on listener
continue
}
for svcName, svc := range subServices {
conf.TCP.Services[svcName] = svc
}
serviceName := fmt.Sprintf("%s-wrr-%d", routerKey, i)
conf.TCP.Services[serviceName] = wrrService
ruleServiceNames = append(ruleServiceNames, serviceName)
}
if len(ruleServiceNames) == 1 {
router.Service = ruleServiceNames[0]
conf.TCP.Routers[routerKey] = &router
continue
}
routeServiceKey := routerKey + "-wrr"
routeService := &dynamic.TCPService{Weighted: &dynamic.TCPWeightedRoundRobin{}}
for _, name := range ruleServiceNames {
service := dynamic.TCPWRRService{Name: name}
service.SetDefaults()
routeService.Weighted.Services = append(routeService.Weighted.Services, service)
}
conf.TCP.Services[routeServiceKey] = routeService
router.Service = routeServiceKey
conf.TCP.Routers[routerKey] = &router
}
return conditions
}
func gatewayTLSRouteToTCPConf(ctx context.Context, ep string, listener gatev1alpha2.Listener, gateway *gatev1alpha2.Gateway, client Client, conf *dynamic.Configuration) []metav1.Condition {
if listener.AllowedRoutes == nil {
// Should not happen due to validation.
return nil
}
namespaces, err := getRouteBindingSelectorNamespace(client, gateway.Namespace, listener.AllowedRoutes.Namespaces)
if err != nil {
// update "ResolvedRefs" status true with "InvalidRoutesRef" reason
return []metav1.Condition{{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: "InvalidRouteNamespacesSelector", // TODO should never happen as the selector is validated by Kubernetes
Message: fmt.Sprintf("Invalid route namespaces selector: %v", err),
}}
}
routes, err := client.GetTLSRoutes(namespaces)
if err != nil {
// update "ResolvedRefs" status true with "InvalidRoutesRef" reason
return []metav1.Condition{{
Type: string(gatev1alpha2.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: string(gatev1alpha2.ListenerReasonRefNotPermitted),
Message: fmt.Sprintf("Cannot fetch TLSRoutes: %v", err),
}}
}
if len(routes) == 0 {
log.FromContext(ctx).Debugf("No TLSRoutes found")
return nil
}
var conditions []metav1.Condition
for _, route := range routes {
if !shouldAttach(gateway, listener, route.Namespace, route.Spec.CommonRouteSpec) {
continue
}
hostnames := matchingHostnames(listener, route.Spec.Hostnames)
if len(hostnames) == 0 && listener.Hostname != nil && *listener.Hostname != "" && len(route.Spec.Hostnames) > 0 {
// TODO update the corresponding route parent status
// https://gateway-api.sigs.k8s.io/v1alpha2/references/spec/#gateway.networking.k8s.io/v1alpha2.TLSRoute
continue
}
rule, err := hostSNIRule(hostnames)
if err != nil {
// update "ResolvedRefs" status true with "DroppedRoutes" reason
conditions = append(conditions, metav1.Condition{