-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
245 lines (210 loc) · 5.25 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
package mconn
import (
"bufio"
"bytes"
"crypto/tls"
"fmt"
"io"
"net"
"sync"
"time"
"github.com/juju/errors"
)
const (
_ = iota
connStatusConnected
connStatusClosed
)
const (
badConnErrDesc = "bad connection: "
maxPayloadLength = 1<<24 - 1
)
var (
// ErrMalformPacket represents a response with the unknown header
ErrMalformPacket = errors.New("Malform packet format")
)
type responseOptions struct {
binary bool
}
// HandshakeInfo represents the mysql server information returned by handshake
type HandshakeInfo struct {
ProtoVersion byte
ServerVersion string
ConnectionID uint32
}
func (i *HandshakeInfo) String() string {
return fmt.Sprintf("Protocol version:%d Server version:%s Connection id:%d",
i.ProtoVersion, i.ServerVersion, i.ConnectionID)
}
// Conn is a connection communicate with the mysql server
type Conn struct {
ds *DataSource
mu sync.Mutex
status int64
lastErr error
conn net.Conn
r io.Reader
seq uint8
capability uint32
loc *time.Location
si HandshakeInfo
rc *ReplicationConfig
readTimeout time.Duration
// TODO: support tls
tlsConfig *tls.Config
}
// GetStatus returns the status of the connection
func (c *Conn) GetStatus() int64 {
c.mu.Lock()
s := c.status
c.mu.Unlock()
return s
}
// SetKeepalive enables the tcp keepalive
func (c *Conn) SetKeepalive(d time.Duration) bool {
if tcpconn, ok := c.conn.(*net.TCPConn); ok {
tcpconn.SetKeepAlive(true)
tcpconn.SetKeepAlivePeriod(d)
return true
}
return false
}
// GetHandshakeInfo get the server information by handshake
func (c *Conn) GetHandshakeInfo(si *HandshakeInfo) {
*si = c.si
}
func (c *Conn) setStatus(v int64) {
c.mu.Lock()
c.status = v
c.mu.Unlock()
}
// Close the connection
func (c *Conn) Close() {
c.mu.Lock()
c.close()
c.mu.Unlock()
}
func (c *Conn) close() {
if c.status == connStatusConnected &&
c.conn != nil {
c.conn.Close()
c.status = connStatusClosed
}
}
// Connect connects to the mysql server
func (c *Conn) Connect(ds *DataSource, database string) error {
c.mu.Lock()
c.ds = ds
if c.status == connStatusConnected {
c.mu.Unlock()
return errors.New("already connected")
}
// Create connection
conn, err := net.DialTimeout("tcp", ds.Address(), time.Second*10)
if nil != err {
c.mu.Unlock()
return errors.Trace(err)
}
c.conn = conn
c.r = bufio.NewReader(c)
c.status = connStatusConnected
c.resetSequence()
// Receive handshake from server
if err = c.handshake(ds.Username, ds.Password, database); nil != err {
c.close()
c.mu.Unlock()
return errors.Trace(err)
}
c.mu.Unlock()
return nil
}
// SetReadTimeout set the read timeout duration
func (c *Conn) SetReadTimeout(dura time.Duration) {
c.readTimeout = dura
}
// Read implement io.Reader interface
func (c *Conn) Read(p []byte) (n int, err error) {
if 0 != c.readTimeout {
c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
}
n, err = c.conn.Read(p)
if 0 != c.readTimeout {
c.conn.SetReadDeadline(time.Time{})
}
return
}
// WritePacket writes the packet to mysql, data must has 4 bytes unused in head
func (c *Conn) WritePacket(data []byte) error {
var header PacketHeader
dl := len(data) - 4
for dl >= maxPayloadLength {
header.SetLength(0x00ffffff)
header.SetSequence(c.seq)
copy(data[:], header.ToSlice())
if n, err := c.conn.Write(data[:maxPayloadLength+4]); nil != err {
return errors.Annotate(err, badConnErrDesc)
} else if n != maxPayloadLength+4 {
return errors.Errorf("%s%s", badConnErrDesc, "send bytes not equal")
} else {
c.seq++
dl -= maxPayloadLength
// Next round the position is before the actual payload data
data = data[maxPayloadLength:]
}
}
header.SetLength(dl)
header.SetSequence(c.seq)
copy(data[:], header.ToSlice())
if n, err := c.conn.Write(data[:]); nil != err {
return errors.Annotate(err, badConnErrDesc)
} else if n != dl+4 {
return errors.Errorf("%s%s", badConnErrDesc, "send bytes not equal")
} else {
c.seq++
}
return nil
}
// ReadPacket reads the full packet from mysql
func (c *Conn) ReadPacket() ([]byte, error) {
var buf bytes.Buffer
if err := c.readFullPacket(&buf); nil != err {
return nil, errors.Trace(err)
}
return buf.Bytes(), nil
}
func (c *Conn) readFullPacket(w io.Writer) error {
var err error
var header PacketHeader
if _, err = io.ReadFull(c.r, header.ToSlice()[:]); nil != err {
return errors.Annotatef(err, badConnErrDesc)
}
length := int64(header.GetLength())
if length < 1 {
return errors.Errorf("invalid packet length %v", length)
}
seq := header.GetSequence()
if seq != c.seq {
//return errors.Errorf("connection sequence mismatch, conn = %v, packet = %v", c.seq, seq)
}
// Once receive the packet, increase the connection's sequence
c.seq++
// Read the payload body into w
n, err := io.CopyN(w, c.r, length)
if nil != err {
return errors.Annotatef(err, badConnErrDesc)
}
if n != length {
return errors.Errorf("%sread pay load length %v, want %v", badConnErrDesc, n, length)
}
// If packet length is max payload length, we should wait for the next packet
if length >= maxPayloadLength {
// Continue reading
if err = c.readFullPacket(w); nil != err {
return errors.Annotate(err, badConnErrDesc)
}
}
return nil
}
func (c *Conn) resetSequence() {
c.seq = 0
}