forked from samuel/go-zookeeper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
286 lines (250 loc) · 5.23 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
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package zk
// TODO: ping server
// TODO: everything
import (
"encoding/binary"
"io"
"log"
"net"
"sync"
"sync/atomic"
"time"
)
type state int
type Conn struct {
servers []string
serverIndex int
conn net.Conn
state state
eventChan <-chan Event
pingInterval time.Duration
recvTimeout time.Duration
connectTimeout time.Duration
sendChan chan *request
requests map[int32]*request // Xid -> pending request
requestsLock sync.Mutex
xid int32
lastZxid int64
sessionId int64
timeout int32
passwd []byte
}
type request struct {
xid int32
pkt interface{}
recvStruct interface{}
recvChan chan error
}
type Event struct {
Type EventType
State int // One of the STATE_* constants.
Path string // For non-session events, the path of the watched node.
}
func Connect(servers []string, recvTimeout time.Duration) (*Conn, <-chan Event, error) {
ec := make(<-chan Event, 5)
conn := Conn{
servers: servers,
serverIndex: 0,
conn: nil,
state: stateDisconnected,
eventChan: ec,
recvTimeout: recvTimeout,
pingInterval: 10 * time.Second,
connectTimeout: 1 * time.Second,
sendChan: make(chan *request),
requests: make(map[int32]*request),
}
go conn.loop()
return &conn, ec, nil
}
func (c *Conn) connect() {
startIndex := c.serverIndex
for {
zkConn, err := net.DialTimeout("tcp", c.servers[c.serverIndex], c.connectTimeout)
if err == nil {
c.conn = zkConn
c.state = stateConnected
return
}
c.serverIndex = (c.serverIndex + 1) % len(c.servers)
if c.serverIndex == startIndex {
time.Sleep(time.Second)
}
}
}
func (c *Conn) loop() {
for {
if c.conn != nil {
c.conn.Close()
}
c.conn = nil
c.state = stateDisconnected
c.connect()
c.handler()
}
}
func (c *Conn) handler() {
buf := make([]byte, 1024)
// connect request
n, err := encodePacket(buf[4:], &connectRequest{
ProtocolVersion: protocolVersion,
LastZxidSeen: c.lastZxid,
TimeOut: 30000,
SessionId: c.sessionId,
Passwd: emptyPassword,
})
if err != nil {
log.Println(err)
return
}
binary.BigEndian.PutUint32(buf[:4], uint32(n))
_, err = c.conn.Write(buf[:n+4])
if err != nil {
log.Println(err)
return
}
// connect response
// package length
_, err = io.ReadFull(c.conn, buf[:4])
if err != nil {
log.Println(err)
return
}
blen := int(binary.BigEndian.Uint32(buf[:4]))
if cap(buf) < blen {
buf = make([]byte, blen)
}
_, err = io.ReadFull(c.conn, buf[:blen])
if err != nil {
log.Println(err)
return
}
r := connectResponse{}
decodePacket(buf[:blen], r)
// TODO: Check for a dead session
c.timeout = r.TimeOut
c.sessionId = r.SessionId
c.passwd = r.Passwd
c.state = stateHasSession
// if new session
c.xid = 0
// Send loop
go func() {
buf := make([]byte, 1024)
for {
req := <-c.sendChan
n, err := encodePacket(buf[4:], req.pkt)
if err != nil {
req.recvChan <- err
continue
}
binary.BigEndian.PutUint32(buf[:4], uint32(n))
c.requestsLock.Lock()
c.requests[req.xid] = req
c.requestsLock.Unlock()
_, err = c.conn.Write(buf[:n+4])
if err != nil {
req.recvChan <- err
return
}
}
}()
// Receive loop
for {
// package length
_, err = io.ReadFull(c.conn, buf[:4])
if err != nil {
log.Println(err)
return
}
blen := int(binary.BigEndian.Uint32(buf[:4]))
if cap(buf) < blen {
buf = make([]byte, blen)
}
_, err = io.ReadFull(c.conn, buf[:blen])
if err != nil {
log.Println(err)
return
}
res := responseHeader{}
_, err := decodePacket(buf[:16], &res)
if err != nil {
// TODO
panic(err)
}
log.Printf("Response xid=%d zxid=%d err=%d\n", res.Xid, res.Zxid, res.Err)
if res.Zxid > 0 {
c.lastZxid = res.Zxid
}
if res.Xid == -1 {
res := &watcherEvent{}
_, err := decodePacket(buf[:blen], res)
if err != nil {
panic(err)
}
log.Printf("%+v\n", res)
} else {
c.requestsLock.Lock()
req, ok := c.requests[res.Xid]
if ok {
delete(c.requests, res.Xid)
}
c.requestsLock.Unlock()
if !ok {
log.Printf("Response for unknown request with xid %d", res.Xid)
} else {
_, err := decodePacket(buf[:blen], req.recvStruct)
req.recvChan <- err
}
}
}
}
func (c *Conn) nextXid() int32 {
return atomic.AddInt32(&c.xid, 1)
}
func (c *Conn) Children(path string) (children []string, stat *Stat, err error) {
xid := c.nextXid()
ch := make(chan error)
rs := &getChildren2Response{}
req := &request{
xid: xid,
pkt: &getChildren2Request{
requestHeader: requestHeader{
Xid: xid,
Opcode: opGetChildren2,
},
Path: path,
Watch: false,
},
recvStruct: rs,
recvChan: ch,
}
c.sendChan <- req
err = <-ch
children = rs.Children
stat = &rs.Stat
return
}
func (c *Conn) ChildrenW(path string) (children []string, stat *Stat, err error) {
xid := c.nextXid()
ch := make(chan error)
rs := &getChildren2Response{}
req := &request{
xid: xid,
pkt: &getChildren2Request{
requestHeader: requestHeader{
Xid: xid,
Opcode: opGetChildren2,
},
Path: path,
Watch: true,
},
recvStruct: rs,
recvChan: ch,
}
c.sendChan <- req
err = <-ch
children = rs.Children
stat = &rs.Stat
return
}