Skip to content

Commit 303a1e6

Browse files
committed
refact: use Set structs instead of map[]struct{}
1 parent a770f18 commit 303a1e6

10 files changed

Lines changed: 53 additions & 59 deletions

File tree

controller/metrics.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package controller
1818

1919
import (
2020
"github.com/prometheus/client_golang/prometheus"
21+
"k8s.io/apimachinery/pkg/util/sets"
2122

2223
"sigs.k8s.io/external-dns/endpoint"
2324
"sigs.k8s.io/external-dns/pkg/metrics"
@@ -151,14 +152,14 @@ type dnsKey struct {
151152
func countMatchingAddressRecords(endpoints []*endpoint.Endpoint, registryRecords []*endpoint.Endpoint, metric metrics.GaugeVecMetric) {
152153
metric.Gauge.Reset()
153154

154-
registry := make(map[dnsKey]struct{}, len(registryRecords))
155+
registry := make(sets.Set[dnsKey], len(registryRecords))
155156
for _, r := range registryRecords {
156-
registry[dnsKey{r.DNSName, r.RecordType}] = struct{}{}
157+
registry.Insert(dnsKey{r.DNSName, r.RecordType})
157158
}
158159

159160
counts := make(map[string]float64)
160161
for _, ep := range endpoints {
161-
if _, found := registry[dnsKey{ep.DNSName, ep.RecordType}]; found {
162+
if registry.Has(dnsKey{ep.DNSName, ep.RecordType}) {
162163
counts[ep.RecordType]++
163164
}
164165
}

endpoint/endpoint.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import (
2727

2828
"github.com/miekg/dns"
2929
log "github.com/sirupsen/logrus"
30+
"k8s.io/apimachinery/pkg/util/sets"
3031
"k8s.io/utils/set"
3132

3233
"sigs.k8s.io/external-dns/pkg/events"
@@ -508,15 +509,15 @@ func FilterEndpointsByOwnerID(ownerID string, eps []*Endpoint) []*Endpoint {
508509
// This function doesn't contemplate the Targets of an Endpoint
509510
// as part of the primary Key
510511
func RemoveDuplicates(endpoints []*Endpoint) []*Endpoint {
511-
visited := make(map[EndpointKey]struct{})
512+
visited := make(sets.Set[EndpointKey], len(endpoints))
512513
result := []*Endpoint{}
513514

514515
for _, ep := range endpoints {
515516
key := ep.Key()
516517

517-
if _, found := visited[key]; !found {
518+
if !visited.Has(key) {
518519
result = append(result, ep)
519-
visited[key] = struct{}{}
520+
visited.Insert(key)
520521
} else {
521522
log.Debugf(`Skipping duplicated endpoint: %v`, ep)
522523
}

provider/awssd/aws_sd.go

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,13 @@ import (
2828
sd "github.com/aws/aws-sdk-go-v2/service/servicediscovery"
2929
sdtypes "github.com/aws/aws-sdk-go-v2/service/servicediscovery/types"
3030
log "github.com/sirupsen/logrus"
31-
32-
"sigs.k8s.io/external-dns/pkg/apis/externaldns"
33-
extdnsaws "sigs.k8s.io/external-dns/provider/aws"
31+
"k8s.io/apimachinery/pkg/util/sets"
3432

3533
"sigs.k8s.io/external-dns/endpoint"
34+
"sigs.k8s.io/external-dns/pkg/apis/externaldns"
3635
"sigs.k8s.io/external-dns/plan"
3736
"sigs.k8s.io/external-dns/provider"
37+
extdnsaws "sigs.k8s.io/external-dns/provider/aws"
3838
)
3939

4040
const (
@@ -276,15 +276,12 @@ func (p *AWSSDProvider) updatesToCreates(changes *plan.Changes) ([]*endpoint.End
276276
current := updateNewMap[old.DNSName]
277277

278278
if !old.Targets.Same(current.Targets) {
279-
currentTargetsMap := make(map[string]struct{}, len(current.Targets))
280-
for _, newTarget := range current.Targets {
281-
currentTargetsMap[newTarget] = struct{}{}
282-
}
279+
currentTargetsSet := sets.New(current.Targets...)
283280

284281
// If targets changed, only deregister removed targets (i.e. in `UpdateOld` but not in `UpdateNew`)
285282
targetsToRemove := make(endpoint.Targets, 0)
286283
for _, oldTarget := range old.Targets {
287-
if _, found := currentTargetsMap[oldTarget]; !found {
284+
if !currentTargetsSet.Has(oldTarget) {
288285
targetsToRemove = append(targetsToRemove, oldTarget)
289286
}
290287
}

provider/provider.go

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ import (
2323
"net"
2424
"strings"
2525

26+
"k8s.io/apimachinery/pkg/util/sets"
27+
2628
"sigs.k8s.io/external-dns/endpoint"
2729
"sigs.k8s.io/external-dns/plan"
2830
)
@@ -95,18 +97,14 @@ func EnsureTrailingDot(hostname string) string {
9597
// added, removed, or left untouched for "current" to be transformed to "desired"
9698
func Difference(current, desired []string) ([]string, []string, []string) {
9799
add, remove, leave := []string{}, []string{}, []string{}
98-
index := make(map[string]struct{}, len(current))
99-
for _, x := range current {
100-
index[x] = struct{}{}
101-
}
100+
index := sets.New(current...)
102101
for _, x := range desired {
103-
if _, found := index[x]; found {
102+
if index.Has(x) {
104103
leave = append(leave, x)
105-
delete(index, x)
106104
} else {
107105
add = append(add, x)
108-
delete(index, x)
109106
}
107+
index.Delete(x)
110108
}
111109
for x := range index {
112110
remove = append(remove, x)

registry/txt/registry.go

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,23 +18,21 @@ package txt
1818

1919
import (
2020
"context"
21+
b64 "encoding/base64"
2122
"errors"
2223
"maps"
23-
2424
"strings"
2525
"time"
2626

27-
b64 "encoding/base64"
28-
2927
log "github.com/sirupsen/logrus"
30-
31-
"sigs.k8s.io/external-dns/pkg/apis/externaldns"
32-
"sigs.k8s.io/external-dns/registry"
33-
"sigs.k8s.io/external-dns/registry/mapper"
28+
"k8s.io/apimachinery/pkg/util/sets"
3429

3530
"sigs.k8s.io/external-dns/endpoint"
31+
"sigs.k8s.io/external-dns/pkg/apis/externaldns"
3632
"sigs.k8s.io/external-dns/plan"
3733
"sigs.k8s.io/external-dns/provider"
34+
"sigs.k8s.io/external-dns/registry"
35+
"sigs.k8s.io/external-dns/registry/mapper"
3836
)
3937

4038
const (
@@ -76,7 +74,7 @@ type TXTRegistry struct {
7674
// It relies on the fact that Records() is always called **before** ApplyChanges()
7775
// within a single reconciliation cycle.
7876
type existingTXTs struct {
79-
entries map[recordKey]struct{}
77+
entries sets.Set[recordKey]
8078
}
8179

8280
type recordKey struct {
@@ -86,7 +84,7 @@ type recordKey struct {
8684

8785
func newExistingTXTs() *existingTXTs {
8886
return &existingTXTs{
89-
entries: make(map[recordKey]struct{}),
87+
entries: make(sets.Set[recordKey]),
9088
}
9189
}
9290

@@ -95,7 +93,7 @@ func (im *existingTXTs) add(r *endpoint.Endpoint) {
9593
dnsName: r.DNSName,
9694
setIdentifier: r.SetIdentifier,
9795
}
98-
im.entries[key] = struct{}{}
96+
im.entries.Insert(key)
9997
}
10098

10199
// isAbsent returns true when there is no entry for the given name in the store.
@@ -105,14 +103,13 @@ func (im *existingTXTs) isAbsent(ep *endpoint.Endpoint) bool {
105103
dnsName: ep.DNSName,
106104
setIdentifier: ep.SetIdentifier,
107105
}
108-
_, ok := im.entries[key]
109-
return !ok
106+
return !im.entries.Has(key)
110107
}
111108

112109
func (im *existingTXTs) reset() {
113110
// Reset the existing TXT records for the next reconciliation loop.
114111
// This is necessary because the existing TXT records are only relevant for the current reconciliation cycle.
115-
im.entries = make(map[recordKey]struct{})
112+
im.entries = make(sets.Set[recordKey])
116113
}
117114

118115
// New creates a TXTRegistry from the given configuration.
@@ -203,7 +200,7 @@ func (im *TXTRegistry) Records(ctx context.Context) ([]*endpoint.Endpoint, error
203200
endpoints := []*endpoint.Endpoint{}
204201

205202
labelMap := map[endpoint.EndpointKey]endpoint.Labels{}
206-
txtRecordsMap := map[string]struct{}{}
203+
txtRecordsSet := make(sets.Set[string], len(records))
207204

208205
for _, record := range records {
209206
if record.RecordType != endpoint.RecordTypeTXT {
@@ -232,7 +229,7 @@ func (im *TXTRegistry) Records(ctx context.Context) ([]*endpoint.Endpoint, error
232229
SetIdentifier: record.SetIdentifier,
233230
}
234231
labelMap[key] = labels
235-
txtRecordsMap[record.DNSName] = struct{}{}
232+
txtRecordsSet.Insert(record.DNSName)
236233
im.existingTXTs.add(record)
237234
}
238235

@@ -274,12 +271,12 @@ func (im *TXTRegistry) Records(ctx context.Context) ([]*endpoint.Endpoint, error
274271
// TODO: remove this migration logic in some future release
275272
// Handle the migration of TXT records created before the new format (introduced in v0.12.0).
276273
// The migration is done for the TXT records owned by this instance only.
277-
if len(txtRecordsMap) > 0 && ep.Labels[endpoint.OwnerLabelKey] == im.ownerID {
274+
if len(txtRecordsSet) > 0 && ep.Labels[endpoint.OwnerLabelKey] == im.ownerID {
278275
if plan.IsManagedRecord(ep.RecordType, im.managedRecordTypes, im.excludeRecordTypes) {
279276
// Get desired TXT records and detect the missing ones
280277
desiredTXTs := im.generateTXTRecord(ep)
281278
for _, desiredTXT := range desiredTXTs {
282-
if _, exists := txtRecordsMap[desiredTXT.DNSName]; !exists {
279+
if !txtRecordsSet.Has(desiredTXT.DNSName) {
283280
ep.WithProviderSpecific(providerSpecificForceUpdate, "true")
284281
}
285282
}

source/service.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import (
2929
v1 "k8s.io/api/core/v1"
3030
discoveryv1 "k8s.io/api/discovery/v1"
3131
"k8s.io/apimachinery/pkg/labels"
32+
"k8s.io/apimachinery/pkg/util/sets"
3233
kubeinformers "k8s.io/client-go/informers"
3334
coreinformers "k8s.io/client-go/informers/core/v1"
3435
discoveryinformers "k8s.io/client-go/informers/discovery/v1"
@@ -455,13 +456,13 @@ func buildHeadlessEndpoints(svc *v1.Service, targetsByHeadlessDomainAndType map[
455456
for _, headlessKey := range headlessKeys {
456457
allTargets := targetsByHeadlessDomainAndType[headlessKey]
457458
targets := []string{}
458-
deduppedTargets := map[string]struct{}{}
459+
deduppedTargets := make(sets.Set[string], len(allTargets))
459460
for _, target := range allTargets {
460-
if _, ok := deduppedTargets[target]; ok {
461+
if deduppedTargets.Has(target) {
461462
log.Debugf("Removing duplicate target %s", target)
462463
continue
463464
}
464-
deduppedTargets[target] = struct{}{}
465+
deduppedTargets.Insert(target)
465466
targets = append(targets, target)
466467
}
467468
var ep *endpoint.Endpoint

source/template/engine.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,15 @@ package template
1919
import (
2020
"bytes"
2121
"fmt"
22-
"maps"
2322
"reflect"
24-
"slices"
2523
"strings"
2624
"text/template"
2725

2826
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2927
"k8s.io/apimachinery/pkg/runtime"
3028
"k8s.io/apimachinery/pkg/runtime/schema"
3129
"k8s.io/client-go/kubernetes/scheme"
30+
"k8s.io/utils/set"
3231

3332
"sigs.k8s.io/external-dns/endpoint"
3433
)
@@ -175,13 +174,13 @@ func execTemplate(tmpl *template.Template, obj kubeObject) ([]string, error) {
175174
return nil, fmt.Errorf("failed to apply template on %s %s/%s: %w", kind, obj.GetNamespace(), obj.GetName(), err)
176175
}
177176
hosts := strings.Split(buf.String(), ",")
178-
hostnames := make(map[string]struct{}, len(hosts))
177+
hostnames := make(set.Set[string], len(hosts))
179178
for _, name := range hosts {
180179
name = strings.TrimSpace(name)
181180
name = strings.TrimSuffix(name, ".")
182181
if name != "" {
183-
hostnames[name] = struct{}{}
182+
hostnames.Insert(name)
184183
}
185184
}
186-
return slices.Sorted(maps.Keys(hostnames)), nil
185+
return hostnames.SortedList(), nil
187186
}

source/template/engine_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -315,7 +315,7 @@ func TestExecFQDN(t *testing.T) {
315315
Name: "test",
316316
},
317317
},
318-
want: nil,
318+
want: []string{},
319319
},
320320
{
321321
name: "ignore trailing comma output",

source/unstructured.go

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import (
3434
"k8s.io/client-go/dynamic/dynamicinformer"
3535
kubeinformers "k8s.io/client-go/informers"
3636
"k8s.io/client-go/kubernetes"
37+
"k8s.io/utils/set"
3738

3839
"sigs.k8s.io/external-dns/endpoint"
3940
"sigs.k8s.io/external-dns/pkg/events"
@@ -353,20 +354,17 @@ func EndpointsForHostsAndTargets(hostnames, targets []string) []*endpoint.Endpoi
353354
}
354355

355356
// Deduplicate hostnames
356-
hostSet := make(map[string]struct{}, len(hostnames))
357-
for _, h := range hostnames {
358-
hostSet[h] = struct{}{}
359-
}
360-
sortedHosts := slices.Sorted(maps.Keys(hostSet))
357+
sortedHosts := set.New(hostnames...).SortedList()
361358

362359
// Group and deduplicate targets by record type
363-
targetsByType := make(map[string]map[string]struct{})
360+
targetsByType := make(map[string]set.Set[string])
364361
for _, target := range targets {
365362
recordType := endpoint.SuitableType(target)
366363
if targetsByType[recordType] == nil {
367-
targetsByType[recordType] = make(map[string]struct{})
364+
targetsByType[recordType] = set.New(target)
365+
} else {
366+
targetsByType[recordType].Insert(target)
368367
}
369-
targetsByType[recordType][target] = struct{}{}
370368
}
371369

372370
// Resolve to sorted slices once

source/wrappers/dedupsource.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"strings"
2222

2323
log "github.com/sirupsen/logrus"
24+
"k8s.io/apimachinery/pkg/util/sets"
2425

2526
"sigs.k8s.io/external-dns/endpoint"
2627
"sigs.k8s.io/external-dns/source"
@@ -40,14 +41,15 @@ func NewDedupSource(source source.Source) source.Source {
4041
func (ms *dedupSource) Endpoints(ctx context.Context) ([]*endpoint.Endpoint, error) {
4142
log.Debug("dedupSource: collecting endpoints and removing duplicates")
4243
resetMetrics()
43-
result := make([]*endpoint.Endpoint, 0)
44-
collected := make(map[string]struct{})
4544

4645
endpoints, err := ms.source.Endpoints(ctx)
4746
if err != nil {
4847
return nil, err
4948
}
5049

50+
result := make([]*endpoint.Endpoint, 0, len(endpoints))
51+
collected := make(sets.Set[string], len(endpoints))
52+
5153
for _, ep := range endpoints {
5254
if ep == nil {
5355
continue
@@ -66,13 +68,13 @@ func (ms *dedupSource) Endpoints(ctx context.Context) ([]*endpoint.Endpoint, err
6668

6769
identifier := strings.Join([]string{ep.RecordType, ep.DNSName, ep.SetIdentifier, ep.Targets.String()}, "/")
6870

69-
if _, ok := collected[identifier]; ok {
71+
if collected.Has(identifier) {
7072
log.Debugf("Removing duplicate endpoint %s", ep)
7173
deduplicatedEndpoints.AddWithLabels(1, ep.RecordType, endpointSource(ep))
7274
continue
7375
}
7476

75-
collected[identifier] = struct{}{}
77+
collected.Insert(identifier)
7678
result = append(result, ep)
7779
}
7880

0 commit comments

Comments
 (0)