forked from arouene/ProbeEP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hostnameManagement.go
118 lines (101 loc) · 2.43 KB
/
hostnameManagement.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
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
package main
import (
"fmt"
"net"
"strings"
v1 "k8s.io/api/core/v1"
)
func CheckHostnamesConfiguration(ep *v1.EndpointSubset, hosts []string) bool {
shouldUpdate := false
if CheckRemovedHost(ep, hosts) {
shouldUpdate = true
}
if ResolveHosts(ep, hosts) {
shouldUpdate = true
}
return shouldUpdate
}
func CheckRemovedHost(ep *v1.EndpointSubset, hosts []string) bool {
shouldUpdate := false
updateAddr, newSet := CheckRemovedHostAddrSet(ep.Addresses, hosts)
if updateAddr {
ep.Addresses = newSet
shouldUpdate = true
}
updateAddr, newSet = CheckRemovedHostAddrSet(ep.NotReadyAddresses, hosts)
if updateAddr {
ep.NotReadyAddresses = newSet
shouldUpdate = true
}
return shouldUpdate
}
func CheckRemovedHostAddrSet(addrSet []v1.EndpointAddress, hosts []string) (bool, []v1.EndpointAddress) {
idxToRemove := make([]int, 0)
shouldUpdate := false
for idx, addr := range addrSet {
if addr.Hostname != "" && !matchesHost(addr.Hostname, hosts) {
idxToRemove = append(idxToRemove, idx)
shouldUpdate = true
}
}
for _, id := range idxToRemove {
addrSet = remove(addrSet, id)
}
return shouldUpdate, addrSet
}
func ResolveHosts(ep *v1.EndpointSubset, hosts []string) bool {
shouldUpdate := false
for _, hostname := range hosts {
ip, err := net.LookupIP(hostname)
if err != nil {
fmt.Println(err)
continue
}
ipString := ip[0].String()
CheckDNSChange(ep, ipString, hostname)
shouldAddHost := true
for _, addr := range ep.Addresses {
if addr.IP == ipString {
shouldAddHost = false
break
}
}
for _, addr := range ep.NotReadyAddresses {
if addr.IP == ipString {
shouldAddHost = false
break
}
}
if shouldAddHost {
AddNewAddress(ep, ipString, hostname)
shouldUpdate = true
}
}
return shouldUpdate
}
func CheckDNSChange(ep *v1.EndpointSubset, ip string, hostname string) {
for idx, addr := range ep.Addresses {
if addr.Hostname == hostname && addr.IP != ip {
ep.Addresses = remove(ep.Addresses, idx)
break
}
}
for idx, addr := range ep.NotReadyAddresses {
if addr.Hostname == hostname && addr.IP != ip {
ep.NotReadyAddresses = remove(ep.NotReadyAddresses, idx)
break
}
}
}
func matchesHost(hostToCheck string, hosts []string) bool {
for _, host := range hosts {
if hostToCheck == strings.Split(host, ".")[0] {
return true
}
}
return false
}
func remove(s []v1.EndpointAddress, i int) []v1.EndpointAddress {
s[i] = s[len(s)-1]
return s[:len(s)-1]
}