This repository was archived by the owner on Jun 3, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathplugin.go
More file actions
1046 lines (877 loc) · 30.4 KB
/
Copy pathplugin.go
File metadata and controls
1046 lines (877 loc) · 30.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package externaldns
import (
"context"
"fmt"
"net"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/coredns/coredns/plugin"
clog "github.com/coredns/coredns/plugin/pkg/log"
"github.com/coredns/coredns/plugin/transfer"
"github.com/miekg/dns"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
externaldnsv1alpha1 "sigs.k8s.io/external-dns/apis/v1alpha1"
"sigs.k8s.io/external-dns/endpoint"
"github.com/ionos-cloud/coredns-externaldns/internal/cache"
dnsbuilder "github.com/ionos-cloud/coredns-externaldns/internal/dns"
"github.com/ionos-cloud/coredns-externaldns/internal/watcher"
)
var pluginLog = clog.NewWithPlugin("externaldns-plugin")
// Plugin represents the ExternalDNS CoreDNS plugin
type Plugin struct {
Next plugin.Handler
// Configuration
config *Config
sortedZones []string // Zones sorted by length (longest first) for efficient matching
// Dependencies
cache *cache.Cache
watcher *watcher.DNSEndpointWatcher
serviceWatcher *watcher.ServiceWatcher
ingressWatcher *watcher.IngressWatcher
transfer *transfer.Transfer
recordBuilder *dnsbuilder.RecordBuilder
// Kubernetes clients
client dynamic.Interface
coreClient kubernetes.Interface
// Zone serial management
zoneSerials map[string]uint32
serialsMutex sync.RWMutex
configMapName string
configMapNamespace string
serialsResourceVersion string
// Context for cancellation
ctx context.Context
cancel context.CancelFunc
// Metrics
metrics *cache.Metrics
}
// Define metrics
var (
requestCount = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: plugin.Namespace,
Subsystem: "externaldns",
Name: "requests_total",
Help: "Counter of DNS requests made to external-dns plugin.",
}, []string{"proto", "type", "zone"})
cacheSize = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: plugin.Namespace,
Subsystem: "externaldns",
Name: "cache_size",
Help: "Number of entries in the DNS cache.",
}, []string{"zone"})
endpointEvents = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: plugin.Namespace,
Subsystem: "externaldns",
Name: "endpoint_events_total",
Help: "Counter of DNSEndpoint events processed.",
}, []string{"type"})
)
// New creates a new ExternalDNS plugin instance
func New(config *Config) *Plugin {
metrics := &cache.Metrics{
CacheSize: cacheSize,
RequestCount: requestCount,
EndpointEvents: endpointEvents,
}
// Normalize and sort zones by length (longest first) for efficient matching
sortedZones := make([]string, len(config.Zones))
for i, zone := range config.Zones {
// Normalize each zone once during creation
sortedZones[i] = dns.Fqdn(strings.ToLower(zone))
}
// Sort zones by length descending for longest match first
sort.Slice(sortedZones, func(i, j int) bool {
return len(sortedZones[i]) > len(sortedZones[j])
})
return &Plugin{
config: config,
sortedZones: sortedZones,
cache: cache.New(metrics),
metrics: metrics,
zoneSerials: make(map[string]uint32),
configMapName: config.ConfigMap.Name,
configMapNamespace: config.ConfigMap.Namespace,
recordBuilder: dnsbuilder.NewRecordBuilder(),
}
}
// Name implements the plugin.Handler interface
func (p *Plugin) Name() string {
return "externaldns"
}
// ServeDNS implements the plugin.Handler interface
func (p *Plugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
if len(r.Question) == 0 {
clog.Debug("No questions in DNS request")
return plugin.NextOrFailure(p.Name(), p.Next, ctx, w, r)
}
q := r.Question[0]
qname := q.Name
qtype := q.Qtype
zone := p.getConfiguredZoneForDomain(qname)
clog.Debugf("DNS request: qname=%s, qtype=%s, zone=%s", qname, dns.TypeToString[qtype], zone)
// Update metrics
if p.metrics.RequestCount != nil {
p.metrics.RequestCount.WithLabelValues(proto(w), dns.TypeToString[qtype], zone).Inc()
}
// If transfer is not loaded, we'll see these, answer with refused (no transfer allowed).
if qtype == dns.TypeAXFR || qtype == dns.TypeIXFR {
clog.Debugf("Zone transfer request refused for %s (type %s)", qname, dns.TypeToString[qtype])
return dns.RcodeRefused, nil
}
// Handle SOA queries for zones we're authoritative for
// This is critical for BIND/secondary DNS servers checking serial numbers before IXFR/AXFR
if qtype == dns.TypeSOA && zone != "." {
// Check if the query is for the zone apex (the zone itself)
normalizedQname := dns.Fqdn(strings.ToLower(qname))
if normalizedQname == zone {
m := new(dns.Msg)
m.SetReply(r)
m.Authoritative = true
m.Answer = []dns.RR{p.createSOARecord(zone, p.getZoneSerial(zone))}
clog.Debugf("Responding to SOA query for zone %s with serial %d", zone, p.getZoneSerial(zone))
if err := w.WriteMsg(m); err != nil {
clog.Errorf("Failed to write SOA response for zone %s: %v", zone, err)
return dns.RcodeServerFailure, err
}
return dns.RcodeSuccess, nil
}
}
// Try to get records from cache
records := p.cache.GetRecords(qname, zone, qtype)
clog.Debugf("Cache lookup for %s %s returned %d records", qname, dns.TypeToString[qtype], len(records))
// If no direct records found and querying for A or AAAA, check for CNAME records
if len(records) == 0 && (qtype == dns.TypeA || qtype == dns.TypeAAAA) {
cnameRecords := p.cache.GetRecords(qname, zone, dns.TypeCNAME)
if len(cnameRecords) > 0 {
clog.Debugf("Found %d CNAME records for %s when looking for %s", len(cnameRecords), qname, dns.TypeToString[qtype])
// Start with the CNAME records
records = make([]dns.RR, len(cnameRecords))
copy(records, cnameRecords)
// Now resolve each CNAME to get the actual A/AAAA records
for _, cnameRR := range cnameRecords {
if cname, ok := cnameRR.(*dns.CNAME); ok {
targetRecords := p.resolveCNAMETarget(cname.Target, qtype, 5) // max 5 hops to prevent infinite loops
records = append(records, targetRecords...)
}
}
} else {
clog.Debugf("No CNAME records found for %s when looking for %s", qname, dns.TypeToString[qtype])
}
}
if len(records) == 0 {
// No records found
clog.Debugf("No records found for %s %s", qname, dns.TypeToString[qtype])
// If not in a configured zone, pass to next plugin
if zone == "." {
return plugin.NextOrFailure(p.Name(), p.Next, ctx, w, r)
}
// Check if the domain exists with any record type
domainExists := p.cache.DomainExists(qname, zone)
if domainExists {
// Domain exists but not this record type - return NODATA (NOERROR with empty answer)
m := new(dns.Msg)
m.SetRcode(r, dns.RcodeSuccess)
m.Authoritative = true
m.Ns = []dns.RR{p.createSOARecord(zone, p.getZoneSerial(zone))}
clog.Debugf("Returning NODATA for %s %s in zone %s (domain exists)", qname, dns.TypeToString[qtype], zone)
if err := w.WriteMsg(m); err != nil {
clog.Errorf("Failed to write NODATA response: %v", err)
return dns.RcodeServerFailure, err
}
return dns.RcodeSuccess, nil
}
// Domain doesn't exist at all - return authoritative NXDOMAIN
m := new(dns.Msg)
m.SetRcode(r, dns.RcodeNameError)
m.Authoritative = true
m.Ns = []dns.RR{p.createSOARecord(zone, p.getZoneSerial(zone))}
clog.Debugf("Returning NXDOMAIN for %s %s in zone %s (domain does not exist)", qname, dns.TypeToString[qtype], zone)
if err := w.WriteMsg(m); err != nil {
clog.Errorf("Failed to write NXDOMAIN response: %v", err)
return dns.RcodeServerFailure, err
}
return dns.RcodeNameError, nil
}
// Create response
m := new(dns.Msg)
m.SetReply(r)
m.Authoritative = true
m.Answer = records
clog.Debugf("Responding to %s %s with %d records (authoritative)", qname, dns.TypeToString[qtype], len(records))
if err := w.WriteMsg(m); err != nil {
clog.Errorf("Failed to write DNS response for %s %s: %v", qname, dns.TypeToString[qtype], err)
return dns.RcodeServerFailure, err
}
clog.Debugf("Successfully responded to %s %s", qname, dns.TypeToString[qtype])
return dns.RcodeSuccess, nil
}
// Start initializes and starts the plugin
func (p *Plugin) Start(ctx context.Context) error {
p.ctx, p.cancel = context.WithCancel(ctx)
// Initialize Kubernetes clients
if err := p.initializeClients(); err != nil {
return fmt.Errorf("failed to initialize clients: %w", err)
}
// Set default ConfigMap namespace if not configured
if p.configMapNamespace == "" {
p.configMapNamespace = p.config.Namespace
if p.configMapNamespace == "" {
p.configMapNamespace = "default"
}
}
// Load existing zone serials from ConfigMap
if err := p.loadZoneSerials(ctx); err != nil {
return fmt.Errorf("failed to load zone serials: %w", err)
}
// Create and start the watcher
p.watcher = watcher.New(p.client, p.config.Namespace, p)
if err := p.watcher.Start(ctx); err != nil {
return fmt.Errorf("failed to start watcher: %w", err)
}
// Create and start the service watcher
p.serviceWatcher = watcher.NewServiceWatcher(p.coreClient, p.config.Namespace, p)
if err := p.serviceWatcher.Start(ctx); err != nil {
return fmt.Errorf("failed to start service watcher: %w", err)
}
// Create and start the ingress watcher
p.ingressWatcher = watcher.NewIngressWatcher(p.coreClient, p.config.Namespace, p)
if err := p.ingressWatcher.Start(ctx); err != nil {
return fmt.Errorf("failed to start ingress watcher: %w", err)
}
pluginLog.Info("ExternalDNS plugin started successfully")
return nil
}
// Stop stops the plugin
func (p *Plugin) Stop() {
if p.cancel != nil {
p.cancel()
}
if p.watcher != nil {
p.watcher.Stop()
}
if p.serviceWatcher != nil {
p.serviceWatcher.Stop()
}
if p.ingressWatcher != nil {
p.ingressWatcher.Stop()
}
pluginLog.Info("ExternalDNS plugin stopped")
}
// Transfer implements the transfer.Transfer interface for AXFR support
func (p *Plugin) Transfer(zone string, serial uint32) (<-chan []dns.RR, error) {
pluginLog.Debugf("AXFR request for zone: %s, serial: %d", zone, serial)
ch := make(chan []dns.RR)
go func() {
defer close(ch)
records := p.cache.GetZoneRecords(zone)
if records == nil {
pluginLog.Debugf("No records found for zone: %s", zone)
return
}
// Send SOA record first
soaRecord := p.createSOARecord(zone, serial)
ch <- []dns.RR{soaRecord}
// Send all records
for _, typeMap := range records {
for _, rrs := range typeMap {
if len(rrs) > 0 {
ch <- rrs
}
}
}
// Send SOA record last
ch <- []dns.RR{soaRecord}
}()
return ch, nil
}
// OnAdd handles DNSEndpoint addition events
func (p *Plugin) OnAdd(endpoint *externaldnsv1alpha1.DNSEndpoint) error {
pluginLog.Debugf("Adding DNSEndpoint: %s/%s", endpoint.Namespace, endpoint.Name)
createPTR := p.shouldCreatePTR(endpoint)
serial := p.generateSerial(endpoint, watch.Added)
return p.processEndpoints(endpoint.Spec.Endpoints, createPTR, watch.Added, serial)
}
// OnUpdate handles DNSEndpoint update events
func (p *Plugin) OnUpdate(endpoint *externaldnsv1alpha1.DNSEndpoint) error {
pluginLog.Debugf("Updating DNSEndpoint: %s/%s", endpoint.Namespace, endpoint.Name)
createPTR := p.shouldCreatePTR(endpoint)
serial := p.generateSerial(endpoint, watch.Modified)
return p.processEndpoints(endpoint.Spec.Endpoints, createPTR, watch.Modified, serial)
}
// OnDelete handles DNSEndpoint deletion events
func (p *Plugin) OnDelete(endpoint *externaldnsv1alpha1.DNSEndpoint) error {
pluginLog.Debugf("Deleting DNSEndpoint: %s/%s", endpoint.Namespace, endpoint.Name)
createPTR := p.shouldCreatePTR(endpoint)
serial := p.generateSerial(endpoint, watch.Deleted)
return p.processEndpoints(endpoint.Spec.Endpoints, createPTR, watch.Deleted, serial)
}
// OnServiceAdd handles Service addition events
func (p *Plugin) OnServiceAdd(svc *corev1.Service) error {
pluginLog.Debugf("Adding Service: %s/%s", svc.Namespace, svc.Name)
return p.processService(svc, watch.Added)
}
// OnServiceUpdate handles Service update events
func (p *Plugin) OnServiceUpdate(svc *corev1.Service) error {
pluginLog.Debugf("Updating Service: %s/%s", svc.Namespace, svc.Name)
return p.processService(svc, watch.Modified)
}
// OnServiceDelete handles Service deletion events
func (p *Plugin) OnServiceDelete(svc *corev1.Service) error {
pluginLog.Debugf("Deleting Service: %s/%s", svc.Namespace, svc.Name)
return p.processService(svc, watch.Deleted)
}
func (p *Plugin) processService(svc *corev1.Service, eventType watch.EventType) error {
endpoints := p.getEndpointsFromService(svc)
if len(endpoints) == 0 {
return nil
}
createPTR := p.shouldCreatePTR(svc)
zones := make(map[string]bool)
for _, ep := range endpoints {
zones[p.getConfiguredZoneForDomain(ep.DNSName)] = true
}
serial := p.getNextSerial(zones)
return p.processEndpoints(endpoints, createPTR, eventType, serial)
}
func (p *Plugin) processEndpoints(endpoints []*endpoint.Endpoint, createPTR bool, eventType watch.EventType, serial uint32) error {
if eventType == watch.Deleted {
for _, ep := range endpoints {
if err := p.removeEndpointRecord(ep, createPTR); err != nil {
pluginLog.Errorf("Failed to remove endpoint record: %v", err)
}
}
} else {
// Added or Modified
if eventType == watch.Modified {
for _, ep := range endpoints {
qtype := p.recordBuilder.RecordTypeToQType(ep.RecordType)
if qtype != 0 {
zone := p.getConfiguredZoneForDomain(ep.DNSName)
p.cache.RemoveAllRecords(ep.DNSName, zone, qtype)
if createPTR && (qtype == dns.TypeA || qtype == dns.TypeAAAA) {
p.cache.RemoveAllPTRRecordsForName(ep.DNSName)
}
}
}
}
for _, ep := range endpoints {
if err := p.addEndpointRecord(ep, createPTR); err != nil {
pluginLog.Errorf("Failed to add endpoint record: %v", err)
continue
}
}
}
// Update metrics
if p.metrics.EndpointEvents != nil {
label := "added"
switch eventType {
case watch.Modified:
label = "updated"
case watch.Deleted:
label = "deleted"
}
p.metrics.EndpointEvents.WithLabelValues(label).Inc()
}
// Update zone serials
zones := make(map[string]bool)
for _, ep := range endpoints {
zones[p.getConfiguredZoneForDomain(ep.DNSName)] = true
}
updatedZones := make([]string, 0, len(zones))
p.serialsMutex.Lock()
for zone := range zones {
// Skip updating serial for ROOT zone
if zone == "." {
continue
}
if currentSerial, exists := p.zoneSerials[zone]; !exists || serial > currentSerial {
p.zoneSerials[zone] = serial
p.cache.SetZoneSerial(zone, serial)
updatedZones = append(updatedZones, zone)
}
}
p.serialsMutex.Unlock()
// Save serials to ConfigMap only if there were actual updates
if len(updatedZones) > 0 {
p.saveZoneSerials(p.ctx, updatedZones)
}
return nil
}
func (p *Plugin) getEndpointsFromService(svc *corev1.Service) []*endpoint.Endpoint {
if svc.Spec.Type != corev1.ServiceTypeLoadBalancer {
return nil
}
hostname, ok := svc.Annotations["external-dns.alpha.kubernetes.io/hostname"]
if !ok || hostname == "" {
return nil
}
var endpoints []*endpoint.Endpoint
ttlVal := endpoint.TTL(p.config.TTL)
// Check for TTL annotation
if ttlStr, ok := svc.Annotations["external-dns.alpha.kubernetes.io/ttl"]; ok {
if t, err := strconv.Atoi(ttlStr); err == nil {
ttlVal = endpoint.TTL(t)
}
}
hostnames := strings.SplitSeq(hostname, ",")
for host := range hostnames {
host = strings.TrimSpace(host)
if host == "" {
continue
}
for _, ingress := range svc.Status.LoadBalancer.Ingress {
if ingress.IP != "" {
endpoints = append(endpoints, &endpoint.Endpoint{
DNSName: host,
Targets: endpoint.Targets{ingress.IP},
RecordType: "A",
RecordTTL: ttlVal,
})
}
if ingress.Hostname != "" {
endpoints = append(endpoints, &endpoint.Endpoint{
DNSName: host,
Targets: endpoint.Targets{ingress.Hostname},
RecordType: "CNAME",
RecordTTL: ttlVal,
})
}
}
}
return endpoints
}
// OnIngressAdd handles Ingress addition events
func (p *Plugin) OnIngressAdd(ing *networkingv1.Ingress) error {
pluginLog.Debugf("Adding Ingress: %s/%s", ing.Namespace, ing.Name)
return p.processIngress(ing, watch.Added)
}
// OnIngressUpdate handles Ingress update events
func (p *Plugin) OnIngressUpdate(ing *networkingv1.Ingress) error {
pluginLog.Debugf("Updating Ingress: %s/%s", ing.Namespace, ing.Name)
return p.processIngress(ing, watch.Modified)
}
// OnIngressDelete handles Ingress deletion events
func (p *Plugin) OnIngressDelete(ing *networkingv1.Ingress) error {
pluginLog.Debugf("Deleting Ingress: %s/%s", ing.Namespace, ing.Name)
return p.processIngress(ing, watch.Deleted)
}
func (p *Plugin) processIngress(ing *networkingv1.Ingress, eventType watch.EventType) error {
endpoints := p.getEndpointsFromIngress(ing)
if len(endpoints) == 0 {
return nil
}
createPTR := p.shouldCreatePTR(ing)
zones := make(map[string]bool)
for _, ep := range endpoints {
zones[p.getConfiguredZoneForDomain(ep.DNSName)] = true
}
serial := p.getNextSerial(zones)
return p.processEndpoints(endpoints, createPTR, eventType, serial)
}
func (p *Plugin) getEndpointsFromIngress(ing *networkingv1.Ingress) []*endpoint.Endpoint {
var endpoints []*endpoint.Endpoint
ttlVal := endpoint.TTL(p.config.TTL)
// Check for TTL annotation
if ttlStr, ok := ing.Annotations["external-dns.alpha.kubernetes.io/ttl"]; ok {
if t, err := strconv.Atoi(ttlStr); err == nil {
ttlVal = endpoint.TTL(t)
}
}
// Get targets from Ingress status
var targets endpoint.Targets
for _, ingress := range ing.Status.LoadBalancer.Ingress {
if ingress.IP != "" {
targets = append(targets, ingress.IP)
}
if ingress.Hostname != "" {
targets = append(targets, ingress.Hostname)
}
}
if len(targets) == 0 {
return nil
}
// Determine hosts to use
var hosts []string
seenHosts := make(map[string]bool)
if hostname, ok := ing.Annotations["external-dns.alpha.kubernetes.io/hostname"]; ok && hostname != "" {
// Use explicitly defined hostname(s)
for _, h := range strings.Split(hostname, ",") {
if h = strings.TrimSpace(h); h != "" {
if !seenHosts[h] {
hosts = append(hosts, h)
seenHosts[h] = true
}
}
}
}
if val, ok := ing.Annotations["coredns-externaldns.ionos.cloud/ingress-from-rules"]; ok && (val == "true" || val == "1") {
// Use hosts from Ingress rules if enabled via annotation
for _, rule := range ing.Spec.Rules {
if rule.Host != "" {
if !seenHosts[rule.Host] {
hosts = append(hosts, rule.Host)
seenHosts[rule.Host] = true
}
}
}
}
if len(hosts) == 0 {
return nil
}
// Create endpoints for each host
for _, host := range hosts {
targetsByRecordType := make(map[string]endpoint.Targets)
for _, target := range targets {
recordType := "A"
if net.ParseIP(target) == nil {
recordType = "CNAME"
}
targetsByRecordType[recordType] = append(targetsByRecordType[recordType], target)
}
for recordType, t := range targetsByRecordType {
endpoints = append(endpoints, &endpoint.Endpoint{
DNSName: host,
Targets: t,
RecordType: recordType,
RecordTTL: ttlVal,
})
}
}
return endpoints
}
// initializeClients initializes Kubernetes clients
func (p *Plugin) initializeClients() error {
config, err := rest.InClusterConfig()
if err != nil {
return fmt.Errorf("failed to create in-cluster config: %w", err)
}
p.client, err = dynamic.NewForConfig(config)
if err != nil {
return fmt.Errorf("failed to create dynamic client: %w", err)
}
p.coreClient, err = kubernetes.NewForConfig(config)
if err != nil {
return fmt.Errorf("failed to create core client: %w", err)
}
return nil
}
// addEndpointRecord adds a single endpoint record to the cache
func (p *Plugin) addEndpointRecord(ep *endpoint.Endpoint, createPTR bool) error {
qtype := p.recordBuilder.RecordTypeToQType(ep.RecordType)
if qtype == 0 {
return fmt.Errorf("unsupported record type: %s", ep.RecordType)
}
// Determine the zone for this endpoint using configured zones
zone := p.getConfiguredZoneForDomain(ep.DNSName)
ttl := p.config.TTL
if ep.RecordTTL > 0 {
ttl = uint32(ep.RecordTTL)
}
for _, target := range ep.Targets {
rr := p.recordBuilder.CreateRecord(ep.DNSName, qtype, ttl, target)
if rr == nil {
pluginLog.Errorf("Failed to create record for %s %s %s", ep.DNSName, ep.RecordType, target)
continue
}
p.cache.AddRecord(ep.DNSName, zone, qtype, rr)
// Create PTR record if requested and applicable
if createPTR && (qtype == dns.TypeA || qtype == dns.TypeAAAA) {
if ptrRR := p.recordBuilder.CreatePTRRecord(target, ep.DNSName, ttl); ptrRR != nil {
// PTR records typically go in reverse zones, but we'll use the same zone for simplicity
p.cache.AddRecord(ptrRR.Header().Name, zone, dns.TypePTR, ptrRR)
}
}
}
return nil
}
// removeEndpointRecord removes a single endpoint record from the cache
func (p *Plugin) removeEndpointRecord(ep *endpoint.Endpoint, createPTR bool) error {
qtype := p.recordBuilder.RecordTypeToQType(ep.RecordType)
if qtype == 0 {
return fmt.Errorf("unsupported record type: %s", ep.RecordType)
}
// Determine the zone for this endpoint
zone := p.getConfiguredZoneForDomain(ep.DNSName)
for _, target := range ep.Targets {
p.cache.RemoveRecord(ep.DNSName, zone, qtype, target)
// Remove PTR record if it was created
if createPTR && (qtype == dns.TypeA || qtype == dns.TypeAAAA) {
if ptrName, err := dns.ReverseAddr(target); err == nil {
// PTR records are in reverse zones, determine the appropriate zone
ptrZone := p.getConfiguredZoneForDomain(ptrName)
p.cache.RemoveRecord(ptrName, ptrZone, dns.TypePTR, ep.DNSName)
}
}
}
return nil
}
// shouldCreatePTR checks if PTR records should be created
func (p *Plugin) shouldCreatePTR(obj metav1.Object) bool {
annotations := obj.GetAnnotations()
if annotations == nil {
return false
}
val, exists := annotations["coredns-externaldns.ionos.cloud/create-ptr"]
return exists && (val == "true" || val == "1")
}
// generateSerial generates a serial number for the DNSEndpoint
// Uses a resource-based approach that's idempotent and doesn't depend on event types
func (p *Plugin) generateSerial(endpoint *externaldnsv1alpha1.DNSEndpoint, eventType watch.EventType) uint32 {
if eventType == watch.Added {
// For ADD events, always use resource-based serial for idempotency
// This ensures same resource always gets same serial regardless of watcher restarts
return p.calculateResourceSerial(endpoint)
}
// Determine which zones will be affected
zones := make(map[string]bool)
for _, ep := range endpoint.Spec.Endpoints {
zones[p.getConfiguredZoneForDomain(ep.DNSName)] = true
}
return p.getNextSerial(zones)
}
// getNextSerial calculates the next serial number for the given zones
func (p *Plugin) getNextSerial(zones map[string]bool) uint32 {
p.serialsMutex.RLock()
defer p.serialsMutex.RUnlock()
var maxSerial uint32
for zone := range zones {
if currentSerial, exists := p.zoneSerials[zone]; exists {
if currentSerial > maxSerial {
maxSerial = currentSerial
}
}
}
if maxSerial == 0 {
return uint32(time.Now().Unix())
}
return maxSerial + 1
}
// calculateResourceSerial calculates a deterministic serial based on resource metadata
// This ensures the same resource always gets the same serial regardless of event replay
func (p *Plugin) calculateResourceSerial(endpoint *externaldnsv1alpha1.DNSEndpoint) uint32 {
t := endpoint.GetCreationTimestamp()
if t.IsZero() {
return uint32(time.Now().Unix())
}
serial := uint32(t.Unix())
// Add generation to handle updates to the same resource
if endpoint.GetGeneration() > 0 {
serial += uint32(endpoint.GetGeneration())
}
return serial
}
// createSOARecord creates a SOA record for a zone
func (p *Plugin) createSOARecord(zone string, serial uint32) dns.RR {
return &dns.SOA{
Hdr: dns.RR_Header{
Name: zone,
Rrtype: dns.TypeSOA,
Class: dns.ClassINET,
Ttl: p.config.TTL,
},
Ns: dns.Fqdn(p.config.SOA.Nameserver),
Mbox: dns.Fqdn(p.config.SOA.Mailbox),
Serial: serial,
Refresh: 3600,
Retry: 1800,
Expire: 1209600,
Minttl: 300,
}
}
// zoneToConfigKey converts a zone name to a valid ConfigMap key
// Kubernetes ConfigMap keys cannot be "." so we convert it to "ROOT"
func (p *Plugin) zoneToConfigKey(zone string) string {
if zone == "." {
return "ROOT"
}
return zone
}
// configKeyToZone converts a ConfigMap key back to a zone name
func (p *Plugin) configKeyToZone(key string) string {
if key == "ROOT" {
return "."
}
return key
}
// loadZoneSerials loads zone serials from ConfigMap
func (p *Plugin) loadZoneSerials(ctx context.Context) error {
if p.coreClient == nil {
return fmt.Errorf("core client not initialized")
}
cm, err := p.coreClient.CoreV1().ConfigMaps(p.configMapNamespace).Get(ctx, p.configMapName, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
// Create empty ConfigMap
cm = &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: p.configMapName,
Namespace: p.configMapNamespace,
},
Data: map[string]string{},
}
cm, err = p.coreClient.CoreV1().ConfigMaps(p.configMapNamespace).Create(ctx, cm, metav1.CreateOptions{})
if err != nil {
if apierrors.IsAlreadyExists(err) {
// Try to get it again
cm, err = p.coreClient.CoreV1().ConfigMaps(p.configMapNamespace).Get(ctx, p.configMapName, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("failed to get ConfigMap after creation conflict: %w", err)
}
} else {
return fmt.Errorf("failed to create ConfigMap: %w", err)
}
}
} else {
return fmt.Errorf("failed to get ConfigMap: %w", err)
}
}
p.serialsMutex.Lock()
p.zoneSerials = make(map[string]uint32)
for configKey, serialStr := range cm.Data {
// Convert ConfigMap key back to zone name
zone := p.configKeyToZone(configKey)
if serial, err := strconv.ParseUint(serialStr, 10, 32); err == nil {
p.zoneSerials[zone] = uint32(serial)
// Update cache with loaded serial
p.cache.SetZoneSerial(zone, uint32(serial))
} else {
pluginLog.Warningf("Invalid serial value for zone %s: %s", zone, serialStr)
}
}
p.serialsResourceVersion = cm.ResourceVersion
p.serialsMutex.Unlock()
pluginLog.Infof("Loaded %d zone serials from ConfigMap", len(p.zoneSerials))
return nil
}
// saveZoneSerials saves zone serials to ConfigMap
func (p *Plugin) saveZoneSerials(ctx context.Context, updatedZones []string) {
if p.coreClient == nil {
return
}
p.serialsMutex.RLock()
data := make(map[string]string)
for zone, serial := range p.zoneSerials {
// Convert zone name to valid ConfigMap key
configKey := p.zoneToConfigKey(zone)
data[configKey] = strconv.FormatUint(uint64(serial), 10)
}
rv := p.serialsResourceVersion
p.serialsMutex.RUnlock()
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: p.configMapName,
Namespace: p.configMapNamespace,
ResourceVersion: rv,
},
Data: data,
}
_, err := p.coreClient.CoreV1().ConfigMaps(p.configMapNamespace).Update(ctx, cm, metav1.UpdateOptions{})
if err != nil {
if apierrors.IsConflict(err) {
pluginLog.Warningf("ConfigMap update conflict, reloading serials")
if reloadErr := p.loadZoneSerials(ctx); reloadErr != nil {
pluginLog.Errorf("Failed to reload serials after conflict: %v", reloadErr)
}
} else {
pluginLog.Errorf("Failed to update ConfigMap: %v", err)
}
return
}
// Notify others of zone changes
if p.transfer != nil {
for _, zone := range updatedZones {
pluginLog.Debugf("Notifying transfer plugin for zone: %s", zone)
if err := p.transfer.Notify(zone); err != nil {
pluginLog.Warningf("Failed to notify transfer of serial update for zone %s: %v", zone, err)
}
}
}
pluginLog.Debugf("Updated ConfigMap with %d zone serials", len(data))
}
// getZoneSerial retrieves the serial number for a zone
func (p *Plugin) getZoneSerial(zone string) uint32 {
p.serialsMutex.RLock()
defer p.serialsMutex.RUnlock()
if serial, exists := p.zoneSerials[zone]; exists {
return serial
}
return uint32(time.Now().Unix())
}
// resolveCNAMETarget resolves a CNAME target to get the actual A/AAAA records
func (p *Plugin) resolveCNAMETarget(target string, qtype uint16, maxHops int) []dns.RR {
if maxHops <= 0 {
clog.Debugf("Maximum CNAME hops reached for %s", target)
return nil
}
// Determine the zone for the target
targetZone := p.getConfiguredZoneForDomain(target)
// First, try to get direct A/AAAA records for the target
targetRecords := p.cache.GetRecords(target, targetZone, qtype)
if len(targetRecords) > 0 {
clog.Debugf("Found %d %s records for CNAME target %s", len(targetRecords), dns.TypeToString[qtype], target)
return targetRecords
}
// If no direct records, check if the target is also a CNAME
cnameRecords := p.cache.GetRecords(target, targetZone, dns.TypeCNAME)
if len(cnameRecords) > 0 {
clog.Debugf("CNAME target %s is also a CNAME, following chain", target)
var allRecords []dns.RR
// Add the intermediate CNAME records to the response
allRecords = append(allRecords, cnameRecords...)
// Recursively resolve each CNAME
for _, cnameRR := range cnameRecords {
if cname, ok := cnameRR.(*dns.CNAME); ok {
recursiveRecords := p.resolveCNAMETarget(cname.Target, qtype, maxHops-1)
allRecords = append(allRecords, recursiveRecords...)
}
}
return allRecords