forked from tarantool/go-tarantool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.go
337 lines (309 loc) · 6.93 KB
/
connection.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package tarantool
import (
"bufio"
"bytes"
"errors"
"io"
"log"
"net"
"sync"
"sync/atomic"
"time"
)
type Connection struct {
addr string
c *net.TCPConn
r *bufio.Reader
w *bufio.Writer
mutex *sync.Mutex
requestId uint32
Greeting *Greeting
requests map[uint32]*Future
packets chan []byte
control chan struct{}
opts Opts
closed bool
}
type Greeting struct {
version string
auth string
}
type Opts struct {
Timeout time.Duration // milliseconds
Reconnect time.Duration // milliseconds
MaxReconnects uint
User string
Pass string
}
func Connect(addr string, opts Opts) (conn *Connection, err error) {
conn = &Connection{
addr: addr,
mutex: &sync.Mutex{},
requestId: 0,
Greeting: &Greeting{},
requests: make(map[uint32]*Future),
packets: make(chan []byte, 64),
control: make(chan struct{}),
opts: opts,
}
var reconnect time.Duration
// disable reconnecting for first connect
reconnect, conn.opts.Reconnect = conn.opts.Reconnect, 0
_, _, err = conn.createConnection()
conn.opts.Reconnect = reconnect
if err != nil && reconnect == 0 {
return nil, err
}
go conn.writer()
go conn.reader()
return conn, err
}
func (conn *Connection) Close() (err error) {
conn.closed = true
close(conn.control)
err = conn.closeConnection(errors.New("client closed connection"))
return
}
func (conn *Connection) RemoteAddr() string {
conn.mutex.Lock()
defer conn.mutex.Unlock()
if conn.c == nil {
return ""
}
return conn.c.RemoteAddr().String()
}
func (conn *Connection) LocalAddr() string {
conn.mutex.Lock()
defer conn.mutex.Unlock()
if conn.c == nil {
return ""
}
return conn.c.LocalAddr().String()
}
func (conn *Connection) dial() (err error) {
connection, err := net.Dial("tcp", conn.addr)
if err != nil {
return
}
c := connection.(*net.TCPConn)
c.SetNoDelay(true)
r := bufio.NewReaderSize(c, 128*1024)
w := bufio.NewWriter(c)
greeting := make([]byte, 128)
_, err = io.ReadFull(r, greeting)
if err != nil {
c.Close()
return
}
conn.Greeting.version = bytes.NewBuffer(greeting[:64]).String()
conn.Greeting.auth = bytes.NewBuffer(greeting[64:108]).String()
// Auth
if conn.opts.User != "" {
scr, err := scramble(conn.Greeting.auth, conn.opts.Pass)
if err != nil {
err = errors.New("auth: scrambling failure " + err.Error())
c.Close()
return err
}
if err = conn.writeAuthRequest(w, scr); err != nil {
c.Close()
return err
}
if err = conn.readAuthResponse(r); err != nil {
c.Close()
return err
}
}
// Only if connected and authenticated
conn.c = c
conn.r = r
conn.w = w
return
}
func (conn *Connection) writeAuthRequest(w *bufio.Writer, scramble []byte) (err error) {
request := conn.NewRequest(AuthRequest)
request.body[KeyUserName] = conn.opts.User
request.body[KeyTuple] = []interface{}{string("chap-sha1"), string(scramble)}
packet, err := request.pack()
if err != nil {
return errors.New("auth: pack error " + err.Error())
}
if err := write(w, packet); err != nil {
return errors.New("auth: write error " + err.Error())
}
if err = w.Flush(); err != nil {
return errors.New("auth: flush error " + err.Error())
}
return
}
func (conn *Connection) readAuthResponse(r io.Reader) (err error) {
resp_bytes, err := read(r)
if err != nil {
return errors.New("auth: read error " + err.Error())
}
resp := Response{buf: smallBuf{b: resp_bytes}}
err = resp.decodeHeader()
if err != nil {
return errors.New("auth: decode response header error " + err.Error())
}
err = resp.decodeBody()
if err != nil {
switch err.(type) {
case Error:
return err
default:
return errors.New("auth: decode response body error " + err.Error())
}
}
return
}
func (conn *Connection) createConnection() (r *bufio.Reader, w *bufio.Writer, err error) {
conn.mutex.Lock()
defer conn.mutex.Unlock()
if conn.closed {
err = errors.New("connection already closed")
return
}
if conn.c == nil {
var reconnects uint
for {
err = conn.dial()
if err == nil {
break
} else if conn.opts.Reconnect > 0 {
if conn.opts.MaxReconnects > 0 && reconnects > conn.opts.MaxReconnects {
log.Printf("tarantool: last reconnect to %s failed: %s, giving it up.\n", conn.addr, err.Error())
return
} else {
log.Printf("tarantool: reconnect (%d/%d) to %s failed: %s\n", reconnects, conn.opts.MaxReconnects, conn.addr, err.Error())
reconnects += 1
time.Sleep(conn.opts.Reconnect)
continue
}
} else {
return
}
}
}
r = conn.r
w = conn.w
return
}
func (conn *Connection) closeConnection(neterr error) (err error) {
conn.mutex.Lock()
defer conn.mutex.Unlock()
if conn.c == nil {
return
}
err = conn.c.Close()
conn.c = nil
conn.r = nil
conn.w = nil
for rid, fut := range conn.requests {
fut.err = neterr
close(fut.c)
delete(conn.requests, rid)
}
return
}
func (conn *Connection) writer() {
var w *bufio.Writer
var err error
for {
var packet []byte
select {
case packet = <-conn.packets:
default:
if w = conn.w; w != nil {
if err := w.Flush(); err != nil {
conn.closeConnection(err)
}
}
select {
case packet = <-conn.packets:
case <-conn.control:
return
}
}
if packet == nil {
return
}
if w = conn.w; w == nil {
if _, w, err = conn.createConnection(); err != nil {
return
}
}
if err := write(w, packet); err != nil {
conn.closeConnection(err)
continue
}
}
}
func (conn *Connection) reader() {
var r *bufio.Reader
var err error
for {
if r = conn.r; r == nil {
if r, _, err = conn.createConnection(); err != nil {
return
}
}
resp_bytes, err := read(r)
if err != nil {
conn.closeConnection(err)
continue
}
resp := Response{buf: smallBuf{b: resp_bytes}}
err = resp.decodeHeader()
//resp, err := newResponse(resp_bytes)
if err != nil {
conn.closeConnection(err)
continue
}
conn.mutex.Lock()
if fut, ok := conn.requests[resp.RequestId]; ok {
delete(conn.requests, resp.RequestId)
fut.resp = resp
close(fut.c)
conn.mutex.Unlock()
} else {
conn.mutex.Unlock()
log.Printf("tarantool: unexpected requestId (%d) in response", uint(resp.RequestId))
}
}
}
func write(w io.Writer, data []byte) (err error) {
l, err := w.Write(data)
if err != nil {
return
}
if l != len(data) {
panic("Wrong length writed")
}
return
}
func read(r io.Reader) (response []byte, err error) {
var lenbuf [PacketLengthBytes]byte
var length int
if _, err = io.ReadFull(r, lenbuf[:]); err != nil {
return
}
if lenbuf[0] != 0xce {
err = errors.New("Wrong reponse header")
return
}
length = (int(lenbuf[1]) << 24) +
(int(lenbuf[2]) << 16) +
(int(lenbuf[3]) << 8) +
int(lenbuf[4])
if length == 0 {
err = errors.New("Response should not be 0 length")
return
}
response = make([]byte, length)
_, err = io.ReadFull(r, response)
return
}
func (conn *Connection) nextRequestId() (requestId uint32) {
return atomic.AddUint32(&conn.requestId, 1)
}