forked from segmentio/kafka-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dialer.go
255 lines (224 loc) · 7.53 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package kafka
import (
"context"
"net"
"strconv"
"time"
)
// The Dialer type mirrors the net.Dialer API but is designed to open kafka
// connections instead of raw network connections.
type Dialer struct {
// Unique identifier for client connections established by this Dialer.
ClientID string
// Timeout is the maximum amount of time a dial will wait for a connect to
// complete. If Deadline is also set, it may fail earlier.
//
// The default is no timeout.
//
// When dialing a name with multiple IP addresses, the timeout may be
// divided between them.
//
// With or without a timeout, the operating system may impose its own
// earlier timeout. For instance, TCP timeouts are often around 3 minutes.
Timeout time.Duration
// Deadline is the absolute point in time after which dials will fail.
// If Timeout is set, it may fail earlier.
// Zero means no deadline, or dependent on the operating system as with the
// Timeout option.
Deadline time.Time
// LocalAddr is the local address to use when dialing an address.
// The address must be of a compatible type for the network being dialed.
// If nil, a local address is automatically chosen.
LocalAddr net.Addr
// DualStack enables RFC 6555-compliant "Happy Eyeballs" dialing when the
// network is "tcp" and the destination is a host name with both IPv4 and
// IPv6 addresses. This allows a client to tolerate networks where one
// address family is silently broken.
DualStack bool
// FallbackDelay specifies the length of time to wait before spawning a
// fallback connection, when DualStack is enabled.
// If zero, a default delay of 300ms is used.
FallbackDelay time.Duration
// KeepAlive specifies the keep-alive period for an active network
// connection.
// If zero, keep-alives are not enabled. Network protocols that do not
// support keep-alives ignore this field.
KeepAlive time.Duration
// Resolver optionally specifies an alternate resolver to use.
Resolver Resolver
}
// Dial connects to the address on the named network.
func (d *Dialer) Dial(network string, address string) (*Conn, error) {
return d.DialContext(context.Background(), network, address)
}
// DialContext connects to the address on the named network using the provided
// context.
//
// The provided Context must be non-nil. If the context expires before the
// connection is complete, an error is returned. Once successfully connected,
// any expiration of the context will not affect the connection.
//
// When using TCP, and the host in the address parameter resolves to multiple
// network addresses, any dial timeout (from d.Timeout or ctx) is spread over
// each consecutive dial, such that each is given an appropriate fraction of the
// time to connect. For example, if a host has 4 IP addresses and the timeout is
// 1 minute, the connect to each single address will be given 15 seconds to
// complete before trying the next one.
func (d *Dialer) DialContext(ctx context.Context, network string, address string) (*Conn, error) {
if d.Timeout != 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, d.Timeout)
defer cancel()
}
if !d.Deadline.IsZero() {
var cancel context.CancelFunc
ctx, cancel = context.WithDeadline(ctx, d.Deadline)
defer cancel()
}
c, err := d.dialContext(ctx, network, address)
if err != nil {
return nil, err
}
return NewConnWith(c, ConnConfig{ClientID: d.ClientID}), nil
}
// DialLeader opens a connection to the leader of the partition for a given
// topic.
//
// The address given to the DialContext method may not be the one that the
// connection will end up being established to, because the dialer will lookup
// the partition leader for the topic and return a connection to that server.
// The original address is only used as a mechanism to discover the
// configuration of the kafka cluster that we're connecting to.
func (d *Dialer) DialLeader(ctx context.Context, network string, address string, topic string, partition int) (*Conn, error) {
b, err := d.LookupLeader(ctx, network, address, topic, partition)
if err != nil {
return nil, err
}
c, err := d.dialContext(ctx, network, net.JoinHostPort(b.Host, strconv.Itoa(b.Port)))
if err != nil {
return nil, err
}
return NewConnWith(c, ConnConfig{
ClientID: d.ClientID,
Topic: topic,
Partition: partition,
}), nil
}
// LookupLeader searches for the kafka broker that is the leader of the
// partition for a given topic, returning a Broker value representing it.
func (d *Dialer) LookupLeader(ctx context.Context, network string, address string, topic string, partition int) (Broker, error) {
c, err := d.DialContext(ctx, network, address)
if err != nil {
return Broker{}, err
}
defer c.Close()
brkch := make(chan Broker, 1)
errch := make(chan error, 1)
go func() {
for attempt := 0; true; attempt++ {
if attempt != 0 {
sleep(ctx, backoff(attempt, 100*time.Millisecond, 10*time.Second))
}
partitions, err := c.ReadPartitions(topic)
if err != nil {
if isTemporary(err) {
continue
}
errch <- err
return
}
for _, p := range partitions {
if p.ID == partition {
brkch <- p.Leader
return
}
}
}
}()
var brk Broker
select {
case brk = <-brkch:
case err = <-errch:
case <-ctx.Done():
err = ctx.Err()
}
return brk, err
}
func (d *Dialer) dialContext(ctx context.Context, network string, address string) (net.Conn, error) {
if r := d.Resolver; r != nil {
host, port := splitHostPort(address)
addrs, err := r.LookupHost(ctx, host)
if err != nil {
return nil, err
}
if len(addrs) != 0 {
address = addrs[0]
}
if len(port) != 0 {
address, _ = splitHostPort(address)
address = net.JoinHostPort(address, port)
}
}
return (&net.Dialer{
LocalAddr: d.LocalAddr,
DualStack: d.DualStack,
FallbackDelay: d.FallbackDelay,
KeepAlive: d.KeepAlive,
}).DialContext(ctx, network, address)
}
// DefaultDialer is the default dialer used when none is specified.
var DefaultDialer = &Dialer{
Timeout: 10 * time.Second,
DualStack: true,
}
// Dial is a convenience wrapper for DefaultDialer.Dial.
func Dial(network string, address string) (*Conn, error) {
return DefaultDialer.Dial(network, address)
}
// DialContext is a convenience wrapper for DefaultDialer.DialContext.
func DialContext(ctx context.Context, network string, address string) (*Conn, error) {
return DefaultDialer.DialContext(ctx, network, address)
}
// DialLeader is a convenience wrapper for DefaultDialer.DialLeader.
func DialLeader(ctx context.Context, network string, address string, topic string, partition int) (*Conn, error) {
return DefaultDialer.DialLeader(ctx, network, address, topic, partition)
}
// The Resolver interface is used as an abstraction to provide service discovery
// of the hosts of a kafka cluster.
type Resolver interface {
// LookupHost looks up the given host using the local resolver.
// It returns a slice of that host's addresses.
LookupHost(ctx context.Context, host string) (addrs []string, err error)
}
func sleep(ctx context.Context, duration time.Duration) bool {
if duration != 0 {
select {
default:
return true
case <-ctx.Done():
return false
}
}
timer := time.NewTimer(duration)
defer timer.Stop()
select {
case <-timer.C:
return true
case <-ctx.Done():
return false
}
}
func backoff(attempt int, min time.Duration, max time.Duration) time.Duration {
d := time.Duration(attempt*attempt) * min
if d > max {
d = max
}
return d
}
func splitHostPort(s string) (host string, port string) {
host, port, _ = net.SplitHostPort(s)
if len(host) == 0 && len(port) == 0 {
host = s
}
return
}