-
Notifications
You must be signed in to change notification settings - Fork 72
/
dialer.go
203 lines (174 loc) · 5.28 KB
/
dialer.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
//
// Copyright (C) 2019-2020 Vdaas.org Vald team ( kpango, rinx, kmrmt )
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Package tcp provides tcp option
package tcp
import (
"context"
"crypto/tls"
"strconv"
"sync/atomic"
"time"
"github.com/vdaas/vald/internal/cache"
"github.com/vdaas/vald/internal/errors"
"github.com/vdaas/vald/internal/log"
"github.com/vdaas/vald/internal/net"
"github.com/vdaas/vald/internal/safety"
)
// Dialer is an interface to get the dialer instance to connect to an address.
type Dialer interface {
GetDialer() func(ctx context.Context, network, addr string) (net.Conn, error)
StartDialerCache(ctx context.Context)
DialContext(ctx context.Context, network, address string) (net.Conn, error)
}
type dialer struct {
cache cache.Cache
dnsCache bool
tlsConfig *tls.Config
dnsRefreshDurationStr string
dnsCacheExpirationStr string
dnsRefreshDuration time.Duration
dnsCacheExpiration time.Duration
dialerTimeout time.Duration
dialerKeepAlive time.Duration
dialerDualStack bool
der *net.Dialer
dialer func(ctx context.Context, network, addr string) (net.Conn, error)
}
type dialerCache struct {
ips []string
cnt uint32
}
// IP returns the next cached IP address in round robin order.
// It starts getting the index 1 cache instead of index 0 cache.
func (d *dialerCache) IP() string {
if d.Len() == 1 {
return d.ips[0]
}
return d.ips[atomic.AddUint32(&d.cnt, 1)%d.Len()]
}
// Len returns the length of cached IP addresses
func (d *dialerCache) Len() uint32 {
return uint32(len(d.ips))
}
// NewDialer initialize and return the dialer instance
func NewDialer(opts ...DialerOption) (der Dialer, err error) {
d := new(dialer)
for _, opt := range append(defaultDialerOptions, opts...) {
opt(d)
}
d.der = &net.Dialer{
Timeout: d.dialerTimeout,
KeepAlive: d.dialerKeepAlive,
DualStack: d.dialerDualStack,
Control: Control,
}
d.dialer = d.dial
if d.dnsCache {
if d.dnsRefreshDuration > d.dnsCacheExpiration {
return nil, errors.ErrInvalidDNSConfig(d.dnsRefreshDuration, d.dnsCacheExpiration)
}
if d.cache == nil {
if d.cache, err = cache.New(
cache.WithExpireDuration(d.dnsCacheExpirationStr),
cache.WithExpireCheckDuration(d.dnsRefreshDurationStr),
cache.WithExpiredHook(d.cacheExpireHook),
); err != nil {
return nil, err
}
}
d.dialer = d.cachedDialer
}
d.der.Resolver = &net.Resolver{
PreferGo: false,
Dial: d.dialer,
}
return d, nil
}
// GetDialer returns a function to return the connection
func (d *dialer) GetDialer() func(ctx context.Context, network, addr string) (net.Conn, error) {
return d.dialer
}
func (d *dialer) lookup(ctx context.Context, host string) (*dialerCache, error) {
cache, ok := d.cache.Get(host)
if ok {
return cache.(*dialerCache), nil
}
r, err := d.der.Resolver.LookupIPAddr(ctx, host)
if err != nil {
return nil, err
}
dc := &dialerCache{
ips: make([]string, 0, len(r)),
}
for _, ip := range r {
dc.ips = append(dc.ips, ip.String())
}
d.cache.Set(host, dc)
return dc, nil
}
// StartDialerCache starts the dialer cache to expire the cache automatically
func (d *dialer) StartDialerCache(ctx context.Context) {
if d.dnsCache && d.cache != nil {
d.cache.Start(ctx)
}
}
// DialContext returns the connection or error base on the input.
// If the DNS cache is enabled, it will lookup the DNS cache in round robin order and return a connection of it.
// Also if TLS is enabled, it will create a TLS connection for it.
func (d *dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
return d.GetDialer()(ctx, network, address)
}
func (d *dialer) cachedDialer(dctx context.Context, network, addr string) (conn net.Conn, err error) {
host, port, isIP, err := net.Parse(addr)
if err != nil {
return nil, err
}
if d.dnsCache && !isIP {
if dc, err := d.lookup(dctx, host); err == nil {
for i := uint32(0); i < dc.Len(); i++ {
hostIP := dc.IP() + ":" + strconv.FormatUint(uint64(port), 10)
if conn, err := d.dial(dctx, network, hostIP); err == nil {
return conn, nil
}
}
d.cache.Delete(host)
}
}
return d.dial(dctx, network, addr)
}
func (d *dialer) dial(ctx context.Context, network, addr string) (net.Conn, error) {
conn, err := d.der.DialContext(ctx, network, addr)
if err != nil {
defer func(conn net.Conn) {
if conn != nil {
conn.Close()
}
}(conn)
return nil, err
}
if d.tlsConfig != nil {
return tls.Client(conn, d.tlsConfig), nil
}
return conn, nil
}
func (d *dialer) cacheExpireHook(ctx context.Context, addr string) {
if err := safety.RecoverFunc(func() (err error) {
_, err = d.lookup(ctx, addr)
return
})(); err != nil {
log.Errorf("DNS cacheExpireHook error occurred: %v", err)
}
}