/
local_dc.go
177 lines (149 loc) · 4.13 KB
/
local_dc.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package balancer
import (
"context"
"errors"
"fmt"
"math/rand"
"net"
"net/url"
"strings"
"sync"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/endpoint"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/xerrors"
)
const (
maxEndpointsCheckPerLocation = 5
)
func checkFastestAddress(ctx context.Context, addresses []string) string {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
type result struct {
address string
err error
}
results := make(chan result, len(addresses))
defer close(results)
startDial := make(chan struct{})
var dialer net.Dialer
var wg sync.WaitGroup
defer wg.Wait()
for _, addr := range addresses {
wg.Add(1)
go func(address string) {
defer wg.Done()
<-startDial
conn, err := dialer.DialContext(ctx, "tcp", address)
if err == nil {
cancel()
_ = conn.Close()
}
results <- result{address: address, err: err}
}(addr)
}
close(startDial)
for range addresses {
res := <-results
if res.err == nil {
return res.address
}
}
return ""
}
func detectFastestEndpoint(ctx context.Context, endpoints []endpoint.Endpoint) (endpoint.Endpoint, error) {
if len(endpoints) == 0 {
return nil, xerrors.WithStackTrace(errors.New("empty endpoints list"))
}
var lastErr error
// common is 2 ip address for every fqdn: ipv4 + ipv6
initialAddressToEndpointCapacity := len(endpoints) * 2
addressToEndpoint := make(map[string]endpoint.Endpoint, initialAddressToEndpointCapacity)
for _, ep := range endpoints {
host, port, err := extractHostPort(ep.Address())
if err != nil {
lastErr = xerrors.WithStackTrace(err)
continue
}
addresses, err := net.DefaultResolver.LookupHost(ctx, host)
if err != nil {
lastErr = err
continue
}
if len(addresses) == 0 {
lastErr = xerrors.WithStackTrace(fmt.Errorf("no ips for fqdn: %q", host))
continue
}
for _, ip := range addresses {
address := net.JoinHostPort(ip, port)
addressToEndpoint[address] = ep
}
}
if len(addressToEndpoint) == 0 {
return nil, xerrors.WithStackTrace(lastErr)
}
addressesToPing := make([]string, 0, len(addressToEndpoint))
for ip := range addressToEndpoint {
addressesToPing = append(addressesToPing, ip)
}
fastestAddress := checkFastestAddress(ctx, addressesToPing)
if fastestAddress == "" {
return nil, xerrors.WithStackTrace(errors.New("failed to check fastest address"))
}
return addressToEndpoint[fastestAddress], nil
}
func detectLocalDC(ctx context.Context, endpoints []endpoint.Endpoint) (string, error) {
if len(endpoints) == 0 {
return "", xerrors.WithStackTrace(ErrNoEndpoints)
}
endpointsByDc := splitEndpointsByLocation(endpoints)
if len(endpointsByDc) == 1 {
return endpoints[0].Location(), nil
}
endpointsToTest := make([]endpoint.Endpoint, 0, maxEndpointsCheckPerLocation*len(endpointsByDc))
for _, dcEndpoints := range endpointsByDc {
endpointsToTest = append(endpointsToTest, getRandomEndpoints(dcEndpoints, maxEndpointsCheckPerLocation)...)
}
fastest, err := detectFastestEndpoint(ctx, endpointsToTest)
if err == nil {
return fastest.Location(), nil
}
return "", err
}
func extractHostPort(address string) (host string, port string, _ error) {
if !strings.Contains(address, "://") {
address = "stub://" + address
}
u, err := url.Parse(address)
if err != nil {
return "", "", xerrors.WithStackTrace(err)
}
host, port, err = net.SplitHostPort(u.Host)
if err != nil {
return "", "", xerrors.WithStackTrace(err)
}
return host, port, nil
}
func getRandomEndpoints(endpoints []endpoint.Endpoint, count int) []endpoint.Endpoint {
if len(endpoints) <= count {
return endpoints
}
got := make(map[int]bool, maxEndpointsCheckPerLocation)
res := make([]endpoint.Endpoint, 0, maxEndpointsCheckPerLocation)
for len(got) < count {
//nolint:gosec
index := rand.Intn(len(endpoints))
if got[index] {
continue
}
got[index] = true
res = append(res, endpoints[index])
}
return res
}
func splitEndpointsByLocation(endpoints []endpoint.Endpoint) map[string][]endpoint.Endpoint {
res := make(map[string][]endpoint.Endpoint)
for _, ep := range endpoints {
location := ep.Location()
res[location] = append(res[location], ep)
}
return res
}