-
Notifications
You must be signed in to change notification settings - Fork 247
/
parallel.go
223 lines (187 loc) · 5.27 KB
/
parallel.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package upstream
import (
"context"
"fmt"
"net"
"time"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/miekg/dns"
)
// exchangeResult is a structure that represents result of exchangeAsync
type exchangeResult struct {
reply *dns.Msg // Result of DNS request execution
upstream Upstream // Upstream that successfully resolved request
err error // Error
}
// ErrNoUpstreams is returned from the methods that expect at least a single
// upstream to work with when no upstreams specified.
const ErrNoUpstreams errors.Error = "no upstream specified"
// ExchangeParallel function is called to parallel exchange dns request by many upstreams
// First answer without error will be returned
// We will return nil and error if count of errors equals count of upstreams
func ExchangeParallel(u []Upstream, req *dns.Msg) (*dns.Msg, Upstream, error) {
size := len(u)
if size == 0 {
return nil, nil, ErrNoUpstreams
}
if size == 1 {
reply, err := exchange(u[0], req)
return reply, u[0], err
}
// Size of channel must accommodate results of exchangeAsync from all upstreams
// Otherwise sending in channel will be locked
ch := make(chan *exchangeResult, size)
for _, f := range u {
go exchangeAsync(f, req, ch)
}
errs := []error{}
for n := 0; n < len(u); n++ {
rep := <-ch
if rep.err != nil {
errs = append(errs, rep.err)
} else if rep.reply != nil {
return rep.reply, rep.upstream, nil
}
}
if len(errs) == 0 {
// All responses had nil replies.
return nil, nil, fmt.Errorf("none of upstream servers responded")
}
return nil, nil, errors.List("all upstreams failed to respond", errs...)
}
// ExchangeAllResult - result of ExchangeAll()
type ExchangeAllResult struct {
Resp *dns.Msg // response
Upstream Upstream // upstream server
}
// ExchangeAll receives a response from each of ups.
func ExchangeAll(ups []Upstream, req *dns.Msg) (res []ExchangeAllResult, err error) {
upsl := len(ups)
if upsl == 0 {
return nil, ErrNoUpstreams
}
res = make([]ExchangeAllResult, 0, upsl)
errs := make([]error, 0, upsl)
resCh := make(chan *exchangeResult, upsl)
// Start exchanging concurrently.
for _, u := range ups {
go exchangeAsync(u, req, resCh)
}
// Wait for all exchanges to finish.
for i := 0; i < upsl; i++ {
rep := <-resCh
if rep.err != nil {
errs = append(errs, rep.err)
continue
}
if rep.reply == nil {
errs = append(errs, errors.Error("no reply"))
continue
}
res = append(res, ExchangeAllResult{
Resp: rep.reply,
Upstream: rep.upstream,
})
}
if len(errs) == upsl {
return res, errors.List("all upstreams failed to exchange", errs...)
}
return res, nil
}
// exchangeAsync tries to resolve DNS request with one upstream and send result to resp channel
func exchangeAsync(u Upstream, req *dns.Msg, respCh chan *exchangeResult) {
resp, err := u.Exchange(req.Copy())
respCh <- &exchangeResult{
reply: resp,
upstream: u,
err: err,
}
}
func exchange(u Upstream, req *dns.Msg) (*dns.Msg, error) {
start := time.Now()
reply, err := u.Exchange(req)
elapsed := time.Since(start)
if err == nil {
log.Tracef(
"upstream %s successfully finished exchange of %s. Elapsed %s.",
u.Address(),
req.Question[0].String(),
elapsed,
)
} else {
log.Tracef(
"upstream %s failed to exchange %s in %s. Cause: %s",
u.Address(),
req.Question[0].String(),
elapsed,
err,
)
}
return reply, err
}
// lookupResult is a structure that represents result of lookup
type lookupResult struct {
address []net.IPAddr // List of IP addresses
err error // Error
}
// LookupParallel starts parallel lookup for host ip with many Resolvers
// First answer without error will be returned
// Return nil and error if count of errors equals count of resolvers
func LookupParallel(ctx context.Context, resolvers []*Resolver, host string) ([]net.IPAddr, error) {
size := len(resolvers)
if size == 0 {
return nil, errors.Error("no resolvers specified")
}
if size == 1 {
address, err := lookup(ctx, resolvers[0], host)
return address, err
}
// Size of channel must accommodate results of lookups from all resolvers
// Otherwise sending in channel will be locked
ch := make(chan *lookupResult, size)
for _, res := range resolvers {
go lookupAsync(ctx, res, host, ch)
}
var errs []error
for n := 0; n < size; n++ {
result := <-ch
if result.err != nil {
errs = append(errs, result.err)
continue
}
return result.address, nil
}
return nil, errors.List("all resolvers failed", errs...)
}
// lookupAsync tries to lookup for host ip with one Resolver and sends lookupResult to res channel
func lookupAsync(ctx context.Context, r *Resolver, host string, res chan *lookupResult) {
address, err := lookup(ctx, r, host)
res <- &lookupResult{
err: err,
address: address,
}
}
func lookup(ctx context.Context, r *Resolver, host string) ([]net.IPAddr, error) {
start := time.Now()
address, err := r.LookupIPAddr(ctx, host)
elapsed := time.Since(start)
if err != nil {
log.Tracef(
"failed to lookup for %s in %s using %s: %s",
host,
elapsed,
r.resolverAddress,
err,
)
} else {
log.Tracef(
"successfully finished lookup for %s in %s using %s. Result : %s",
host,
elapsed,
r.resolverAddress,
address,
)
}
return address, err
}