forked from messagebird/beanstalkd_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lazy_conn.go
96 lines (83 loc) · 1.81 KB
/
lazy_conn.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
package main
import (
"io"
"net"
"sync"
"time"
"github.com/prometheus/common/log"
)
type lazyConn struct {
m sync.Mutex
conn net.Conn
addr string
dialTimeout time.Duration
readTimeout time.Duration
}
func newLazyConn(addr string, dialTimeout time.Duration, readTimeout time.Duration) (io.ReadWriteCloser, error) {
l := &lazyConn{
dialTimeout: dialTimeout,
readTimeout: readTimeout,
addr: addr,
}
if err := l.connect(); err != nil {
return nil, err
}
return l, nil
}
func (l *lazyConn) connect() error {
conn, err := net.DialTimeout("tcp", l.addr, l.dialTimeout)
if err != nil {
l.conn = nil
return err
}
l.conn = conn
return nil
}
func (l *lazyConn) withTimeout() net.Conn {
if l.readTimeout > 0 {
err := l.conn.SetReadDeadline(time.Now().Add(l.readTimeout))
if err != nil {
log.Warnf("unable to set timeout: %s", err)
}
}
return l.conn
}
// Read implements the io.Reader interface and attempt
// to reconnect to beanstalk in case of io.EOF.
func (l *lazyConn) Read(p []byte) (n int, err error) {
l.m.Lock()
defer l.m.Unlock()
if l.conn == nil {
if err := l.connect(); err != nil {
return 0, io.ErrUnexpectedEOF
}
}
n, err = l.withTimeout().Read(p)
switch {
case err == io.EOF:
fallthrough
case err == io.ErrUnexpectedEOF:
l.conn = nil
}
return n, err
}
// Write implements the io.Writer interface and attempt
// to reconnect to beanstalk in case of io.EOF.
func (l *lazyConn) Write(p []byte) (n int, err error) {
l.m.Lock()
defer l.m.Unlock()
if l.conn == nil {
if err := l.connect(); err != nil {
return 0, io.ErrClosedPipe
}
}
n, err = l.withTimeout().Write(p)
if n == 0 && err != io.ErrClosedPipe {
l.conn = nil
}
return n, err
}
// Close the TCP connection.
func (l *lazyConn) Close() error {
return l.conn.Close()
}