-
Notifications
You must be signed in to change notification settings - Fork 219
Expand file tree
/
Copy pathconnection.go
More file actions
277 lines (242 loc) · 6.32 KB
/
connection.go
File metadata and controls
277 lines (242 loc) · 6.32 KB
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
/*
* Radon
*
* Copyright 2018 The Radon Authors.
* Code is licensed under the GPLv3.
*
*/
package backend
import (
"context"
"errors"
"fmt"
"io"
"sync"
"time"
"monitor"
"xbase/stats"
"xbase/sync2"
"github.com/xelabs/go-mysqlstack/driver"
"github.com/xelabs/go-mysqlstack/sqlparser/depends/sqltypes"
"github.com/xelabs/go-mysqlstack/xlog"
)
var _ Connection = &connection{}
var (
queryLogMaxLen = 512 * 1024 // 512KB
)
// Connection tuple.
type Connection interface {
ID() uint32
Dial() error
Ping() error
Close()
Closed() bool
LastErr() error
UseDB(string) error
Kill(string) error
Recycle()
Address() string
SetTimestamp(int64)
Timestamp() int64
Execute(string) (*sqltypes.Result, error)
ExecuteStreamFetch(string) (driver.Rows, error)
ExecuteWithLimits(query string, timeout int, maxmem int) (*sqltypes.Result, error)
}
type connection struct {
mu sync.Mutex
log *xlog.Log
connectionID uint32
user string
password string
address string
charset string
pool *Pool
lastErr error // If lastErr is not nil, this connection should be closed.
killed sync2.AtomicBool
driver driver.Conn
timestamp int64 // Recycle timestamp, in seconds.
counters *stats.Counters
}
// NewConnection creates a new connection.
func NewConnection(log *xlog.Log, pool *Pool) Connection {
conf := pool.conf
return &connection{
log: log,
pool: pool,
user: conf.User,
password: conf.Password,
address: pool.address,
charset: conf.Charset,
counters: pool.counters,
}
}
// Dial used to create a new driver conn.
func (c *connection) Dial() error {
var err error
defer mysqlStats.Record("conn.dial", time.Now())
if c.driver, err = driver.NewConn(c.user, c.password, c.address, "", c.charset); err != nil {
c.log.Error("conn[%s].dial.error:%+v", c.address, err)
c.counters.Add(poolCounterBackendDialError, 1)
c.Close()
return errors.New("Server maybe lost, please try again")
}
c.connectionID = c.driver.ConnectionID()
monitor.BackendConnectionInc(c.address)
return nil
}
// Ping used to do ping.
func (c *connection) Ping() error {
return c.driver.Ping()
}
// ID returns the connection ID.
func (c *connection) ID() uint32 {
return c.connectionID
}
// UseDB used to send a 'use database' query to MySQL.
// This is SQLCOM_CHANGE_DB command not COM_INIT_DB.
func (c *connection) UseDB(db string) error {
if db != "" {
query := fmt.Sprintf("use %s", db)
if _, err := c.Execute(query); err != nil {
return err
}
}
return nil
}
// SetTimestamp used to set the timestamp.
func (c *connection) SetTimestamp(ts int64) {
c.timestamp = ts
}
// Timestamp returns Timestamp of connection.
func (c *connection) Timestamp() int64 {
return c.timestamp
}
// setDeadline used to set deadline for a query.
func (c *connection) setDeadline(timeout int) (chan bool, *sync.WaitGroup) {
var wg sync.WaitGroup
done := make(chan bool, 1)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Millisecond)
wg.Add(1)
go func() {
defer func() {
wg.Done()
cancel()
}()
select {
case <-ctx.Done():
c.counters.Add(poolCounterBackendExecuteTimeout, 1)
c.killed.Set(true)
reason := ctx.Err().Error()
c.Kill(reason)
case <-done:
return
}
}()
return done, &wg
}
// Execute used to execute a query through this connection without limits.
func (c *connection) Execute(query string) (*sqltypes.Result, error) {
return c.ExecuteWithLimits(query, 0, 0)
}
// Execute used to execute a query through this connection.
// if timeout or memlimits is 0, means there is not limits.
func (c *connection) ExecuteWithLimits(query string, timeout int, memlimits int) (*sqltypes.Result, error) {
var err error
var qr *sqltypes.Result
log := c.log
defer mysqlStats.Record("Connection.Execute", time.Now())
// Query details.
qd := NewQueryDetail(c, query)
qz.Add(qd)
defer qz.Remove(qd)
// timeout.
if timeout > 0 {
done, wg := c.setDeadline(timeout)
if done != nil {
defer func() {
close(done)
wg.Wait()
}()
}
}
// memory limits.
checkFunc := func(rows driver.Rows) error {
if memlimits > 0 {
if rows.Bytes() > memlimits {
c.counters.Add(poolCounterBackendExecuteMaxresult, 1)
return fmt.Errorf("Query execution was interrupted, max memory usage[%d bytes] exceeded", memlimits)
}
}
return nil
}
// Thread safe.
c.mu.Lock()
defer c.mu.Unlock()
// execute.
if qr, err = c.driver.FetchAllWithFunc(query, -1, checkFunc); err != nil {
c.counters.Add(poolCounterBackendExecuteAllError, 1)
if len(query) > queryLogMaxLen {
query = query[:queryLogMaxLen]
}
log.Error("conn[%s].execute[%s].len[%d].error:%+v", c.address, query, len(query), err)
c.lastErr = err
// Connection is killed.
if c.killed.Get() {
return nil, fmt.Errorf("Query execution was interrupted, timeout[%dms] exceeded", timeout)
}
// Connection is broken(closed by server).
if err == io.EOF {
return nil, errors.New("Server maybe lost, please try again")
}
return nil, err
}
return qr, nil
}
func (c *connection) ExecuteStreamFetch(query string) (driver.Rows, error) {
return c.driver.Query(query)
}
// Kill used to kill current connection.
func (c *connection) Kill(reason string) error {
c.counters.Add(poolCounterBackendKilled, 1)
kill, err := c.pool.Get()
if err != nil {
return err
}
defer kill.Recycle()
c.log.Warning("conn[%s, ID:%v].be.killed.by[%v].reason[%s]", c.address, c.ID(), kill.ID(), reason)
query := fmt.Sprintf("KILL %d", c.connectionID)
if _, err = kill.Execute(query); err != nil {
c.log.Warning("conn[%s, ID:%v].kill.error:%+v", c.address, c.ID(), err)
return err
}
return nil
}
// Recycle used to put current to pool.
func (c *connection) Recycle() {
defer mysqlStats.Record("conn.recycle", time.Now())
if !c.driver.Closed() {
c.pool.Put(c)
}
}
// Address returns the backend address of the connection.
func (c *connection) Address() string {
return c.address
}
// Close used to close connection.
func (c *connection) Close() {
defer mysqlStats.Record("conn.close", time.Now())
c.lastErr = errors.New("I.am.closed")
if c.driver != nil {
c.driver.Close()
monitor.BackendConnectionDec(c.address)
}
}
func (c *connection) Closed() bool {
if c.driver != nil {
return c.driver.Closed()
}
return true
}
func (c *connection) LastErr() error {
return c.lastErr
}