-
Notifications
You must be signed in to change notification settings - Fork 1
/
conn.go
116 lines (99 loc) · 2.04 KB
/
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package gearman // import "github.com/nathanaelle/gearman/v2"
import (
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
)
type (
// Conn describe a connection
Conn interface {
io.Writer
io.Reader
io.Closer
SetReadDeadline(time.Time)
SetWriteDeadline(time.Time)
Redial()
String() string
CounterAdd(int32)
IsZeroCounter() bool
}
netConn struct {
lock *sync.Mutex
closed int32
counter int32
network, address string
conn atomic.Value
}
)
// NetConn return a gearman.Conn for a network connection
func NetConn(network, address string) Conn {
nc := &netConn{
lock: new(sync.Mutex),
network: network,
address: address,
}
return nc
}
func (nc *netConn) Close() error {
if !nc.isNotClosed() {
return nil
}
atomic.AddInt32(&nc.closed, 1)
conn := nc.conn.Load()
if conn != nil {
return conn.(io.Closer).Close()
}
return nil
}
func (nc *netConn) String() string {
return fmt.Sprintf("%s[%s]", nc.network, nc.address)
}
func (nc *netConn) Redial() {
if conn := nc.conn.Load(); conn != nil {
conn.(io.Closer).Close()
}
if nc.isNotClosed() {
conn, err := net.Dial(nc.network, nc.address)
if conn != nil {
nc.conn.Store(conn)
}
if err != nil {
time.Sleep(RetryTimeout)
}
}
}
func (nc *netConn) Read(b []byte) (int, error) {
return nc.nc().Read(b)
}
func (nc *netConn) SetReadDeadline(t time.Time) {
nc.nc().SetReadDeadline(t)
}
func (nc *netConn) SetWriteDeadline(t time.Time) {
nc.nc().SetWriteDeadline(t)
}
func (nc *netConn) Write(b []byte) (int, error) {
return nc.nc().Write(b)
}
func (nc *netConn) CounterAdd(d int32) {
atomic.AddInt32(&nc.counter, d)
}
func (nc *netConn) IsZeroCounter() bool {
return atomic.LoadInt32(&nc.counter) == 0
}
func (nc *netConn) isNotClosed() bool {
return atomic.LoadInt32(&nc.closed) == 0
}
func (nc *netConn) nc() net.Conn {
for nc.isNotClosed() {
if c := nc.conn.Load(); c != nil {
if conn, ok := c.(net.Conn); ok {
return conn
}
}
time.Sleep(RetryTimeout)
}
return &nullConn{nc.network, nc.address}
}