-
Notifications
You must be signed in to change notification settings - Fork 590
/
parser.go
2005 lines (1812 loc) · 56.6 KB
/
parser.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 parser
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"github.com/ghodss/yaml"
"github.com/kong/go-kong/kong"
"github.com/kong/kubernetes-ingress-controller/internal/ingress/annotations"
"github.com/kong/kubernetes-ingress-controller/internal/ingress/store"
"github.com/kong/kubernetes-ingress-controller/internal/ingress/utils"
configurationv1 "github.com/kong/kubernetes-ingress-controller/pkg/apis/configuration/v1"
configurationv1beta1 "github.com/kong/kubernetes-ingress-controller/pkg/apis/configuration/v1beta1"
"github.com/mitchellh/mapstructure"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
networking "k8s.io/api/networking/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"
knative "knative.dev/networking/pkg/apis/networking/v1alpha1"
)
// Route represents a Kong Route and holds a reference to the Ingress
// rule.
type Route struct {
kong.Route
// Ingress object associated with this route
Ingress networking.Ingress
// TCPIngress object associated with this route
TCPIngress configurationv1beta1.TCPIngress
// Is this route coming from TCPIngress or networking.Ingress?
IsTCP bool
Plugins []kong.Plugin
}
type backend struct {
Name string
Port intstr.IntOrString
}
// Service represents a service in Kong and holds routes associated with the
// service and other k8s metadata.
type Service struct {
kong.Service
Backend backend
Namespace string
Routes []Route
Plugins []kong.Plugin
K8sService corev1.Service
}
// Upstream is a wrapper around Upstream object in Kong.
type Upstream struct {
kong.Upstream
Targets []Target
// Service this upstream is asosciated with.
Service Service
}
// Target is a wrapper around Target object in Kong.
type Target struct {
kong.Target
}
// Consumer holds a Kong consumer and its plugins and credentials.
type Consumer struct {
kong.Consumer
Plugins []kong.Plugin
KeyAuths []*kong.KeyAuth
HMACAuths []*kong.HMACAuth
JWTAuths []*kong.JWTAuth
BasicAuths []*kong.BasicAuth
ACLGroups []*kong.ACLGroup
Oauth2Creds []*kong.Oauth2Credential
k8sKongConsumer configurationv1.KongConsumer
}
// KongState holds the configuration that should be applied to Kong.
type KongState struct {
Services []Service
Upstreams []Upstream
Certificates []Certificate
CACertificates []kong.CACertificate
Plugins []Plugin
Consumers []Consumer
}
// Certificate represents the certificate object in Kong.
type Certificate struct {
kong.Certificate
}
// Plugin represetns a plugin Object in Kong.
type Plugin struct {
kong.Plugin
}
// Parser parses Kubernetes CRDs and Ingress rules and generates a
// Kong configuration.
type Parser struct {
store store.Storer
Logger logrus.FieldLogger
}
type parsedIngressRules struct {
SecretNameToSNIs map[string][]string
ServiceNameToServices map[string]Service
}
var supportedCreds = sets.NewString(
"acl",
"basic-auth",
"hmac-auth",
"jwt",
"key-auth",
"oauth2",
)
var validProtocols = regexp.MustCompile(`\Ahttps$|\Ahttp$|\Agrpc$|\Agrpcs|\Atcp|\Atls$`)
var validMethods = regexp.MustCompile(`\A[A-Z]+$`)
// New returns a new parser backed with store.
func New(store store.Storer, logger logrus.FieldLogger) Parser {
return Parser{store: store, Logger: logger}
}
// Build creates a Kong configuration from Ingress and Custom resources
// defined in Kuberentes.
// It throws an error if there is an error returned from client-go.
func (p *Parser) Build() (*KongState, error) {
var state KongState
ings := p.store.ListIngresses()
tcpIngresses, err := p.store.ListTCPIngresses()
if err != nil {
p.Logger.Errorf("failed to list TCPIngresses: %v", err)
}
// parse ingress rules
parsedInfo := p.parseIngressRules(ings, tcpIngresses)
knativeIngresses, err := p.store.ListKnativeIngresses()
if err != nil {
p.Logger.Errorf("failed to list Knative Ingresses: %v", err)
}
servicesFromKnative, secretToSNIsFromKnative := p.parseKnativeIngressRules(knativeIngresses)
for name, service := range servicesFromKnative {
parsedInfo.ServiceNameToServices[name] = service
}
for secret, snis := range secretToSNIsFromKnative {
var combinedSNIs []string
if snisFromIngress, ok := parsedInfo.SecretNameToSNIs[secret]; ok {
combinedSNIs = append(combinedSNIs, snisFromIngress...)
}
combinedSNIs = append(combinedSNIs, snis...)
parsedInfo.SecretNameToSNIs[secret] = combinedSNIs
}
// populate Kubernetes Service
for key, service := range parsedInfo.ServiceNameToServices {
k8sSvc, err := p.store.GetService(service.Namespace, service.Backend.Name)
if err != nil {
p.Logger.WithFields(logrus.Fields{
"service_name": service.Backend.Name,
"service_namespace": service.Namespace,
}).Errorf("failed to fetch service: %v", err)
}
if k8sSvc != nil {
service.K8sService = *k8sSvc
}
secretName := annotations.ExtractClientCertificate(
service.K8sService.GetAnnotations())
if secretName != "" {
secret, err := p.store.GetSecret(service.K8sService.Namespace,
secretName)
secretKey := service.K8sService.Namespace + "/" + secretName
// ensure that the cert is loaded into Kong
if _, ok := parsedInfo.SecretNameToSNIs[secretKey]; !ok {
parsedInfo.SecretNameToSNIs[secretKey] = []string{}
}
if err == nil {
service.ClientCertificate = &kong.Certificate{
ID: kong.String(string(secret.UID)),
}
} else {
p.Logger.WithFields(logrus.Fields{
"secret_name": secretName,
"secret_namespace": service.K8sService.Namespace,
}).Errorf("failed to fetch secret: %v", err)
}
}
parsedInfo.ServiceNameToServices[key] = service
}
// add the routes and services to the state
for _, service := range parsedInfo.ServiceNameToServices {
state.Services = append(state.Services, service)
}
// generate Upstreams and Targets from service defs
state.Upstreams = p.getUpstreams(parsedInfo.ServiceNameToServices)
// merge KongIngress with Routes, Services and Upstream
p.fillOverrides(state)
// generate consumers and credentials
p.fillConsumersAndCredentials(&state)
// process annotation plugins
state.Plugins = p.fillPlugins(state)
// generate Certificates and SNIs
state.Certificates = p.getCerts(parsedInfo.SecretNameToSNIs)
// populate CA certificates in Kong
state.CACertificates, err = p.getCACerts()
if err != nil {
return nil, err
}
return &state, nil
}
func (p *Parser) getCACerts() ([]kong.CACertificate, error) {
caCertSecrets, err := p.store.ListCACerts()
if err != nil {
return nil, err
}
var caCerts []kong.CACertificate
for _, certSecret := range caCertSecrets {
secretName := certSecret.Namespace + "/" + certSecret.Name
idbytes, idExists := certSecret.Data["id"]
logger := p.Logger.WithFields(logrus.Fields{
"secret_name": secretName,
"secret_namespace": certSecret.Namespace,
})
if !idExists {
logger.Errorf("invalid CA certificate: missing 'id' field in data")
continue
}
caCertbytes, certExists := certSecret.Data["cert"]
if !certExists {
logger.Errorf("invalid CA certificate: missing 'cert' field in data")
continue
}
pemBlock, _ := pem.Decode(caCertbytes)
if pemBlock == nil {
logger.Errorf("invalid CA certificate: invalid PEM block")
continue
}
x509Cert, err := x509.ParseCertificate(pemBlock.Bytes)
if err != nil {
logger.Errorf("invalid CA certificate: failed to parse certificate: %v", err)
continue
}
if !x509Cert.IsCA {
logger.Errorf("invalid CA certificate: certificate is missing the 'CA' basic constraint: %v", err)
continue
}
caCerts = append(caCerts, kong.CACertificate{
ID: kong.String(string(idbytes)),
Cert: kong.String(string(caCertbytes)),
})
}
return caCerts, nil
}
func (p *Parser) processCredential(credType string, consumer *Consumer,
credConfig interface{}) error {
switch credType {
case "key-auth", "keyauth_credential":
var cred kong.KeyAuth
err := decodeCredential(credConfig, &cred)
if err != nil {
return fmt.Errorf("failed to decode key-auth credential: %w", err)
}
consumer.KeyAuths = append(consumer.KeyAuths, &cred)
case "basic-auth", "basicauth_credential":
var cred kong.BasicAuth
err := decodeCredential(credConfig, &cred)
if err != nil {
return fmt.Errorf("failed to decode basic-auth credential: %w", err)
}
consumer.BasicAuths = append(consumer.BasicAuths, &cred)
case "hmac-auth", "hmacauth_credential":
var cred kong.HMACAuth
err := decodeCredential(credConfig, &cred)
if err != nil {
return fmt.Errorf("failed to decode hmac-auth credential: %w", err)
}
consumer.HMACAuths = append(consumer.HMACAuths, &cred)
case "oauth2":
var cred kong.Oauth2Credential
err := decodeCredential(credConfig, &cred)
if err != nil {
return fmt.Errorf("failed to decode oauth2 credential: %w", err)
}
consumer.Oauth2Creds = append(consumer.Oauth2Creds, &cred)
case "jwt", "jwt_secret":
var cred kong.JWTAuth
err := decodeCredential(credConfig, &cred)
if err != nil {
p.Logger.Errorf("failed to process JWT credential: %v", err)
}
// This is treated specially because only this
// field might be omitted by user under the expectation
// that Kong will insert the default.
// If we don't set it, decK will detect a diff and PUT this
// credential everytime it performs a sync operation, which
// leads to unnecessary cache invalidations in Kong.
if cred.Algorithm == nil || *cred.Algorithm == "" {
cred.Algorithm = kong.String("HS256")
}
consumer.JWTAuths = append(consumer.JWTAuths, &cred)
case "acl":
var cred kong.ACLGroup
err := decodeCredential(credConfig, &cred)
if err != nil {
p.Logger.Errorf("failed to process ACL group: %v", err)
}
consumer.ACLGroups = append(consumer.ACLGroups, &cred)
default:
return fmt.Errorf("invalid credential type: '%v'", credType)
}
return nil
}
func decodeCredential(credConfig interface{},
credStructPointer interface{}) error {
decoder, err := mapstructure.NewDecoder(
&mapstructure.DecoderConfig{TagName: "json",
Result: credStructPointer,
})
if err != nil {
return fmt.Errorf("failed to create a decoder: %w", err)
}
err = decoder.Decode(credConfig)
if err != nil {
return fmt.Errorf("failed to decode credential: %w", err)
}
return nil
}
func (p *Parser) fillConsumersAndCredentials(state *KongState) {
consumerIndex := make(map[string]Consumer)
// build consumer index
for _, consumer := range p.store.ListKongConsumers() {
var c Consumer
if consumer.Username == "" && consumer.CustomID == "" {
continue
}
if consumer.Username != "" {
c.Username = kong.String(consumer.Username)
}
if consumer.CustomID != "" {
c.CustomID = kong.String(consumer.CustomID)
}
c.k8sKongConsumer = *consumer
logger := p.Logger.WithFields(logrus.Fields{
"kongconsumer_name": consumer.Name,
"kongconsumer_namespace": consumer.Namespace,
})
for _, cred := range consumer.Credentials {
logger = logger.WithFields(logrus.Fields{
"secret_name": cred,
"secret_namespace": consumer.Namespace,
})
secret, err := p.store.GetSecret(consumer.Namespace, cred)
if err != nil {
logger.Errorf("failed to fetch secret: %v", err)
continue
}
credConfig := map[string]interface{}{}
for k, v := range secret.Data {
// TODO populate these based on schema from Kong
// and remove this workaround
if k == "redirect_uris" {
credConfig[k] = strings.Split(string(v), ",")
continue
}
credConfig[k] = string(v)
}
credType, ok := credConfig["kongCredType"].(string)
if !ok {
logger.Errorf("failed to provision credential: invalid credType: %v", credType)
}
if !supportedCreds.Has(credType) {
logger.Errorf("failed to provision credential: invalid credType: %v", credType)
continue
}
if len(credConfig) <= 1 { // 1 key of credType itself
logger.Errorf("failed to provision credential: empty secret")
continue
}
err = p.processCredential(credType, &c, credConfig)
if err != nil {
logger.Errorf("failed to provision credential: %v", err)
continue
}
}
consumerIndex[consumer.Namespace+"/"+consumer.Name] = c
}
// legacy attach credentials
credentials := p.store.ListKongCredentials()
if len(credentials) > 0 {
p.Logger.Warnf("deprecated KongCredential resource in use; " +
"please use secret-based credentials, " +
"KongCredential resource will be removed in future")
}
for _, credential := range credentials {
logger := p.Logger.WithFields(logrus.Fields{
"kongcredential_name": credential.Name,
"kongcredential_namespace": credential.Namespace,
"consumerRef": credential.ConsumerRef,
})
consumer, ok := consumerIndex[credential.Namespace+"/"+
credential.ConsumerRef]
if !ok {
continue
}
if credential.Type == "" {
logger.Errorf("invalid KongCredential: no Type provided")
continue
}
if !supportedCreds.Has(credential.Type) {
logger.Errorf("invalid KongCredential: invalid Type provided")
continue
}
if credential.Config == nil {
logger.Errorf("invalid KongCredential: empty config")
continue
}
err := p.processCredential(credential.Type, &consumer, credential.Config)
if err != nil {
logger.Errorf("failed to provision credential: %v", err)
continue
}
consumerIndex[credential.Namespace+"/"+credential.ConsumerRef] = consumer
}
// populate the consumer in the state
for _, c := range consumerIndex {
state.Consumers = append(state.Consumers, c)
}
}
func filterHosts(secretNameToSNIs map[string][]string, hosts []string) []string {
hostsToAdd := []string{}
seenHosts := map[string]bool{}
for _, hosts := range secretNameToSNIs {
for _, host := range hosts {
seenHosts[host] = true
}
}
for _, host := range hosts {
if !seenHosts[host] {
hostsToAdd = append(hostsToAdd, host)
}
}
return hostsToAdd
}
func processTLSSections(tlsSections []networking.IngressTLS,
namespace string, secretNameToSNIs map[string][]string) {
// TODO: optmize: collect all TLS sections and process at the same
// time to avoid regenerating the seen map; or use a seen map in the
// parser struct itself.
for _, tls := range tlsSections {
if len(tls.Hosts) == 0 {
continue
}
if tls.SecretName == "" {
continue
}
hosts := tls.Hosts
secretName := namespace + "/" + tls.SecretName
hosts = filterHosts(secretNameToSNIs, hosts)
if secretNameToSNIs[secretName] != nil {
hosts = append(hosts, secretNameToSNIs[secretName]...)
}
secretNameToSNIs[secretName] = hosts
}
}
func knativeIngressToNetworkingTLS(tls []knative.IngressTLS) []networking.IngressTLS {
var result []networking.IngressTLS
for _, t := range tls {
result = append(result, networking.IngressTLS{
Hosts: t.Hosts,
SecretName: t.SecretName,
})
}
return result
}
func tcpIngressToNetworkingTLS(tls []configurationv1beta1.IngressTLS) []networking.IngressTLS {
var result []networking.IngressTLS
for _, t := range tls {
result = append(result, networking.IngressTLS{
Hosts: t.Hosts,
SecretName: t.SecretName,
})
}
return result
}
func (p *Parser) parseKnativeIngressRules(
ingressList []*knative.Ingress) (map[string]Service, map[string][]string) {
sort.SliceStable(ingressList, func(i, j int) bool {
return ingressList[i].CreationTimestamp.Before(
&ingressList[j].CreationTimestamp)
})
services := map[string]Service{}
secretToSNIs := map[string][]string{}
for i := 0; i < len(ingressList); i++ {
ingress := *ingressList[i]
ingressSpec := ingress.Spec
processTLSSections(knativeIngressToNetworkingTLS(ingress.Spec.TLS),
ingress.Namespace, secretToSNIs)
for i, rule := range ingressSpec.Rules {
hosts := rule.Hosts
if rule.HTTP == nil {
continue
}
for j, rule := range rule.HTTP.Paths {
path := rule.Path
if path == "" {
path = "/"
}
r := Route{
Route: kong.Route{
// TODO Figure out a way to name the routes
// This is not a stable scheme
// 1. If a user adds a route in the middle,
// due to a shift, all the following routes will
// be PATCHED
// 2. Is it guaranteed that the order is stable?
// Meaning, the routes will always appear in the same
// order?
Name: kong.String(ingress.Namespace + "." + ingress.Name + "." + strconv.Itoa(i) + strconv.Itoa(j)),
Paths: kong.StringSlice(path),
StripPath: kong.Bool(false),
PreserveHost: kong.Bool(true),
Protocols: kong.StringSlice("http", "https"),
RegexPriority: kong.Int(0),
},
}
r.Hosts = kong.StringSlice(hosts...)
knativeBackend := knativeSelectSplit(rule.Splits)
serviceName := knativeBackend.ServiceNamespace + "." +
knativeBackend.ServiceName + "." +
knativeBackend.ServicePort.String()
serviceHost := knativeBackend.ServiceName + "." +
knativeBackend.ServiceNamespace + "." +
knativeBackend.ServicePort.String() + ".svc"
service, ok := services[serviceName]
if !ok {
var headers []string
for key, value := range knativeBackend.AppendHeaders {
headers = append(headers, key+":"+value)
}
for key, value := range rule.AppendHeaders {
headers = append(headers, key+":"+value)
}
service = Service{
Service: kong.Service{
Name: kong.String(serviceName),
Host: kong.String(serviceHost),
Port: kong.Int(80),
Protocol: kong.String("http"),
Path: kong.String("/"),
ConnectTimeout: kong.Int(60000),
ReadTimeout: kong.Int(60000),
WriteTimeout: kong.Int(60000),
Retries: kong.Int(5),
},
Namespace: ingress.Namespace,
Backend: backend{
Name: knativeBackend.ServiceName,
Port: knativeBackend.ServicePort,
},
}
if len(headers) > 0 {
service.Plugins = append(service.Plugins, kong.Plugin{
Name: kong.String("request-transformer"),
Config: kong.Configuration{
"add": map[string]interface{}{
"headers": headers,
},
},
})
}
}
service.Routes = append(service.Routes, r)
services[serviceName] = service
}
}
}
return services, secretToSNIs
}
func knativeSelectSplit(splits []knative.IngressBackendSplit) knative.IngressBackendSplit {
if len(splits) == 0 {
return knative.IngressBackendSplit{}
}
res := splits[0]
maxPercentage := splits[0].Percent
if len(splits) == 1 {
return res
}
for i := 1; i < len(splits); i++ {
if splits[i].Percent > maxPercentage {
res = splits[i]
maxPercentage = res.Percent
}
}
return res
}
func (p *Parser) parseIngressRules(
ingressList []*networking.Ingress,
tcpIngressList []*configurationv1beta1.TCPIngress) *parsedIngressRules {
sort.SliceStable(ingressList, func(i, j int) bool {
return ingressList[i].CreationTimestamp.Before(
&ingressList[j].CreationTimestamp)
})
sort.SliceStable(tcpIngressList, func(i, j int) bool {
return tcpIngressList[i].CreationTimestamp.Before(
&tcpIngressList[j].CreationTimestamp)
})
// generate the following:
// Services and Routes
var allDefaultBackends []networking.Ingress
secretNameToSNIs := make(map[string][]string)
serviceNameToServices := make(map[string]Service)
for i := 0; i < len(ingressList); i++ {
ingress := *ingressList[i]
ingressSpec := ingress.Spec
logger := p.Logger.WithFields(logrus.Fields{
"ingress_namespace": ingress.Namespace,
"ingress_name": ingress.Name,
})
if ingressSpec.Backend != nil {
allDefaultBackends = append(allDefaultBackends, ingress)
}
processTLSSections(ingressSpec.TLS, ingress.Namespace, secretNameToSNIs)
for i, rule := range ingressSpec.Rules {
host := rule.Host
if rule.HTTP == nil {
continue
}
for j, rule := range rule.HTTP.Paths {
path := rule.Path
if strings.Contains(path, "//") {
logger.Errorf("rule skipped: invalid path: '%v'", path)
continue
}
if path == "" {
path = "/"
}
r := Route{
Ingress: ingress,
Route: kong.Route{
// TODO Figure out a way to name the routes
// This is not a stable scheme
// 1. If a user adds a route in the middle,
// due to a shift, all the following routes will
// be PATCHED
// 2. Is it guaranteed that the order is stable?
// Meaning, the routes will always appear in the same
// order?
Name: kong.String(ingress.Namespace + "." + ingress.Name + "." + strconv.Itoa(i) + strconv.Itoa(j)),
Paths: kong.StringSlice(path),
StripPath: kong.Bool(false),
PreserveHost: kong.Bool(true),
Protocols: kong.StringSlice("http", "https"),
RegexPriority: kong.Int(0),
},
}
if host != "" {
r.Hosts = kong.StringSlice(host)
}
serviceName := ingress.Namespace + "." +
rule.Backend.ServiceName + "." +
rule.Backend.ServicePort.String()
service, ok := serviceNameToServices[serviceName]
if !ok {
service = Service{
Service: kong.Service{
Name: kong.String(serviceName),
Host: kong.String(rule.Backend.ServiceName +
"." + ingress.Namespace + "." +
rule.Backend.ServicePort.String() + ".svc"),
Port: kong.Int(80),
Protocol: kong.String("http"),
Path: kong.String("/"),
ConnectTimeout: kong.Int(60000),
ReadTimeout: kong.Int(60000),
WriteTimeout: kong.Int(60000),
Retries: kong.Int(5),
},
Namespace: ingress.Namespace,
Backend: backend{
Name: rule.Backend.ServiceName,
Port: rule.Backend.ServicePort,
},
}
}
service.Routes = append(service.Routes, r)
serviceNameToServices[serviceName] = service
}
}
}
for i := 0; i < len(tcpIngressList); i++ {
ingress := *tcpIngressList[i]
ingressSpec := ingress.Spec
logger := p.Logger.WithFields(logrus.Fields{
"tcpingress_namespace": ingress.Namespace,
"tcpingress_name": ingress.Name,
})
processTLSSections(tcpIngressToNetworkingTLS(ingressSpec.TLS),
ingress.Namespace, secretNameToSNIs)
for i, rule := range ingressSpec.Rules {
if rule.Port <= 0 {
logger.Errorf("invalid TCPIngress: invalid port: %v", rule.Port)
continue
}
r := Route{
IsTCP: true,
TCPIngress: ingress,
Route: kong.Route{
// TODO Figure out a way to name the routes
// This is not a stable scheme
// 1. If a user adds a route in the middle,
// due to a shift, all the following routes will
// be PATCHED
// 2. Is it guaranteed that the order is stable?
// Meaning, the routes will always appear in the same
// order?
Name: kong.String(ingress.Namespace + "." + ingress.Name + "." + strconv.Itoa(i)),
Protocols: kong.StringSlice("tcp", "tls"),
Destinations: []*kong.CIDRPort{
{
Port: kong.Int(rule.Port),
},
},
},
}
host := rule.Host
if host != "" {
r.SNIs = kong.StringSlice(host)
}
if rule.Backend.ServiceName == "" {
logger.Errorf("invalid TCPIngress: empty serviceName")
continue
}
if rule.Backend.ServicePort <= 0 {
logger.Errorf("invalid TCPIngress: invalid servicePort: %v", rule.Backend.ServicePort)
continue
}
serviceName := ingress.Namespace + "." +
rule.Backend.ServiceName + "." +
strconv.Itoa(rule.Backend.ServicePort)
service, ok := serviceNameToServices[serviceName]
if !ok {
service = Service{
Service: kong.Service{
Name: kong.String(serviceName),
Host: kong.String(rule.Backend.ServiceName +
"." + ingress.Namespace + "." +
strconv.Itoa(rule.Backend.ServicePort) + ".svc"),
Port: kong.Int(80),
Protocol: kong.String("tcp"),
ConnectTimeout: kong.Int(60000),
ReadTimeout: kong.Int(60000),
WriteTimeout: kong.Int(60000),
Retries: kong.Int(5),
},
Namespace: ingress.Namespace,
Backend: backend{
Name: rule.Backend.ServiceName,
Port: intstr.FromInt(rule.Backend.ServicePort),
},
}
}
service.Routes = append(service.Routes, r)
serviceNameToServices[serviceName] = service
}
}
sort.SliceStable(allDefaultBackends, func(i, j int) bool {
return allDefaultBackends[i].CreationTimestamp.Before(&allDefaultBackends[j].CreationTimestamp)
})
// Process the default backend
if len(allDefaultBackends) > 0 {
ingress := allDefaultBackends[0]
defaultBackend := allDefaultBackends[0].Spec.Backend
serviceName := allDefaultBackends[0].Namespace + "." +
defaultBackend.ServiceName + "." +
defaultBackend.ServicePort.String()
service, ok := serviceNameToServices[serviceName]
if !ok {
service = Service{
Service: kong.Service{
Name: kong.String(serviceName),
Host: kong.String(defaultBackend.ServiceName + "." +
ingress.Namespace + "." +
defaultBackend.ServicePort.String() + ".svc"),
Port: kong.Int(80),
Protocol: kong.String("http"),
ConnectTimeout: kong.Int(60000),
ReadTimeout: kong.Int(60000),
WriteTimeout: kong.Int(60000),
Retries: kong.Int(5),
},
Namespace: ingress.Namespace,
Backend: backend{
Name: defaultBackend.ServiceName,
Port: defaultBackend.ServicePort,
},
}
}
r := Route{
Ingress: ingress,
Route: kong.Route{
Name: kong.String(ingress.Namespace + "." + ingress.Name),
Paths: kong.StringSlice("/"),
StripPath: kong.Bool(false),
PreserveHost: kong.Bool(true),
Protocols: kong.StringSlice("http", "https"),
RegexPriority: kong.Int(0),
},
}
service.Routes = append(service.Routes, r)
serviceNameToServices[serviceName] = service
}
return &parsedIngressRules{
SecretNameToSNIs: secretNameToSNIs,
ServiceNameToServices: serviceNameToServices,
}
}
func (p *Parser) fillOverrides(state KongState) {
for i := 0; i < len(state.Services); i++ {
// Services
anns := state.Services[i].K8sService.Annotations
kongIngress, err := p.getKongIngressForService(
state.Services[i].K8sService)
if err != nil {
p.Logger.WithFields(logrus.Fields{
"service_name": state.Services[i].K8sService.Name,
"service_namespace": state.Services[i].K8sService.Namespace,
}).Errorf("failed to fetch KongIngress resource for Service: %v", err)
}
overrideService(&state.Services[i], kongIngress, anns)
// Routes
for j := 0; j < len(state.Services[i].Routes); j++ {
var kongIngress *configurationv1.KongIngress
var err error
if state.Services[i].Routes[j].IsTCP {
kongIngress, err = p.getKongIngressFromTCPIngress(
&state.Services[i].Routes[j].TCPIngress)
if err != nil {
p.Logger.WithFields(logrus.Fields{
"tcpingress_name": state.Services[i].Routes[j].TCPIngress.Name,
"tcpingress_namespace": state.Services[i].Routes[j].TCPIngress.Namespace,
}).Errorf("failed to fetch KongIngress resource for Ingress: %v", err)
}
} else {
kongIngress, err = p.getKongIngressFromIngress(
&state.Services[i].Routes[j].Ingress)
if err != nil {
p.Logger.WithFields(logrus.Fields{
"ingress_name": state.Services[i].Routes[j].Ingress.Name,
"ingress_namespace": state.Services[i].Routes[j].Ingress.Namespace,
}).Errorf("failed to fetch KongIngress resource for Ingress: %v", err)
}
}
p.overrideRoute(&state.Services[i].Routes[j], kongIngress)
}
}
// Upstreams
for i := 0; i < len(state.Upstreams); i++ {
kongIngress, err := p.getKongIngressForService(
state.Upstreams[i].Service.K8sService)
anns := state.Upstreams[i].Service.K8sService.Annotations
if err != nil {
p.Logger.WithFields(logrus.Fields{
"service_name": state.Upstreams[i].Service.K8sService.Name,
"service_namespace": state.Upstreams[i].Service.K8sService.Namespace,
}).Errorf("failed to fetch KongIngress resource for Service: %v", err)
continue
}
overrideUpstream(&state.Upstreams[i], kongIngress, anns)
}
}
// overrideServiceByKongIngress sets Service fields by KongIngress
func overrideServiceByKongIngress(service *Service,
kongIngress *configurationv1.KongIngress) {
if kongIngress == nil || kongIngress.Proxy == nil {
return
}
s := kongIngress.Proxy
if s.Protocol != nil {
service.Protocol = kong.String(*s.Protocol)
}
if s.Path != nil {
service.Path = kong.String(*s.Path)
}
if s.Retries != nil {
service.Retries = kong.Int(*s.Retries)
}
if s.ConnectTimeout != nil {
service.ConnectTimeout = kong.Int(*s.ConnectTimeout)
}
if s.ReadTimeout != nil {
service.ReadTimeout = kong.Int(*s.ReadTimeout)
}
if s.WriteTimeout != nil {
service.WriteTimeout = kong.Int(*s.WriteTimeout)
}
}
func overrideServicePath(service *kong.Service, anns map[string]string) {
if service == nil {
return
}
path := annotations.ExtractPath(anns)
if path == "" {
return
}
// kong errors if path doesn't start with `/`
if !strings.HasPrefix(path, "/") {
return
}
service.Path = kong.String(path)
}
func overrideServiceProtocol(service *kong.Service, anns map[string]string) {
if service == nil {
return
}