-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathendpoint.go
More file actions
694 lines (606 loc) · 23.1 KB
/
Copy pathendpoint.go
File metadata and controls
694 lines (606 loc) · 23.1 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
/*
Copyright 2026.
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 adapter
import (
"maps"
"sort"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/external-dns/endpoint"
sreportalv1alpha1 "github.com/golgoth31/sreportal/api/v1alpha1"
v1alpha2 "github.com/golgoth31/sreportal/api/v1alpha2"
"github.com/golgoth31/sreportal/internal/config"
domaindns "github.com/golgoth31/sreportal/internal/domain/dns"
"github.com/golgoth31/sreportal/internal/log"
)
const (
// SourceExternalDNS indicates an FQDN discovered from external-dns sources.
SourceExternalDNS = "external-dns"
// PortalAnnotationKey is the label key used on external-dns endpoints
// to route them to a specific portal.
PortalAnnotationKey = "sreportal.io/portal"
// GroupsAnnotationKey is the label key used on external-dns endpoints
// to assign them to one or more groups (comma-separated). Takes highest
// priority over other grouping rules (labelKey, namespace mapping, default group).
GroupsAnnotationKey = "sreportal.io/groups"
// IgnoreAnnotationKey is the label key used on external-dns endpoints
// to exclude them from DNS discovery. When set to "true", the endpoint
// is silently dropped during group conversion.
IgnoreAnnotationKey = "sreportal.io/ignore"
// ComponentAnnotationKey triggers automatic Component CR creation when
// present on a K8s source resource or DNS CR. The value is the component
// display name.
ComponentAnnotationKey = "sreportal.io/component"
// ComponentGroupAnnotationKey overrides the component group. When absent
// the FQDN group from GroupMappingStrategy is used.
ComponentGroupAnnotationKey = "sreportal.io/component-group"
// ComponentDescriptionAnnotationKey sets the component description.
ComponentDescriptionAnnotationKey = "sreportal.io/component-description"
// ComponentLinkAnnotationKey sets the component external URL.
ComponentLinkAnnotationKey = "sreportal.io/component-link"
// ComponentStatusAnnotationKey sets the initial declared status.
// Defaults to "operational" when absent.
ComponentStatusAnnotationKey = "sreportal.io/component-status"
// ManagedByLabelKey marks auto-created Component CRs so orphan cleanup
// only deletes components that were created by the same controller.
ManagedByLabelKey = "sreportal.io/managed-by"
// ManagedBySourceController is the managed-by value for components
// created by the source reconciliation chain.
ManagedBySourceController = "source-controller"
// ManagedByDNSController is the managed-by value for components
// created by the DNS reconciliation chain.
ManagedByDNSController = "dns-controller"
// annotationValueTrue is the canonical boolean-true value for
// sreportal annotations (e.g. sreportal.io/ignore: "true").
annotationValueTrue = "true"
// defaultGroupServices is the fallback group name applied when no
// GroupMappingConfig is provided.
defaultGroupServices = "Services"
)
// SreportalAnnotations lists the annotation keys that should be propagated
// from K8s resource annotations to endpoint labels.
var SreportalAnnotations = []string{
PortalAnnotationKey,
GroupsAnnotationKey,
IgnoreAnnotationKey,
ComponentAnnotationKey,
ComponentGroupAnnotationKey,
ComponentDescriptionAnnotationKey,
ComponentLinkAnnotationKey,
ComponentStatusAnnotationKey,
}
// ComponentAnnotations holds the component metadata extracted from annotations.
type ComponentAnnotations struct {
DisplayName string
Group string
Description string
Link string
Status string
}
// ResolveComponentSpec extracts component metadata from endpoint labels.
// Returns nil when the sreportal.io/component annotation is absent.
func ResolveComponentSpec(ep *endpoint.Endpoint) *ComponentAnnotations {
if ep == nil {
return nil
}
displayName, ok := ep.Labels[ComponentAnnotationKey]
if !ok || displayName == "" {
return nil
}
return &ComponentAnnotations{
DisplayName: displayName,
Group: ep.Labels[ComponentGroupAnnotationKey],
Description: ep.Labels[ComponentDescriptionAnnotationKey],
Link: ep.Labels[ComponentLinkAnnotationKey],
Status: ep.Labels[ComponentStatusAnnotationKey],
}
}
// ComponentAnnotationsFromMap extracts component metadata from a raw annotation
// map (e.g. from a DNS CR). Returns nil when sreportal.io/component is absent.
func ComponentAnnotationsFromMap(annotations map[string]string) *ComponentAnnotations {
displayName := annotations[ComponentAnnotationKey]
if displayName == "" {
return nil
}
return &ComponentAnnotations{
DisplayName: displayName,
Group: annotations[ComponentGroupAnnotationKey],
Description: annotations[ComponentDescriptionAnnotationKey],
Link: annotations[ComponentLinkAnnotationKey],
Status: annotations[ComponentStatusAnnotationKey],
}
}
// EnrichEndpointLabels copies sreportal annotations from K8s resource annotations
// to the endpoint's labels. Existing endpoint labels are not overwritten.
func EnrichEndpointLabels(ep *endpoint.Endpoint, annotations map[string]string) {
if ep == nil || len(annotations) == 0 {
return
}
if ep.Labels == nil {
ep.Labels = make(map[string]string)
}
for _, key := range SreportalAnnotations {
if val, ok := annotations[key]; ok && val != "" {
if _, exists := ep.Labels[key]; !exists {
ep.Labels[key] = val
}
}
}
}
// ResolvePortal extracts the portal name from an endpoint's labels.
// Returns the portal name or empty string if not annotated.
func ResolvePortal(ep *endpoint.Endpoint) string {
if ep == nil {
return ""
}
if val, ok := ep.Labels[PortalAnnotationKey]; ok && val != "" {
return val
}
return ""
}
// IsIgnored returns true when the endpoint has the sreportal.io/ignore label set to "true".
func IsIgnored(ep *endpoint.Endpoint) bool {
if ep == nil {
return false
}
return ep.Labels[IgnoreAnnotationKey] == annotationValueTrue
}
// IsEndpointStatusIgnored returns true when the EndpointStatus has the sreportal.io/ignore label set to "true".
func IsEndpointStatusIgnored(ep *sreportalv1alpha1.EndpointStatus) bool {
if ep == nil {
return false
}
return ep.Labels[IgnoreAnnotationKey] == annotationValueTrue
}
// strategyFromConfig builds a GroupMappingStrategy from the provided config.
// A nil mapping yields a strategy with the "Services" default group.
func strategyFromConfig(mapping *config.GroupMappingConfig) domaindns.GroupMappingStrategy {
if mapping == nil {
return domaindns.GroupMappingStrategy{DefaultGroup: defaultGroupServices}
}
return domaindns.GroupMappingStrategy{
DefaultGroup: mapping.DefaultGroup,
LabelKey: mapping.LabelKey,
ByNamespace: mapping.ByNamespace,
}
}
// EndpointsToGroups converts external-dns endpoints to DNS CR status groups.
// It groups endpoints based on the provided mapping configuration.
func EndpointsToGroups(endpoints []*endpoint.Endpoint, mapping *config.GroupMappingConfig) []sreportalv1alpha1.FQDNGroupStatus {
strategy := strategyFromConfig(mapping)
// Group endpoints by mapping rules
groups := make(map[string]*sreportalv1alpha1.FQDNGroupStatus)
now := metav1.Now()
for _, ep := range endpoints {
if IsIgnored(ep) {
continue
}
ns := extractNamespace(ep.Labels[endpoint.ResourceLabelKey])
groupNames := strategy.Resolve(ep.Labels, ns)
fqdn := sreportalv1alpha1.FQDNStatus{
FQDN: ep.DNSName,
RecordType: ep.RecordType,
Targets: ep.Targets,
LastSeen: now,
OriginRef: originRefFromLabel(ep.Labels[endpoint.ResourceLabelKey]),
}
for _, groupName := range groupNames {
if _, exists := groups[groupName]; !exists {
groups[groupName] = &sreportalv1alpha1.FQDNGroupStatus{
Name: groupName,
Source: SourceExternalDNS,
FQDNs: []sreportalv1alpha1.FQDNStatus{},
}
}
groups[groupName].FQDNs = append(groups[groupName].FQDNs, fqdn)
}
}
// Convert map to sorted slice
result := make([]sreportalv1alpha1.FQDNGroupStatus, 0, len(groups))
for _, group := range groups {
// Sort FQDNs within each group
sort.Slice(group.FQDNs, func(i, j int) bool {
return group.FQDNs[i].FQDN < group.FQDNs[j].FQDN
})
result = append(result, *group)
}
// Sort groups by name
sort.Slice(result, func(i, j int) bool {
return result[i].Name < result[j].Name
})
return result
}
// extractNamespace extracts the namespace from a resource label.
// The resource label format from external-dns is "kind/namespace/name" (e.g., "service/default/my-svc").
func extractNamespace(resource string) string {
ref, err := domaindns.ParseResourceRef(resource)
if err != nil {
return ""
}
return ref.Namespace()
}
// parseOriginLabel parses the external-dns "resource" label
// (kind/namespace/name). An empty label is expected (the endpoint has no
// originating resource) and returns ok=false silently. A non-empty but
// unparsable label is an anomaly — it would otherwise drop the origin with no
// trace (the FQDN card shows no source) — so it is logged at warn level.
func parseOriginLabel(raw string) (domaindns.ResourceRef, bool) {
if strings.TrimSpace(raw) == "" {
return domaindns.ResourceRef{}, false
}
ref, err := domaindns.ParseResourceRef(raw)
if err != nil || ref.IsZero() {
log.Default().WithName("adapter.endpoint").Warn(
"ignoring malformed external-dns resource label",
"resource", raw, "err", err)
return domaindns.ResourceRef{}, false
}
return ref, true
}
// originRefFromLabel parses an external-dns resource label into an OriginResourceRef.
// Returns nil when the label is absent or malformed (malformed is logged).
func originRefFromLabel(raw string) *sreportalv1alpha1.OriginResourceRef {
ref, ok := parseOriginLabel(raw)
if !ok {
return nil
}
return &sreportalv1alpha1.OriginResourceRef{
Kind: ref.Kind(),
Namespace: ref.Namespace(),
Name: ref.Name(),
}
}
// MergeGroups merges existing groups with new external groups.
// Manual groups (source != external-dns) are preserved, while external groups are replaced.
func MergeGroups(existing, external []sreportalv1alpha1.FQDNGroupStatus) []sreportalv1alpha1.FQDNGroupStatus {
// Start with manual groups from existing
result := make([]sreportalv1alpha1.FQDNGroupStatus, 0, len(existing)+len(external))
for _, g := range existing {
if g.Source != SourceExternalDNS {
result = append(result, g)
}
}
// Add all external groups
result = append(result, external...)
// Sort by name
sort.Slice(result, func(i, j int) bool {
return result[i].Name < result[j].Name
})
return result
}
// ToEndpointStatus converts external-dns endpoints to EndpointStatus slice.
// This is used when storing endpoints in DNSRecord status.
func ToEndpointStatus(endpoints []*endpoint.Endpoint) []sreportalv1alpha1.EndpointStatus {
now := metav1.Now()
result := make([]sreportalv1alpha1.EndpointStatus, 0, len(endpoints))
for _, ep := range endpoints {
status := sreportalv1alpha1.EndpointStatus{
DNSName: ep.DNSName,
RecordType: ep.RecordType,
Targets: ep.Targets,
TTL: int64(ep.RecordTTL),
LastSeen: now,
}
// Copy labels if present
if len(ep.Labels) > 0 {
status.Labels = make(map[string]string, len(ep.Labels))
maps.Copy(status.Labels, ep.Labels)
}
result = append(result, status)
}
// Sort by DNS name for consistent ordering
sort.Slice(result, func(i, j int) bool {
if result[i].DNSName == result[j].DNSName {
return result[i].RecordType < result[j].RecordType
}
return result[i].DNSName < result[j].DNSName
})
return result
}
// fqdnKey uniquely identifies a FQDN within a group for deduplication.
type fqdnKey struct {
groupName string
dnsName string
recordType string
}
// EndpointStatusToGroups converts EndpointStatus slice to FQDNGroupStatus slice.
// This is used when aggregating endpoints from DNSRecord resources into DNS status.
// Duplicate FQDNs (same DNSName + RecordType) within the same group are merged,
// combining their targets.
func EndpointStatusToGroups(endpoints []sreportalv1alpha1.EndpointStatus, mapping *config.GroupMappingConfig) []sreportalv1alpha1.FQDNGroupStatus {
strategy := strategyFromConfig(mapping)
// Group endpoints by mapping rules
groups := make(map[string]*sreportalv1alpha1.FQDNGroupStatus)
// Track seen FQDNs per group to deduplicate and merge targets
seen := make(map[fqdnKey]int) // key → index in group.FQDNs
for _, ep := range endpoints {
if IsEndpointStatusIgnored(&ep) {
continue
}
ns := extractNamespace(ep.Labels[endpoint.ResourceLabelKey])
// Parse once per endpoint (not per group): the label is identical across
// this endpoint's groups, so this avoids re-parsing and, for a malformed
// label, avoids logging once per group.
originRef := originRefFromLabel(ep.Labels[endpoint.ResourceLabelKey])
groupNames := strategy.Resolve(ep.Labels, ns)
for _, groupName := range groupNames {
if _, exists := groups[groupName]; !exists {
groups[groupName] = &sreportalv1alpha1.FQDNGroupStatus{
Name: groupName,
Source: SourceExternalDNS,
FQDNs: []sreportalv1alpha1.FQDNStatus{},
}
}
key := fqdnKey{groupName: groupName, dnsName: ep.DNSName, recordType: ep.RecordType}
if idx, dup := seen[key]; dup {
// Merge targets from duplicate endpoint
existing := &groups[groupName].FQDNs[idx]
existing.Targets = mergeTargets(existing.Targets, ep.Targets)
if ep.LastSeen.After(existing.LastSeen.Time) {
existing.LastSeen = ep.LastSeen
}
} else {
seen[key] = len(groups[groupName].FQDNs)
groups[groupName].FQDNs = append(groups[groupName].FQDNs, sreportalv1alpha1.FQDNStatus{
FQDN: ep.DNSName,
RecordType: ep.RecordType,
Targets: ep.Targets,
SyncStatus: ep.SyncStatus,
LastSeen: ep.LastSeen,
OriginRef: originRef,
})
}
}
}
// Convert map to sorted slice
result := make([]sreportalv1alpha1.FQDNGroupStatus, 0, len(groups))
for _, group := range groups {
// Sort FQDNs within each group
sort.Slice(group.FQDNs, func(i, j int) bool {
return group.FQDNs[i].FQDN < group.FQDNs[j].FQDN
})
result = append(result, *group)
}
// Sort groups by name
sort.Slice(result, func(i, j int) bool {
return result[i].Name < result[j].Name
})
return result
}
// ApplySourcePriority deduplicates endpoints across multiple source types using the
// provided priority ordering. Priority is applied at the FQDN-name level: when the
// same hostname appears in multiple sources, the highest-priority source wins and ALL
// its record types (A, AAAA, CNAME, …) are kept, while ALL records from lower-priority
// sources for that hostname are dropped. This correctly handles the common case where
// two sources discover the same FQDN via different record types (e.g. a Service A record
// vs an Istio Gateway CNAME).
//
// Sources not listed in priority receive the lowest rank and lose to any listed source
// on conflict, but still contribute FQDNs they uniquely own. Intra-source duplicates
// (same source, same FQDN+RecordType) have their targets merged. Tie-breaking between
// sources of equal rank is alphabetical by source type name, making results deterministic.
//
// When priority is empty or nil, all endpoints are returned without deduplication
// (preserving the existing merge-targets behaviour when passed to EndpointStatusToGroups).
func ApplySourcePriority(endpointsBySource map[string][]sreportalv1alpha1.EndpointStatus, priority []string) []sreportalv1alpha1.EndpointStatus {
if len(endpointsBySource) == 0 {
return nil
}
// Without priority, flatten all sources (caller handles deduplication via EndpointStatusToGroups)
if len(priority) == 0 {
total := 0
for _, eps := range endpointsBySource {
total += len(eps)
}
all := make([]sreportalv1alpha1.EndpointStatus, 0, total)
for _, eps := range endpointsBySource {
all = append(all, eps...)
}
return all
}
return selectByPriority(endpointsBySource, priority)
}
// selectByPriority implements two-phase FQDN-name-level deduplication.
//
// Phase 1 – elect the winning source type per FQDN name using priority rank.
// Phase 2 – collect all endpoints from the winning source (preserving every
// record type it published) and merge intra-source duplicates (same FQDN+RecordType).
//
// This ensures that a lower-priority source cannot leak any record type for an FQDN
// that a higher-priority source also discovers, even when the two sources publish
// different record types (e.g. Service A vs Istio Gateway CNAME).
func selectByPriority(endpointsBySource map[string][]sreportalv1alpha1.EndpointStatus, priority []string) []sreportalv1alpha1.EndpointStatus {
// Build rank map: lower index = higher priority (rank 0 beats rank 1).
rankOf := make(map[string]int, len(priority))
for i, src := range priority {
rankOf[src] = i
}
lowestRank := len(priority) // unlisted sources always lose to any listed source
// Sort source types so tie-breaking between equal-rank sources is alphabetical (deterministic).
srcTypes := make([]string, 0, len(endpointsBySource))
for srcType := range endpointsBySource {
srcTypes = append(srcTypes, srcType)
}
sort.Strings(srcTypes)
// Phase 1: elect the winning source type per FQDN name.
type sourceWinner struct {
srcType string
rank int
}
winnerBySrc := make(map[string]sourceWinner) // DNSName → winning source
for _, srcType := range srcTypes {
srcRank, ok := rankOf[srcType]
if !ok {
srcRank = lowestRank
}
for _, ep := range endpointsBySource[srcType] {
existing, exists := winnerBySrc[ep.DNSName]
if !exists || srcRank < existing.rank {
winnerBySrc[ep.DNSName] = sourceWinner{srcType: srcType, rank: srcRank}
}
// equal rank: first-seen (alphabetically) wins — srcTypes is already sorted
}
}
// Phase 2: collect all endpoints from the winning source for each FQDN name.
// Intra-source duplicates (same FQDN+RecordType within the winning source) are merged.
type epKey struct {
dnsName string
recordType string
}
winningEps := make(map[epKey]sreportalv1alpha1.EndpointStatus)
for _, srcType := range srcTypes {
for _, ep := range endpointsBySource[srcType] {
winner, ok := winnerBySrc[ep.DNSName]
if !ok || winner.srcType != srcType {
continue // this source does not own this FQDN name
}
key := epKey{dnsName: ep.DNSName, recordType: ep.RecordType}
if existing, dup := winningEps[key]; dup {
existing.Targets = mergeTargets(existing.Targets, ep.Targets)
winningEps[key] = existing
} else {
winningEps[key] = ep
}
}
}
result := make([]sreportalv1alpha1.EndpointStatus, 0, len(winningEps))
for _, ep := range winningEps {
result = append(result, ep)
}
// Sort for deterministic output.
sort.Slice(result, func(i, j int) bool {
if result[i].DNSName == result[j].DNSName {
return result[i].RecordType < result[j].RecordType
}
return result[i].DNSName < result[j].DNSName
})
return result
}
// strategyFromV2Spec builds a GroupMappingStrategy from a v1alpha2.GroupMappingSpec.
// A nil mapping yields a strategy with the "Services" default group.
func strategyFromV2Spec(mapping *v1alpha2.GroupMappingSpec) domaindns.GroupMappingStrategy {
if mapping == nil {
return domaindns.GroupMappingStrategy{DefaultGroup: defaultGroupServices}
}
return domaindns.GroupMappingStrategy{
DefaultGroup: mapping.DefaultGroup,
LabelKey: mapping.LabelKey,
ByNamespace: mapping.ByNamespace,
}
}
// originRefV2FromLabel parses an external-dns resource label into a v1alpha2.OriginResourceRef.
// Returns nil when the label is absent or malformed.
func originRefV2FromLabel(raw string) *v1alpha2.OriginResourceRef {
ref, ok := parseOriginLabel(raw)
if !ok {
return nil
}
return &v1alpha2.OriginResourceRef{
Kind: ref.Kind(),
Namespace: ref.Namespace(),
Name: ref.Name(),
}
}
// IsEndpointStatusV2Ignored returns true when a v1alpha2.EndpointStatus has the
// sreportal.io/ignore label set to "true".
func IsEndpointStatusV2Ignored(ep *v1alpha2.EndpointStatus) bool {
if ep == nil {
return false
}
return ep.Labels[IgnoreAnnotationKey] == annotationValueTrue
}
// fqdnKeyV2 uniquely identifies an FQDN within a group for v1alpha2 dedup.
type fqdnKeyV2 struct {
groupName string
dnsName string
recordType string
}
// EndpointStatusToGroupsV2 converts a v1alpha2.EndpointStatus slice to v1alpha2.FQDNGroupStatus.
// Semantics identical to EndpointStatusToGroups but uses v1alpha2 types throughout.
// Duplicate FQDNs (same DNSName + RecordType) within the same group are merged,
// combining their targets.
func EndpointStatusToGroupsV2(endpoints []v1alpha2.EndpointStatus, mapping *v1alpha2.GroupMappingSpec) []v1alpha2.FQDNGroupStatus {
strategy := strategyFromV2Spec(mapping)
groups := make(map[string]*v1alpha2.FQDNGroupStatus)
seen := make(map[fqdnKeyV2]int)
for _, ep := range endpoints {
if IsEndpointStatusV2Ignored(&ep) {
continue
}
ns := extractNamespace(ep.Labels[endpoint.ResourceLabelKey])
// Parse once per endpoint (not per group): see EndpointStatusToGroups.
originRef := originRefV2FromLabel(ep.Labels[endpoint.ResourceLabelKey])
groupNames := strategy.Resolve(ep.Labels, ns)
for _, groupName := range groupNames {
if _, exists := groups[groupName]; !exists {
groups[groupName] = &v1alpha2.FQDNGroupStatus{
Name: groupName,
Source: SourceExternalDNS,
FQDNs: []v1alpha2.FQDNStatus{},
}
}
key := fqdnKeyV2{groupName: groupName, dnsName: ep.DNSName, recordType: ep.RecordType}
if idx, dup := seen[key]; dup {
existing := &groups[groupName].FQDNs[idx]
existing.Targets = mergeTargets(existing.Targets, ep.Targets)
if ep.LastSeen.After(existing.LastSeen.Time) {
existing.LastSeen = ep.LastSeen
}
} else {
seen[key] = len(groups[groupName].FQDNs)
groups[groupName].FQDNs = append(groups[groupName].FQDNs, v1alpha2.FQDNStatus{
FQDN: ep.DNSName,
RecordType: ep.RecordType,
Targets: ep.Targets,
SyncStatus: ep.SyncStatus,
LastSeen: ep.LastSeen,
OriginRef: originRef,
})
}
}
}
result := make([]v1alpha2.FQDNGroupStatus, 0, len(groups))
for _, group := range groups {
sort.Slice(group.FQDNs, func(i, j int) bool {
return group.FQDNs[i].FQDN < group.FQDNs[j].FQDN
})
result = append(result, *group)
}
sort.Slice(result, func(i, j int) bool {
return result[i].Name < result[j].Name
})
return result
}
// mergeTargets merges two target slices, deduplicating entries.
// It always returns a new slice and never aliases the caller's backing array.
func mergeTargets(existing, additional []string) []string {
if len(additional) == 0 {
return existing
}
set := make(map[string]struct{}, len(existing)+len(additional))
result := make([]string, 0, len(existing)+len(additional))
for _, t := range existing {
if _, seen := set[t]; !seen {
set[t] = struct{}{}
result = append(result, t)
}
}
for _, t := range additional {
if _, seen := set[t]; !seen {
set[t] = struct{}{}
result = append(result, t)
}
}
sort.Strings(result)
return result
}