-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
addresstype.go
65 lines (59 loc) · 1.69 KB
/
addresstype.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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package addressing
import (
"net"
)
// AddressType represents a type of IP address for a node. They are copied
// from k8s.io/api/core/v1/types.go to avoid pulling in a lot of Kubernetes
// imports into this package.
type AddressType string
const (
NodeHostName AddressType = "Hostname"
NodeExternalIP AddressType = "ExternalIP"
NodeInternalIP AddressType = "InternalIP"
NodeExternalDNS AddressType = "ExternalDNS"
NodeInternalDNS AddressType = "InternalDNS"
NodeCiliumInternalIP AddressType = "CiliumInternalIP"
)
type Address interface {
AddrType() AddressType
ToString() string
}
// ExtractNodeIP returns one of the provided IP addresses available with the following priority:
// - NodeInternalIP
// - NodeExternalIP
// - other IP address type
// An error is returned if ExtractNodeIP fails to get an IP based on the provided address family.
func ExtractNodeIP[T Address](addrs []T, ipv6 bool) net.IP {
var backupIP net.IP
for _, addr := range addrs {
parsed := net.ParseIP(addr.ToString())
if parsed == nil {
continue
}
if (ipv6 && parsed.To4() != nil) ||
(!ipv6 && parsed.To4() == nil) {
continue
}
switch addr.AddrType() {
// Ignore CiliumInternalIPs
case NodeCiliumInternalIP:
continue
// Always prefer a cluster internal IP
case NodeInternalIP:
return parsed
case NodeExternalIP:
// Fall back to external Node IP
// if no internal IP could be found
backupIP = parsed
default:
// As a last resort, if no internal or external
// IP was found, use any node address available
if backupIP == nil {
backupIP = parsed
}
}
}
return backupIP
}