forked from flike/kingshard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend_conn.go
724 lines (556 loc) · 13.8 KB
/
backend_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
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
// Copyright 2016 The kingshard Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package backend
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"net"
"strings"
"time"
"github.com/flike/kingshard/mysql"
)
var (
pingPeriod = int64(time.Second * 16)
)
//proxy <-> mysql server
type Conn struct {
conn net.Conn
pkg *mysql.PacketIO
addr string
user string
password string
db string
capability uint32
status uint16
collation mysql.CollationId
charset string
salt []byte
pushTimestamp int64
pkgErr error
}
func (c *Conn) Connect(addr string, user string, password string, db string) error {
c.addr = addr
c.user = user
c.password = password
c.db = db
//use utf8
c.collation = mysql.DEFAULT_COLLATION_ID
c.charset = mysql.DEFAULT_CHARSET
return c.ReConnect()
}
func (c *Conn) ReConnect() error {
if c.conn != nil {
c.conn.Close()
}
n := "tcp"
if strings.Contains(c.addr, "/") {
n = "unix"
}
netConn, err := net.Dial(n, c.addr)
if err != nil {
return err
}
tcpConn := netConn.(*net.TCPConn)
//SetNoDelay controls whether the operating system should delay packet transmission
// in hopes of sending fewer packets (Nagle's algorithm).
// The default is true (no delay),
// meaning that data is sent as soon as possible after a Write.
//I set this option false.
tcpConn.SetNoDelay(false)
tcpConn.SetKeepAlive(true)
c.conn = tcpConn
c.pkg = mysql.NewPacketIO(tcpConn)
if err := c.readInitialHandshake(); err != nil {
c.conn.Close()
return err
}
if err := c.writeAuthHandshake(); err != nil {
c.conn.Close()
return err
}
if _, err := c.readOK(); err != nil {
c.conn.Close()
return err
}
//we must always use autocommit
if !c.IsAutoCommit() {
if _, err := c.exec("set autocommit = 1"); err != nil {
c.conn.Close()
return err
}
}
return nil
}
func (c *Conn) Close() error {
if c.conn != nil {
c.conn.Close()
c.conn = nil
c.salt = nil
c.pkgErr = nil
}
return nil
}
func (c *Conn) readPacket() ([]byte, error) {
d, err := c.pkg.ReadPacket()
c.pkgErr = err
return d, err
}
func (c *Conn) writePacket(data []byte) error {
err := c.pkg.WritePacket(data)
c.pkgErr = err
return err
}
func (c *Conn) readInitialHandshake() error {
data, err := c.readPacket()
if err != nil {
return err
}
if data[0] == mysql.ERR_HEADER {
return errors.New("read initial handshake error")
}
if data[0] < mysql.MinProtocolVersion {
return fmt.Errorf("invalid protocol version %d, must >= 10", data[0])
}
//skip mysql version and connection id
//mysql version end with 0x00
//connection id length is 4
pos := 1 + bytes.IndexByte(data[1:], 0x00) + 1 + 4
c.salt = append(c.salt, data[pos:pos+8]...)
//skip filter
pos += 8 + 1
//capability lower 2 bytes
c.capability = uint32(binary.LittleEndian.Uint16(data[pos : pos+2]))
pos += 2
if len(data) > pos {
//skip server charset
//c.charset = data[pos]
pos += 1
c.status = binary.LittleEndian.Uint16(data[pos : pos+2])
pos += 2
c.capability = uint32(binary.LittleEndian.Uint16(data[pos:pos+2]))<<16 | c.capability
pos += 2
//skip auth data len or [00]
//skip reserved (all [00])
pos += 10 + 1
// The documentation is ambiguous about the length.
// The official Python library uses the fixed length 12
// mysql-proxy also use 12
// which is not documented but seems to work.
c.salt = append(c.salt, data[pos:pos+12]...)
}
return nil
}
func (c *Conn) writeAuthHandshake() error {
// Adjust client capability flags based on server support
capability := mysql.CLIENT_PROTOCOL_41 | mysql.CLIENT_SECURE_CONNECTION |
mysql.CLIENT_LONG_PASSWORD | mysql.CLIENT_TRANSACTIONS | mysql.CLIENT_LONG_FLAG
capability &= c.capability
//packet length
//capbility 4
//max-packet size 4
//charset 1
//reserved all[0] 23
length := 4 + 4 + 1 + 23
//username
length += len(c.user) + 1
//we only support secure connection
auth := mysql.CalcPassword(c.salt, []byte(c.password))
length += 1 + len(auth)
if len(c.db) > 0 {
capability |= mysql.CLIENT_CONNECT_WITH_DB
length += len(c.db) + 1
}
c.capability = capability
data := make([]byte, length+4)
//capability [32 bit]
data[4] = byte(capability)
data[5] = byte(capability >> 8)
data[6] = byte(capability >> 16)
data[7] = byte(capability >> 24)
//MaxPacketSize [32 bit] (none)
//data[8] = 0x00
//data[9] = 0x00
//data[10] = 0x00
//data[11] = 0x00
//Charset [1 byte]
data[12] = byte(c.collation)
//Filler [23 bytes] (all 0x00)
pos := 13 + 23
//User [null terminated string]
if len(c.user) > 0 {
pos += copy(data[pos:], c.user)
}
//data[pos] = 0x00
pos++
// auth [length encoded integer]
data[pos] = byte(len(auth))
pos += 1 + copy(data[pos+1:], auth)
// db [null terminated string]
if len(c.db) > 0 {
pos += copy(data[pos:], c.db)
//data[pos] = 0x00
}
return c.writePacket(data)
}
func (c *Conn) writeCommand(command byte) error {
c.pkg.Sequence = 0
return c.writePacket([]byte{
0x01, //1 bytes long
0x00,
0x00,
0x00, //sequence
command,
})
}
func (c *Conn) writeCommandBuf(command byte, arg []byte) error {
c.pkg.Sequence = 0
length := len(arg) + 1
data := make([]byte, length+4)
data[4] = command
copy(data[5:], arg)
return c.writePacket(data)
}
func (c *Conn) writeCommandStr(command byte, arg string) error {
c.pkg.Sequence = 0
length := len(arg) + 1
data := make([]byte, length+4)
data[4] = command
copy(data[5:], arg)
return c.writePacket(data)
}
func (c *Conn) writeCommandUint32(command byte, arg uint32) error {
c.pkg.Sequence = 0
return c.writePacket([]byte{
0x05, //5 bytes long
0x00,
0x00,
0x00, //sequence
command,
byte(arg),
byte(arg >> 8),
byte(arg >> 16),
byte(arg >> 24),
})
}
func (c *Conn) writeCommandStrStr(command byte, arg1 string, arg2 string) error {
c.pkg.Sequence = 0
data := make([]byte, 4, 6+len(arg1)+len(arg2))
data = append(data, command)
data = append(data, arg1...)
data = append(data, 0)
data = append(data, arg2...)
return c.writePacket(data)
}
func (c *Conn) Ping() error {
if err := c.writeCommand(mysql.COM_PING); err != nil {
return err
}
if _, err := c.readOK(); err != nil {
return err
}
c.pushTimestamp = time.Now().Unix()
return nil
}
func (c *Conn) UseDB(dbName string) error {
if c.db == dbName || len(dbName) == 0 {
return nil
}
if err := c.writeCommandStr(mysql.COM_INIT_DB, dbName); err != nil {
return err
}
if _, err := c.readOK(); err != nil {
return err
}
c.db = dbName
return nil
}
func (c *Conn) GetDB() string {
return c.db
}
func (c *Conn) GetAddr() string {
return c.addr
}
func (c *Conn) Execute(command string, args ...interface{}) (*mysql.Result, error) {
if len(args) == 0 {
return c.exec(command)
} else {
if s, err := c.Prepare(command); err != nil {
return nil, err
} else {
var r *mysql.Result
r, err = s.Execute(args...)
s.Close()
return r, err
}
}
}
func (c *Conn) ClosePrepare(id uint32) error {
return c.writeCommandUint32(mysql.COM_STMT_CLOSE, id)
}
func (c *Conn) Begin() error {
_, err := c.exec("begin")
return err
}
func (c *Conn) Commit() error {
_, err := c.exec("commit")
return err
}
func (c *Conn) Rollback() error {
_, err := c.exec("rollback")
return err
}
func (c *Conn) SetAutoCommit(n uint8) error {
if n == 0 {
if _, err := c.exec("set autocommit = 0"); err != nil {
c.conn.Close()
return err
}
} else {
if _, err := c.exec("set autocommit = 1"); err != nil {
c.conn.Close()
return err
}
}
return nil
}
func (c *Conn) SetCharset(charset string, collation mysql.CollationId) error {
charset = strings.Trim(charset, "\"'`")
if collation == 0 {
collation = mysql.CollationNames[mysql.Charsets[charset]]
}
if c.charset == charset && c.collation == collation {
return nil
}
_, ok := mysql.CharsetIds[charset]
if !ok {
return fmt.Errorf("invalid charset %s", charset)
}
_, ok = mysql.Collations[collation]
if !ok {
return fmt.Errorf("invalid collation %s", collation)
}
if _, err := c.exec(fmt.Sprintf("SET NAMES %s COLLATE %s", charset, mysql.Collations[collation])); err != nil {
return err
} else {
c.collation = collation
c.charset = charset
return nil
}
}
func (c *Conn) FieldList(table string, wildcard string) ([]*mysql.Field, error) {
if err := c.writeCommandStrStr(mysql.COM_FIELD_LIST, table, wildcard); err != nil {
return nil, err
}
data, err := c.readPacket()
if err != nil {
return nil, err
}
fs := make([]*mysql.Field, 0, 4)
var f *mysql.Field
if data[0] == mysql.ERR_HEADER {
return nil, c.handleErrorPacket(data)
} else {
for {
if data, err = c.readPacket(); err != nil {
return nil, err
}
// EOF Packet
if c.isEOFPacket(data) {
return fs, nil
}
if f, err = mysql.FieldData(data).Parse(); err != nil {
return nil, err
}
fs = append(fs, f)
}
}
return nil, fmt.Errorf("field list error")
}
func (c *Conn) exec(query string) (*mysql.Result, error) {
if err := c.writeCommandStr(mysql.COM_QUERY, query); err != nil {
return nil, err
}
return c.readResult(false)
}
func (c *Conn) readResultset(data []byte, binary bool) (*mysql.Result, error) {
result := &mysql.Result{
Status: 0,
InsertId: 0,
AffectedRows: 0,
Resultset: &mysql.Resultset{},
}
// column count
count, _, n := mysql.LengthEncodedInt(data)
if n-len(data) != 0 {
return nil, mysql.ErrMalformPacket
}
result.Fields = make([]*mysql.Field, count)
result.FieldNames = make(map[string]int, count)
if err := c.readResultColumns(result); err != nil {
return nil, err
}
if err := c.readResultRows(result, binary); err != nil {
return nil, err
}
return result, nil
}
func (c *Conn) readResultColumns(result *mysql.Result) (err error) {
var i int = 0
var data []byte
for {
data, err = c.readPacket()
if err != nil {
return
}
// EOF Packet
if c.isEOFPacket(data) {
if c.capability&mysql.CLIENT_PROTOCOL_41 > 0 {
//result.Warnings = binary.LittleEndian.Uint16(data[1:])
//todo add strict_mode, warning will be treat as error
result.Status = binary.LittleEndian.Uint16(data[3:])
c.status = result.Status
}
if i != len(result.Fields) {
err = mysql.ErrMalformPacket
}
return
}
result.Fields[i], err = mysql.FieldData(data).Parse()
if err != nil {
return
}
result.FieldNames[string(result.Fields[i].Name)] = i
i++
}
}
func (c *Conn) readResultRows(result *mysql.Result, isBinary bool) (err error) {
var data []byte
for {
data, err = c.readPacket()
if err != nil {
return
}
// EOF Packet
if c.isEOFPacket(data) {
if c.capability&mysql.CLIENT_PROTOCOL_41 > 0 {
//result.Warnings = binary.LittleEndian.Uint16(data[1:])
//todo add strict_mode, warning will be treat as error
result.Status = binary.LittleEndian.Uint16(data[3:])
c.status = result.Status
}
break
}
result.RowDatas = append(result.RowDatas, data)
}
result.Values = make([][]interface{}, len(result.RowDatas))
for i := range result.Values {
result.Values[i], err = result.RowDatas[i].Parse(result.Fields, isBinary)
if err != nil {
return err
}
}
return nil
}
func (c *Conn) readUntilEOF() (err error) {
var data []byte
for {
data, err = c.readPacket()
if err != nil {
return
}
// EOF Packet
if c.isEOFPacket(data) {
return
}
}
return
}
func (c *Conn) isEOFPacket(data []byte) bool {
return data[0] == mysql.EOF_HEADER && len(data) <= 5
}
func (c *Conn) handleOKPacket(data []byte) (*mysql.Result, error) {
var n int
var pos int = 1
r := new(mysql.Result)
r.AffectedRows, _, n = mysql.LengthEncodedInt(data[pos:])
pos += n
r.InsertId, _, n = mysql.LengthEncodedInt(data[pos:])
pos += n
if c.capability&mysql.CLIENT_PROTOCOL_41 > 0 {
r.Status = binary.LittleEndian.Uint16(data[pos:])
c.status = r.Status
pos += 2
//todo:strict_mode, check warnings as error
//Warnings := binary.LittleEndian.Uint16(data[pos:])
//pos += 2
} else if c.capability&mysql.CLIENT_TRANSACTIONS > 0 {
r.Status = binary.LittleEndian.Uint16(data[pos:])
c.status = r.Status
pos += 2
}
//info
return r, nil
}
func (c *Conn) handleErrorPacket(data []byte) error {
e := new(mysql.SqlError)
var pos int = 1
e.Code = binary.LittleEndian.Uint16(data[pos:])
pos += 2
if c.capability&mysql.CLIENT_PROTOCOL_41 > 0 {
//skip '#'
pos++
e.State = string(data[pos : pos+5])
pos += 5
}
e.Message = string(data[pos:])
return e
}
func (c *Conn) readOK() (*mysql.Result, error) {
data, err := c.readPacket()
if err != nil {
return nil, err
}
if data[0] == mysql.OK_HEADER {
return c.handleOKPacket(data)
} else if data[0] == mysql.ERR_HEADER {
return nil, c.handleErrorPacket(data)
} else {
return nil, errors.New("invalid ok packet")
}
}
func (c *Conn) readResult(binary bool) (*mysql.Result, error) {
data, err := c.readPacket()
if err != nil {
return nil, err
}
if data[0] == mysql.OK_HEADER {
return c.handleOKPacket(data)
} else if data[0] == mysql.ERR_HEADER {
return nil, c.handleErrorPacket(data)
} else if data[0] == mysql.LocalInFile_HEADER {
return nil, mysql.ErrMalformPacket
}
return c.readResultset(data, binary)
}
func (c *Conn) IsAutoCommit() bool {
return c.status&mysql.SERVER_STATUS_AUTOCOMMIT > 0
}
func (c *Conn) IsInTransaction() bool {
return c.status&mysql.SERVER_STATUS_IN_TRANS > 0
}
func (c *Conn) GetCharset() string {
return c.charset
}