-
Notifications
You must be signed in to change notification settings - Fork 0
/
gqtp.go
479 lines (444 loc) · 11.2 KB
/
gqtp.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
package grnci
import (
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"net"
"strings"
"time"
)
// Constants for gqtpHeader.
const (
gqtpProtocol = byte(0xc7)
// gqtpQueryTypeNone = byte(0)
// gqtpQueryTypeTSV = byte(1)
// gqtpQueryTypeJSON = byte(2)
// gqtpQueryTypeXML = byte(3)
// gqtpQueryTypeMsgPack = byte(4)
// gqtpFlagMore = byte(0x01)
gqtpFlagTail = byte(0x02)
// gqtpFlagHead = byte(0x04)
// gqtpFlagQuiet = byte(0x08)
// gqtpFlagQuit = byte(0x10)
)
const (
gqtpMaxChunkSize = 1 << 30 // Maximum chunk size
gqtpDefaultBufferSize = 1 << 16 // Default buffer size
gqtpMaxIdleConns = 2 // Maximum number of idle connections
)
// gqtpHeader is a GQTP header.
type gqtpHeader struct {
Protocol byte // Must be 0xc7
QueryType byte // Body type
KeyLength uint16 // Unused
Level byte // Unused
Flags byte // Flags
Status uint16 // Return code
Size uint32 // Body size
Opaque uint32 // Unused
CAS uint64 // Unused
}
// gqtpResponse is a GQTP response.
type gqtpResponse struct {
client *GQTPClient // Client
conn *GQTPConn // Connection
head gqtpHeader // Current header
start time.Time // Start time
elapsed time.Duration // Elapsed time
err error // Error response
left int // Number of bytes left in the current chunk
broken bool // Whether or not the connection is broken
closed bool // Whether or not the response is closed
}
// newGQTPResponse returns a new GQTP response.
func newGQTPResponse(conn *GQTPConn, head gqtpHeader, start time.Time, name string) *gqtpResponse {
resp := &gqtpResponse{
conn: conn,
head: head,
start: start,
elapsed: time.Now().Sub(start),
left: int(head.Size),
}
if head.Status > 32767 {
status := int(head.Status) - 65536
resp.err = NewError(status, nil)
if _, ok := CommandRules[name]; !ok {
data, err := ioutil.ReadAll(resp)
if err != nil {
resp.broken = true
} else {
resp.err = EnhanceError(resp.err, map[string]interface{}{
"error": string(data),
})
}
}
}
return resp
}
func (r *gqtpResponse) Status() int {
if err, ok := r.err.(*Error); ok {
return err.Code
}
return 0
}
func (r *gqtpResponse) Start() time.Time {
return r.start
}
func (r *gqtpResponse) Elapsed() time.Duration {
return r.elapsed
}
func (r *gqtpResponse) Read(p []byte) (int, error) {
if r.closed {
return 0, io.EOF
}
for r.left == 0 {
if r.head.Flags&gqtpFlagTail != 0 {
return 0, io.EOF
}
head, err := r.conn.recvHeader()
if err != nil {
r.broken = true
return 0, err
}
r.head = head
r.left = int(head.Size)
}
if r.left < len(p) {
p = p[:r.left]
}
n, err := r.conn.conn.Read(p)
r.left -= n
if err == io.EOF {
return n, io.EOF
}
if err != nil {
r.broken = true
return n, NewError(StatusNetworkError, map[string]interface{}{
"method": "net.Conn.Read",
"n": n,
"error": err.Error(),
})
}
return n, nil
}
func (r *gqtpResponse) Close() error {
if r.closed {
return nil
}
var err error
if _, e := io.CopyBuffer(ioutil.Discard, r, r.conn.getBuffer()); e != nil {
r.broken = true
err = NewError(StatusNetworkError, map[string]interface{}{
"method": "io.CopyBuffer",
"error": err.Error(),
})
}
r.closed = true
if err == nil {
r.conn.ready = true
}
if r.client != nil {
// Broken connections are closed.
if r.broken {
if e := r.conn.Close(); e != nil && err != nil {
err = e
}
}
select {
case r.client.idleConns <- r.conn:
default:
if e := r.conn.Close(); e != nil && err != nil {
err = e
}
}
}
return err
}
func (r *gqtpResponse) Err() error {
return r.err
}
// GQTPConn is a thread-unsafe GQTP client.
type GQTPConn struct {
conn net.Conn // Connection to a GQTP server
buf []byte // Copy buffer
bufSize int // Copy buffer size
ready bool // Whether or not Exec and Query are ready
}
// DialGQTP returns a new GQTPConn connected to a GQTP server.
// The expected address format is [scheme://][host][:port].
func DialGQTP(addr string) (*GQTPConn, error) {
a, err := ParseGQTPAddress(addr)
if err != nil {
return nil, err
}
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", a.Host, a.Port))
if err != nil {
return nil, NewError(StatusNetworkError, map[string]interface{}{
"host": a.Host,
"port": a.Port,
"error": err.Error(),
})
}
return NewGQTPConn(conn), nil
}
// NewGQTPConn returns a new GQTPConn using an existing connection.
func NewGQTPConn(conn net.Conn) *GQTPConn {
return &GQTPConn{
conn: conn,
bufSize: gqtpDefaultBufferSize,
ready: true,
}
}
// Close closes the connection.
func (c *GQTPConn) Close() error {
if err := c.conn.Close(); err != nil {
return NewError(StatusNetworkError, map[string]interface{}{
"method": "net.Conn.Close",
"error": err.Error(),
})
}
return nil
}
// SetBufferSize updates the size of the copy buffer.
func (c *GQTPConn) SetBufferSize(n int) {
if n <= 0 || n > gqtpMaxChunkSize {
n = gqtpDefaultBufferSize
}
c.bufSize = n
}
// getBuffer returns the copy buffer.
func (c *GQTPConn) getBuffer() []byte {
if len(c.buf) != c.bufSize {
c.buf = make([]byte, c.bufSize)
}
return c.buf
}
// sendHeader sends a GQTP header.
func (c *GQTPConn) sendHeader(flags byte, size int) error {
head := gqtpHeader{
Protocol: gqtpProtocol,
Flags: flags,
Size: uint32(size),
}
if err := binary.Write(c.conn, binary.BigEndian, head); err != nil {
return NewError(StatusNetworkError, map[string]interface{}{
"method": "binary.Write",
"error": err.Error(),
})
}
return nil
}
// sendChunkBytes sends data with flags.
func (c *GQTPConn) sendChunkBytes(data []byte, flags byte) error {
if err := c.sendHeader(flags, len(data)); err != nil {
return err
}
if _, err := c.conn.Write(data); err != nil {
return NewError(StatusNetworkError, map[string]interface{}{
"method": "net.Conn.Write",
"error": err.Error(),
})
}
return nil
}
// sendChunkString sends data with flags.
func (c *GQTPConn) sendChunkString(data string, flags byte) error {
if err := c.sendHeader(flags, len(data)); err != nil {
return err
}
if _, err := io.WriteString(c.conn, data); err != nil {
return NewError(StatusNetworkError, map[string]interface{}{
"method": "io.WriteString",
"error": err.Error(),
})
}
return nil
}
// recvHeader receives a GQTP header.
func (c *GQTPConn) recvHeader() (gqtpHeader, error) {
var head gqtpHeader
if err := binary.Read(c.conn, binary.BigEndian, &head); err != nil {
return head, NewError(StatusNetworkError, map[string]interface{}{
"method": "binary.Read",
"error": err.Error(),
})
}
return head, nil
}
// exec sends a command without body and receives a response.
func (c *GQTPConn) exec(cmd string) (Response, error) {
start := time.Now()
name := strings.TrimLeft(cmd, " \t\r\n")
if idx := strings.IndexAny(name, " \t\r\n"); idx != -1 {
name = name[:idx]
}
if err := c.sendChunkString(cmd, gqtpFlagTail); err != nil {
return nil, err
}
head, err := c.recvHeader()
if err != nil {
return nil, err
}
return newGQTPResponse(c, head, start, name), nil
}
// execBody sends a command with body and receives a response.
func (c *GQTPConn) execBody(cmd string, body io.Reader) (Response, error) {
start := time.Now()
name := strings.TrimLeft(cmd, " \t\r\n")
if idx := strings.IndexAny(name, " \t\r\n"); idx != -1 {
name = name[:idx]
}
if err := c.sendChunkString(cmd, 0); err != nil {
return nil, err
}
head, err := c.recvHeader()
if err != nil {
return nil, err
}
if head.Status != 0 || head.Size != 0 {
return newGQTPResponse(c, head, start, name), nil
}
n := 0
buf := c.getBuffer()
for {
m, err := body.Read(buf[n:])
n += m
if err != nil {
if err := c.sendChunkBytes(buf[:n], gqtpFlagTail); err != nil {
return nil, err
}
head, err = c.recvHeader()
if err != nil {
return nil, err
}
return newGQTPResponse(c, head, start, name), nil
}
if n == len(buf) {
if err := c.sendChunkBytes(buf, 0); err != nil {
return nil, err
}
head, err = c.recvHeader()
if err != nil {
return nil, err
}
if head.Status != 0 || head.Size != 0 {
return newGQTPResponse(c, head, start, name), nil
}
n = 0
}
}
}
// Exec sends a request and receives a response.
// It is the caller's responsibility to close the response.
// The GQTPConn should not be used until the response is closed.
func (c *GQTPConn) Exec(cmd string, body io.Reader) (Response, error) {
if !c.ready {
return nil, NewError(StatusInvalidOperation, map[string]interface{}{
"error": "The connection is not ready to send a request.",
})
}
if len(cmd) > gqtpMaxChunkSize {
return nil, NewError(StatusInvalidCommand, map[string]interface{}{
"length": len(cmd),
"error": "The command is too long.",
})
}
c.ready = false
if body == nil {
return c.exec(cmd)
}
return c.execBody(cmd, body)
}
// Invoke assembles cmd, params and body into a Request and calls Query.
func (c *GQTPConn) Invoke(cmd string, params map[string]interface{}, body io.Reader) (Response, error) {
req, err := NewRequest(cmd, params, body)
if err != nil {
return nil, err
}
return c.Query(req)
}
// Query calls Exec with req.GQTPRequest and returns the result.
func (c *GQTPConn) Query(req *Request) (Response, error) {
cmd, body, err := req.GQTPRequest()
if err != nil {
return nil, err
}
return c.Exec(cmd, body)
}
// GQTPClient is a thread-safe GQTP client.
type GQTPClient struct {
addr *Address
idleConns chan *GQTPConn
}
// NewGQTPClient returns a new GQTPClient connected to a GQTP server.
// The expected address format is [scheme://][host][:port].
func NewGQTPClient(addr string) (*GQTPClient, error) {
a, err := ParseGQTPAddress(addr)
if err != nil {
return nil, err
}
conn, err := DialGQTP(addr)
if err != nil {
return nil, err
}
conns := make(chan *GQTPConn, gqtpMaxIdleConns)
conns <- conn
return &GQTPClient{
addr: a,
idleConns: conns,
}, nil
}
// Close closes the idle connections.
// Close should be called after all responses are closed.
// Otherwise, connections will be leaked.
func (c *GQTPClient) Close() error {
var err error
for {
select {
case conn := <-c.idleConns:
if e := conn.Close(); e != nil && err == nil {
err = e
}
default:
return err
}
}
}
// Exec sends a request and receives a response.
// It is the caller's responsibility to close the response.
func (c *GQTPClient) Exec(cmd string, body io.Reader) (Response, error) {
var conn *GQTPConn
var err error
select {
case conn = <-c.idleConns:
default:
conn, err = DialGQTP(c.addr.String())
if err != nil {
return nil, err
}
}
resp, err := conn.Exec(cmd, body)
if err != nil {
conn.Close()
return nil, err
}
resp.(*gqtpResponse).client = c
return resp, nil
}
// Invoke assembles cmd, params and body into a Request and calls Query.
func (c *GQTPClient) Invoke(cmd string, params map[string]interface{}, body io.Reader) (Response, error) {
req, err := NewRequest(cmd, params, body)
if err != nil {
return nil, err
}
return c.Query(req)
}
// Query calls Exec with req.GQTPRequest and returns the result.
func (c *GQTPClient) Query(req *Request) (Response, error) {
cmd, body, err := req.GQTPRequest()
if err != nil {
return nil, err
}
return c.Exec(cmd, body)
}