/
helpers.go
93 lines (79 loc) · 2.69 KB
/
helpers.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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package fqdn
import (
"net/netip"
"regexp"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/sets"
"github.com/cilium/cilium/pkg/fqdn/dns"
"github.com/cilium/cilium/pkg/fqdn/matchpattern"
"github.com/cilium/cilium/pkg/fqdn/re"
"github.com/cilium/cilium/pkg/policy/api"
)
// mapSelectorsToIPsLocked iterates through a set of FQDNSelectors and evalutes
// whether they match the DNS Names in the cache. If so, the set of IPs which
// the cache maintains as mapping to each DNS Name are mapped to the matching
// FQDNSelector.
// Returns the mapping of FQDNSelector to all IPs selected by that selector.
func (n *NameManager) mapSelectorsToIPsLocked(fqdnSelectors sets.Set[api.FQDNSelector]) (selectorIPMapping map[api.FQDNSelector][]netip.Addr) {
selectorIPMapping = make(map[api.FQDNSelector][]netip.Addr)
log.WithField("fqdnSelectors", fqdnSelectors).Debug("mapSelectorsToIPs")
// Map each FQDNSelector to set of CIDRs
for ToFQDN := range fqdnSelectors {
var ipsSelected []netip.Addr
dedup := false
// lookup matching DNS names
if len(ToFQDN.MatchName) > 0 {
dnsName := prepareMatchName(ToFQDN.MatchName)
lookupIPs := n.cache.Lookup(dnsName)
log.WithFields(logrus.Fields{
"DNSName": dnsName,
"IPs": lookupIPs,
"matchName": ToFQDN.MatchName,
}).Debug("Emitting matching DNS Name -> IPs for FQDNSelector")
ipsSelected = lookupIPs
}
if len(ToFQDN.MatchPattern) > 0 {
// lookup matching DNS names
dnsPattern := matchpattern.Sanitize(ToFQDN.MatchPattern)
patternREStr := matchpattern.ToAnchoredRegexp(dnsPattern)
var (
err error
patternRE *regexp.Regexp
)
if patternRE, err = re.CompileRegex(patternREStr); err != nil {
log.WithError(err).Error("Error compiling matchPattern")
}
lookupIPs := n.cache.LookupByRegexp(patternRE)
for name, ips := range lookupIPs {
if len(ips) > 0 {
if log.Logger.IsLevelEnabled(logrus.DebugLevel) {
log.WithFields(logrus.Fields{
"DNSName": name,
"IPs": ips,
"matchPattern": ToFQDN.MatchPattern,
}).Debug("Emitting matching DNS Name -> IPs for FQDNSelector")
}
if ipsSelected == nil {
ipsSelected = ips
} else {
ipsSelected = append(ipsSelected, ips...)
dedup = true
}
}
}
}
if dedup {
s := make(sets.Set[netip.Addr], len(ipsSelected))
s.Insert(ipsSelected...)
ipsSelected = s.UnsortedList()
}
selectorIPMapping[ToFQDN] = ipsSelected
}
return selectorIPMapping
}
// prepareMatchName ensures a ToFQDNs.matchName field is used consistently.
func prepareMatchName(matchName string) string {
return dns.FQDN(matchName)
}