This repository was archived by the owner on Jun 5, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcoredns.go
More file actions
535 lines (473 loc) · 14.6 KB
/
Copy pathcoredns.go
File metadata and controls
535 lines (473 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
/*
Copyright 2024 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/rand"
"net"
"os"
"strings"
"time"
log "github.com/sirupsen/logrus"
etcdcv3 "go.etcd.io/etcd/client/v3"
"sigs.k8s.io/external-dns/pkg/tlsutils"
"sigs.k8s.io/external-dns/endpoint"
"sigs.k8s.io/external-dns/plan"
"sigs.k8s.io/external-dns/provider"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
const (
priority = 10 // default priority when nothing is set
etcdTimeout = 5 * time.Second
randomPrefixLabel = "prefix"
providerSpecificGroup = "webhook/coredns-group"
)
type CoreDNSConfig struct {
coreDNSPrefix string
domainFilter *endpoint.DomainFilter
}
// coreDNSClient is an interface to work with CoreDNS service records in etcd
type coreDNSClient interface {
GetServices(ctx context.Context, prefix string) ([]*Service, error)
SaveService(ctx context.Context, value *Service) error
DeleteService(ctx context.Context, key string) error
}
type coreDNSProvider struct {
provider.BaseProvider
client coreDNSClient
dryRun bool
CoreDNSConfig
}
// Service represents CoreDNS etcd record
type Service struct {
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
Priority int `json:"priority,omitempty"`
Weight int `json:"weight,omitempty"`
Text string `json:"text,omitempty"`
Mail bool `json:"mail,omitempty"` // Be an MX record. Priority becomes Preference.
TTL uint32 `json:"ttl,omitempty"`
// When a SRV record with a "Host: IP-address" is added, we synthesize
// a srv.Target domain name. Normally we convert the full Key where
// the record lives to a DNS name and use this as the srv.Target. When
// TargetStrip > 0 we strip the left most TargetStrip labels from the
// DNS name.
TargetStrip int `json:"targetstrip,omitempty"`
// Group is used to group (or *not* to group) different services
// together. Services with an identical Group are returned in the same
// answer.
Group string `json:"group,omitempty"`
// Etcd key where we found this service and ignored from json un-/marshaling
Key string `json:"-"`
// ManagedBy is used to prevent service to be added by different external-dns (only used by external-dns)
ManagedBy string `json:"managedby,omitempty"`
}
type etcdClient struct {
client *etcdcv3.Client
managedBy string
ignoreEmptyManagedBy bool
}
var _ coreDNSClient = etcdClient{}
// GetServices return all Service records stored in etcd stored anywhere under the given key (recursively)
func (c etcdClient) GetServices(ctx context.Context, prefix string) ([]*Service, error) {
ctx, cancel := context.WithTimeout(ctx, etcdTimeout)
defer cancel()
path := prefix
r, err := c.client.Get(ctx, path, etcdcv3.WithPrefix())
if err != nil {
return nil, err
}
var svcs []*Service
bx := make(map[Service]bool)
for _, n := range r.Kvs {
svc := new(Service)
if err := json.Unmarshal(n.Value, svc); err != nil {
return nil, fmt.Errorf("%s: %w", n.Key, err)
}
b := Service{
Host: svc.Host,
Port: svc.Port,
Priority: svc.Priority,
Weight: svc.Weight,
Text: svc.Text,
Key: string(n.Key),
ManagedBy: svc.ManagedBy,
}
if _, ok := bx[b]; ok {
// skip the service if already added to service list.
// the same service might be found in multiple etcd nodes.
continue
}
if c.managedBy != "" {
if c.ignoreEmptyManagedBy && b.ManagedBy != c.managedBy {
continue
} else if !c.ignoreEmptyManagedBy && b.ManagedBy != "" && b.ManagedBy != c.managedBy {
continue
}
}
bx[b] = true
svc.Key = string(n.Key)
if svc.Priority == 0 {
svc.Priority = priority
}
svcs = append(svcs, svc)
}
return svcs, nil
}
// SaveService persists service data into etcd
func (c etcdClient) SaveService(ctx context.Context, service *Service) error {
ctx, cancel := context.WithTimeout(ctx, etcdTimeout)
defer cancel()
if c.managedBy != "" {
service.ManagedBy = c.managedBy
}
if ownedBy, err := c.IsOwnedBy(ctx, service.Key); err != nil {
return err
} else if !ownedBy {
return fmt.Errorf("key %q is not owned by this service", service.Key)
}
value, err := json.Marshal(&service)
if err != nil {
return err
}
_, err = c.client.Put(ctx, service.Key, string(value))
if err != nil {
return err
}
return nil
}
func (c etcdClient) IsOwnedBy(ctx context.Context, key string) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, etcdTimeout)
defer cancel()
if c.managedBy == "" {
return true, nil
}
r, err := c.client.Get(ctx, key)
if err != nil {
return false, err
}
if r == nil {
return true, nil
} else if len(r.Kvs) > 1 {
return false, fmt.Errorf("found multiple keys with the same key this service")
} else if len(r.Kvs) == 0 {
return true, nil
}
for _, n := range r.Kvs {
svc := new(Service)
if err := json.Unmarshal(n.Value, svc); err != nil {
return false, fmt.Errorf("%s: %w", n.Key, err)
}
if !c.ignoreEmptyManagedBy && svc.ManagedBy == "" {
return true, nil
}
if svc.ManagedBy == c.managedBy {
return true, nil
}
}
return false, nil
}
// DeleteService deletes service record from etcd
func (c etcdClient) DeleteService(ctx context.Context, key string) error {
ctx, cancel := context.WithTimeout(ctx, etcdTimeout)
defer cancel()
if owned, err := c.IsOwnedBy(ctx, key); err != nil {
return err
} else if !owned {
return fmt.Errorf("key %q is not owned by this service", key)
}
_, err := c.client.Delete(ctx, key, etcdcv3.WithPrefix())
return err
}
// builds etcd client config depending on connection scheme and TLS parameters
func getETCDConfig() (*etcdcv3.Config, error) {
etcdURLsStr := os.Getenv("ETCD_URLS")
if etcdURLsStr == "" {
etcdURLsStr = "http://localhost:2379"
}
etcdURLs := strings.Split(etcdURLsStr, ",")
firstURL := strings.ToLower(etcdURLs[0])
etcdUsername := os.Getenv("ETCD_USERNAME")
etcdPassword := os.Getenv("ETCD_PASSWORD")
if strings.HasPrefix(firstURL, "http://") {
return &etcdcv3.Config{Endpoints: etcdURLs, Username: etcdUsername, Password: etcdPassword}, nil
} else if strings.HasPrefix(firstURL, "https://") {
tlsConfig, err := tlsutils.CreateTLSConfig("ETCD")
if err != nil {
return nil, err
}
log.Debug("using TLS for etcd")
return &etcdcv3.Config{
Endpoints: etcdURLs,
TLS: tlsConfig,
Username: etcdUsername,
Password: etcdPassword,
}, nil
} else {
return nil, errors.New("etcd URLs must start with either http:// or https://")
}
}
// the newETCDClient is an etcd client constructor
func newETCDClient(managedBy string, ignoreEmptyManagedBy bool) (coreDNSClient, error) {
cfg, err := getETCDConfig()
if err != nil {
return nil, err
}
c, err := etcdcv3.New(*cfg)
if err != nil {
return nil, err
}
return etcdClient{c, managedBy, ignoreEmptyManagedBy}, nil
}
// NewCoreDNSProvider is a CoreDNS provider constructor
func NewCoreDNSProvider(config CoreDNSConfig, managedBy string, ignoreEmptyManagedBy, dryRun bool) (provider.Provider, error) {
client, err := newETCDClient(managedBy, ignoreEmptyManagedBy)
if err != nil {
return nil, err
}
return coreDNSProvider{
client: client,
dryRun: dryRun,
CoreDNSConfig: config,
}, nil
}
// findEp takes an Endpoint slice and looks for an element in it. If found it will
// return Endpoint, otherwise it will return nil and a bool of false.
func findEp(slice []*endpoint.Endpoint, dnsName string) (*endpoint.Endpoint, bool) {
for _, item := range slice {
if item.DNSName == dnsName {
return item, true
}
}
return nil, false
}
// findLabelInTargets takes an ep.Targets string slice and looks for an element in it. If found it will
// return its string value, otherwise it will return empty string and a bool of false.
func findLabelInTargets(targets []string, label string) (string, bool) {
for _, target := range targets {
if target == label {
return target, true
}
}
return "", false
}
// Records returns all DNS records found in CoreDNS etcd backend. Depending on the record fields
// it may be mapped to one or two records of type A, CNAME, TXT, A+TXT, CNAME+TXT
func (p coreDNSProvider) Records(ctx context.Context) ([]*endpoint.Endpoint, error) {
var result []*endpoint.Endpoint
services, err := p.client.GetServices(ctx, p.coreDNSPrefix)
if err != nil {
return nil, err
}
for _, service := range services {
domains := strings.Split(strings.TrimPrefix(service.Key, p.coreDNSPrefix), "/")
reverse(domains)
dnsName := strings.Join(domains[service.TargetStrip:], ".")
if !p.domainFilter.Match(dnsName) {
continue
}
log.Debugf("Getting service (%v) with service host (%s)", service, service.Host)
prefix := strings.Join(domains[:service.TargetStrip], ".")
if service.Host != "" {
ep, found := findEp(result, dnsName)
if found {
ep.Targets = append(ep.Targets, service.Host)
log.Debugf("Extending ep (%s) with new service host (%s)", ep, service.Host)
} else {
ep = endpoint.NewEndpointWithTTL(
dnsName,
guessRecordType(service.Host),
endpoint.TTL(service.TTL),
service.Host,
)
if service.Group != "" {
ep.WithProviderSpecific(providerSpecificGroup, service.Group)
}
log.Debugf("Creating new ep (%s) with new service host (%s)", ep, service.Host)
}
ep.Labels["originalText"] = service.Text
ep.Labels[randomPrefixLabel] = prefix
ep.Labels[service.Host] = prefix
result = append(result, ep)
}
if service.Text != "" {
ep := endpoint.NewEndpoint(
dnsName,
endpoint.RecordTypeTXT,
service.Text,
)
ep.Labels[randomPrefixLabel] = prefix
result = append(result, ep)
}
}
return result, nil
}
func (p coreDNSProvider) ApplyChanges(ctx context.Context, changes *plan.Changes) error {
grouped := p.groupEndpoints(changes)
for dnsName, group := range grouped {
if !p.domainFilter.Match(dnsName) {
log.Debugf("Skipping record %q due to domain filter", dnsName)
continue
}
if err := p.applyGroup(ctx, dnsName, group); err != nil {
return err
}
}
return p.deleteEndpoints(ctx, changes.Delete)
}
func (p coreDNSProvider) groupEndpoints(changes *plan.Changes) map[string][]*endpoint.Endpoint {
grouped := make(map[string][]*endpoint.Endpoint)
for _, ep := range changes.Create {
grouped[ep.DNSName] = append(grouped[ep.DNSName], ep)
}
for i, ep := range changes.UpdateNew {
log.Debugf("Updating labels (%s) with old labels (%s)", ep.Labels, changes.UpdateOld[i].Labels)
ep.Labels = changes.UpdateOld[i].Labels
grouped[ep.DNSName] = append(grouped[ep.DNSName], ep)
}
return grouped
}
func (p coreDNSProvider) applyGroup(ctx context.Context, dnsName string, group []*endpoint.Endpoint) error {
var services []*Service
for _, ep := range group {
if ep.RecordType != endpoint.RecordTypeTXT {
srvs, err := p.createServicesForEndpoint(ctx, dnsName, ep)
if err != nil {
return err
}
services = append(services, srvs...)
}
}
services = p.updateTXTRecords(dnsName, group, services)
for _, service := range services {
log.Infof("Add/set key %s to Host=%s, Text=%s, TTL=%d", service.Key, service.Host, service.Text, service.TTL)
if p.dryRun {
continue
}
if err := p.client.SaveService(ctx, service); err != nil {
return err
}
}
return nil
}
func (p coreDNSProvider) createServicesForEndpoint(ctx context.Context, dnsName string, ep *endpoint.Endpoint) ([]*Service, error) {
var services []*Service
for _, target := range ep.Targets {
prefix := ep.Labels[target]
if prefix == "" {
prefix = fmt.Sprintf("%08x", rand.Int31())
log.Infof("Generating new prefix: (%s)", prefix)
}
group := ""
if prop, ok := ep.GetProviderSpecificProperty(providerSpecificGroup); ok {
group = prop
}
service := Service{
Host: target,
Text: ep.Labels["originalText"],
Key: p.etcdKeyFor(prefix + "." + dnsName),
TargetStrip: strings.Count(prefix, ".") + 1,
TTL: uint32(ep.RecordTTL),
Group: group,
}
services = append(services, &service)
ep.Labels[target] = prefix
}
// Clean outdated labels
for label, labelPrefix := range ep.Labels {
if shouldSkipLabel(label) {
continue
}
if _, ok := findLabelInTargets(ep.Targets, label); !ok {
key := p.etcdKeyFor(labelPrefix + "." + dnsName)
log.Infof("Delete key %s", key)
if p.dryRun {
continue
}
if err := p.client.DeleteService(ctx, key); err != nil {
return nil, err
}
}
}
return services, nil
}
func shouldSkipLabel(label string) bool {
skip := []string{"originalText", "prefix", "resource"}
_, ok := findLabelInTargets(skip, label)
return ok
}
// updateTXTRecords updates the TXT records in the provided services slice based on the given group of endpoints.
func (p coreDNSProvider) updateTXTRecords(dnsName string, group []*endpoint.Endpoint, services []*Service) []*Service {
index := 0
for _, ep := range group {
if ep.RecordType != endpoint.RecordTypeTXT {
continue
}
if index >= len(services) {
prefix := ep.Labels[randomPrefixLabel]
if prefix == "" {
prefix = fmt.Sprintf("%08x", rand.Int31())
}
services = append(services, &Service{
Key: p.etcdKeyFor(prefix + "." + dnsName),
TargetStrip: strings.Count(prefix, ".") + 1,
TTL: uint32(ep.RecordTTL),
})
}
services[index].Text = ep.Targets[0]
index++
}
for i := index; index > 0 && i < len(services); i++ {
services[i].Text = ""
}
return services
}
func (p coreDNSProvider) deleteEndpoints(ctx context.Context, endpoints []*endpoint.Endpoint) error {
for _, ep := range endpoints {
dnsName := ep.DNSName
if ep.Labels[randomPrefixLabel] != "" {
dnsName = ep.Labels[randomPrefixLabel] + "." + dnsName
}
key := p.etcdKeyFor(dnsName)
log.Infof("Delete key %s", key)
if p.dryRun {
continue
}
if err := p.client.DeleteService(ctx, key); err != nil {
return err
}
}
return nil
}
func (p coreDNSProvider) etcdKeyFor(dnsName string) string {
domains := strings.Split(dnsName, ".")
reverse(domains)
return p.coreDNSPrefix + strings.Join(domains, "/")
}
func guessRecordType(target string) string {
if net.ParseIP(target) != nil {
return endpoint.RecordTypeA
}
return endpoint.RecordTypeCNAME
}
func reverse(slice []string) {
for i := range len(slice) / 2 {
j := len(slice) - i - 1
slice[i], slice[j] = slice[j], slice[i]
}
}