-
Notifications
You must be signed in to change notification settings - Fork 22
/
loadbalancer.go
50 lines (39 loc) · 1.42 KB
/
loadbalancer.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
package helpers
import (
"fmt"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"log"
"net"
)
// GetLoadBalancerIp returns the IP of the load balancer from the load balancer ingress object
func GetLoadBalancerIp(loadBalancerIngress map[string]interface{}) (net.IP, error) {
loadBalancerIP, err := getIpBasedLoadBalancerIp(loadBalancerIngress)
if err == nil {
return loadBalancerIP, nil
} else {
log.Printf("Falling back to reading DNS based load balancer IP, because of: %s\n", err)
return getDnsBasedLoadBalancerIp(loadBalancerIngress)
}
}
func getIpBasedLoadBalancerIp(lbIngress map[string]interface{}) (net.IP, error) {
loadBalancerIP, found, err := unstructured.NestedString(lbIngress, "ip")
if err != nil || !found {
return nil, fmt.Errorf("could not get IP based load balancer IP: %s", err)
}
ip := net.ParseIP(loadBalancerIP)
if ip == nil {
return nil, fmt.Errorf("failed to parse IP from load balancer IP %s", loadBalancerIP)
}
return ip, nil
}
func getDnsBasedLoadBalancerIp(lbIngress map[string]interface{}) (net.IP, error) {
loadBalancerHostname, found, err := unstructured.NestedString(lbIngress, "hostname")
if err != nil || !found {
return nil, fmt.Errorf("could not get DNS based load balancer IP: %s", err)
}
ips, err := net.LookupIP(loadBalancerHostname)
if err != nil || len(ips) < 1 {
return nil, fmt.Errorf("could not get IPs by load balancer hostname: %s", err)
}
return ips[0], nil
}