...
1
2
3
4
5
6
7
8
9
10
11
12
13
14 package cluster
15
16 import (
17 "net"
18
19 "github.com/hashicorp/go-sockaddr"
20 "github.com/pkg/errors"
21 )
22
23 type getIPFunc func() (string, error)
24
25
26 var getPrivateAddress getIPFunc = sockaddr.GetPrivateIP
27 var getPublicAddress getIPFunc = sockaddr.GetPublicIP
28
29
30
31
32
33
34
35 func calculateAdvertiseAddress(bindAddr, advertiseAddr string, allowInsecureAdvertise bool) (net.IP, error) {
36 if advertiseAddr != "" {
37 ip := net.ParseIP(advertiseAddr)
38 if ip == nil {
39 return nil, errors.Errorf("failed to parse advertise addr '%s'", advertiseAddr)
40 }
41 if ip4 := ip.To4(); ip4 != nil {
42 ip = ip4
43 }
44 return ip, nil
45 }
46
47 if isAny(bindAddr) {
48 return discoverAdvertiseAddress(allowInsecureAdvertise)
49 }
50
51 ip := net.ParseIP(bindAddr)
52 if ip == nil {
53 return nil, errors.Errorf("failed to parse bind addr '%s'", bindAddr)
54 }
55 return ip, nil
56 }
57
58
59
60
61
62 func discoverAdvertiseAddress(allowInsecureAdvertise bool) (net.IP, error) {
63 addr, err := getPrivateAddress()
64 if err != nil {
65 return nil, errors.Wrap(err, "failed to get private IP")
66 }
67 if addr == "" && !allowInsecureAdvertise {
68 return nil, errors.New("no private IP found, explicit advertise addr not provided")
69 }
70
71 if addr == "" {
72 addr, err = getPublicAddress()
73 if err != nil {
74 return nil, errors.Wrap(err, "failed to get public IP")
75 }
76 if addr == "" {
77 return nil, errors.New("no private/public IP found, explicit advertise addr not provided")
78 }
79 }
80
81 ip := net.ParseIP(addr)
82 if ip == nil {
83 return nil, errors.Errorf("failed to parse discovered IP '%s'", addr)
84 }
85 return ip, nil
86 }
87
View as plain text