-
Notifications
You must be signed in to change notification settings - Fork 31
/
connpool.go
120 lines (109 loc) · 2.58 KB
/
connpool.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
package retryabledns
import (
"container/heap"
"context"
"fmt"
"net"
"time"
"github.com/miekg/dns"
)
type ConnPool struct {
items map[*dns.Conn]bool
newArrival chan *waitingClient
finished chan *dns.Conn
clients clientQueue
cancel context.CancelFunc
resolver NetworkResolver
}
func NewConnPool(resolver NetworkResolver, poolSize int) (*ConnPool, error) {
ctx, cancel := context.WithCancel(context.Background())
pool := &ConnPool{
items: make(map[*dns.Conn]bool, poolSize),
newArrival: make(chan *waitingClient),
finished: make(chan *dns.Conn),
cancel: cancel,
resolver: resolver,
}
heap.Init(&pool.clients)
for i := 0; i < poolSize; i++ {
conn, err := dns.Dial(resolver.Protocol.String(), resolver.String())
if err != nil {
return nil, fmt.Errorf("unable to create conn to %s: %w", resolver.String(), err)
}
pool.items[conn] = false
}
go pool.coordinate(ctx)
return pool, nil
}
func (cp *ConnPool) LocalAddrs() []*net.UDPAddr {
retval := make([]*net.UDPAddr, len(cp.items))
i := 0
for conn := range cp.items {
retval[i] = conn.LocalAddr().(*net.UDPAddr)
i++
}
return retval
}
func (cp *ConnPool) Resolver() NetworkResolver {
return cp.resolver
}
func (cp *ConnPool) Exchange(ctx context.Context, client *dns.Client, msg *dns.Msg) (r *dns.Msg, rtt time.Duration, err error) {
conn, err := cp.getConnection(ctx)
if err != nil {
return nil, time.Duration(0), err
}
defer cp.releaseConnection(conn)
return client.ExchangeWithConn(msg, conn)
}
func (cp *ConnPool) Close() {
cp.cancel()
for conn := range cp.items {
conn.Close()
}
}
func (cp *ConnPool) coordinate(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case client := <-cp.newArrival:
heap.Push(&cp.clients, client)
case conn := <-cp.finished:
cp.items[conn] = false
}
for conn, inUse := range cp.items {
if !inUse && len(cp.clients) > 0 {
cp.items[conn] = true
client := heap.Pop(&cp.clients).(*waitingClient)
select {
case client.returnCh <- conn:
case <-client.doneCh:
cp.items[conn] = false
case <-ctx.Done():
return
}
}
}
}
}
func (cp *ConnPool) getConnection(ctx context.Context) (*dns.Conn, error) {
client := &waitingClient{
arrivalTime: time.Now(),
returnCh: make(chan *dns.Conn),
doneCh: ctx.Done(),
}
select {
case cp.newArrival <- client:
case <-ctx.Done():
return nil, ctx.Err()
}
select {
case conn := <-client.returnCh:
return conn, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (cp *ConnPool) releaseConnection(conn *dns.Conn) {
cp.finished <- conn
}