forked from CovenantSQL/CovenantSQL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
494 lines (413 loc) · 11.1 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
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
/*
* Copyright 2018 The CovenantSQL Authors.
*
* 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 client
import (
"context"
"database/sql"
"database/sql/driver"
"sync"
"sync/atomic"
"time"
"github.com/pkg/errors"
"github.com/CovenantSQL/CovenantSQL/crypto/asymmetric"
"github.com/CovenantSQL/CovenantSQL/crypto/kms"
"github.com/CovenantSQL/CovenantSQL/proto"
"github.com/CovenantSQL/CovenantSQL/route"
"github.com/CovenantSQL/CovenantSQL/rpc"
"github.com/CovenantSQL/CovenantSQL/rpc/mux"
"github.com/CovenantSQL/CovenantSQL/types"
"github.com/CovenantSQL/CovenantSQL/utils/log"
"github.com/CovenantSQL/CovenantSQL/utils/trace"
)
// conn implements an interface sql.Conn.
type conn struct {
dbID proto.DatabaseID
queries []types.Query
localNodeID proto.NodeID
privKey *asymmetric.PrivateKey
inTransaction bool
closed int32
leader *pconn
follower *pconn
}
// pconn represents a connection to a peer.
type pconn struct {
wg *sync.WaitGroup
parent *conn
ackCh chan *types.Ack
pCaller rpc.PCaller
}
const workerCount int = 2
func newConn(cfg *Config) (c *conn, err error) {
// get local node id
var localNodeID proto.NodeID
if localNodeID, err = kms.GetLocalNodeID(); err != nil {
return
}
// get local private key
var privKey *asymmetric.PrivateKey
if privKey, err = kms.GetLocalPrivateKey(); err != nil {
return
}
c = &conn{
dbID: proto.DatabaseID(cfg.DatabaseID),
localNodeID: localNodeID,
privKey: privKey,
queries: make([]types.Query, 0),
}
// get peers from BP
var peers *proto.Peers
if peers, err = cacheGetPeers(c.dbID, c.privKey); err != nil {
return nil, errors.WithMessage(err, "cacheGetPeers failed")
}
if cfg.Mirror != "" {
c.leader = &pconn{
wg: &sync.WaitGroup{},
parent: c,
pCaller: mux.NewRawCaller(cfg.Mirror),
}
// no ack workers required, mirror mode does not support ack worker
} else {
if cfg.UseLeader {
var caller rpc.PCaller
if cfg.UseDirectRPC {
caller = rpc.NewPersistentCaller(peers.Leader)
} else {
caller = mux.NewPersistentCaller(peers.Leader)
}
c.leader = &pconn{
wg: &sync.WaitGroup{},
ackCh: make(chan *types.Ack, workerCount*4),
parent: c,
pCaller: caller,
}
}
// choose a random follower node
if cfg.UseFollower && len(peers.Servers) > 1 {
for {
node := peers.Servers[randSource.Intn(len(peers.Servers))]
if node != peers.Leader {
var caller rpc.PCaller
if cfg.UseDirectRPC {
caller = rpc.NewPersistentCaller(node)
} else {
caller = mux.NewPersistentCaller(node)
}
c.follower = &pconn{
wg: &sync.WaitGroup{},
ackCh: make(chan *types.Ack, workerCount*4),
parent: c,
pCaller: caller,
}
break
}
}
}
if c.leader == nil && c.follower == nil {
return nil, errors.New("no follower peers found")
}
if c.leader != nil {
if err := c.leader.startAckWorkers(); err != nil {
return nil, errors.WithMessage(err, "leader startAckWorkers failed")
}
}
if c.follower != nil {
if err := c.follower.startAckWorkers(); err != nil {
return nil, errors.WithMessage(err, "follower startAckWorkers failed")
}
}
}
log.WithField("db", c.dbID).Debug("new connection to database")
return
}
func (c *pconn) startAckWorkers() (err error) {
for i := 0; i < workerCount; i++ {
c.wg.Add(1)
go c.ackWorker()
}
return
}
func (c *pconn) stopAckWorkers() {
if c.ackCh != nil {
close(c.ackCh)
}
}
func (c *pconn) ackWorker() {
defer c.wg.Done()
var (
oneTime sync.Once
pc rpc.PCaller
err error
)
ackWorkerLoop:
for {
ack, got := <-c.ackCh
if !got { // closed and empty
break ackWorkerLoop
}
oneTime.Do(func() {
pc = c.pCaller.New()
})
if err = ack.Sign(c.parent.privKey); err != nil {
log.WithField("target", pc.Target()).WithError(err).Error("failed to sign ack")
continue
}
var ackRes types.AckResponse
// send ack back
if err = pc.Call(route.DBSAck.String(), ack, &ackRes); err != nil {
log.WithError(err).Debug("send ack failed")
continue
}
}
if pc != nil {
pc.Close()
}
log.Debug("ack worker quiting")
}
func (c *pconn) close() error {
c.stopAckWorkers()
c.wg.Wait()
if c.pCaller != nil {
c.pCaller.Close()
}
return nil
}
// Prepare implements the driver.Conn.Prepare method.
func (c *conn) Prepare(query string) (driver.Stmt, error) {
return c.PrepareContext(context.Background(), query)
}
// Close implements the driver.Conn.Close method.
func (c *conn) Close() error {
// close the meta connection
if atomic.CompareAndSwapInt32(&c.closed, 0, 1) {
log.WithField("db", c.dbID).Debug("closed connection")
}
if c.leader != nil {
c.leader.close()
}
if c.follower != nil {
c.follower.close()
}
return nil
}
// Begin implements the driver.Conn.Begin method.
func (c *conn) Begin() (driver.Tx, error) {
return c.BeginTx(context.Background(), driver.TxOptions{})
}
// BeginTx implements the driver.ConnBeginTx.BeginTx method.
func (c *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
if atomic.LoadInt32(&c.closed) != 0 {
return nil, driver.ErrBadConn
}
// start transaction
log.WithField("inTx", c.inTransaction).Debug("begin transaction")
if c.inTransaction {
return nil, sql.ErrTxDone
}
// TODO(xq262144): make use of the ctx argument
c.inTransaction = true
c.queries = c.queries[:0]
return c, nil
}
// PrepareContext implements the driver.ConnPrepareContext.ConnPrepareContext method.
func (c *conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
if atomic.LoadInt32(&c.closed) != 0 {
return nil, driver.ErrBadConn
}
log.WithField("query", query).Debug("prepared statement")
// prepare the statement
return newStmt(c, query), nil
}
// ExecContext implements the driver.ExecerContext.ExecContext method.
func (c *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (result driver.Result, err error) {
defer trace.StartRegion(ctx, "dbExec").End()
if atomic.LoadInt32(&c.closed) != 0 {
err = driver.ErrBadConn
return
}
// TODO(xq262144): make use of the ctx argument
sq := convertQuery(query, args)
var affectedRows, lastInsertID int64
if affectedRows, lastInsertID, _, err = c.addQuery(ctx, types.WriteQuery, sq); err != nil {
return
}
result = &execResult{
affectedRows: affectedRows,
lastInsertID: lastInsertID,
}
return
}
// QueryContext implements the driver.QueryerContext.QueryContext method.
func (c *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (rows driver.Rows, err error) {
defer trace.StartRegion(ctx, "dbQuery").End()
if atomic.LoadInt32(&c.closed) != 0 {
err = driver.ErrBadConn
return
}
// TODO(xq262144): make use of the ctx argument
sq := convertQuery(query, args)
_, _, rows, err = c.addQuery(ctx, types.ReadQuery, sq)
return
}
// Commit implements the driver.Tx.Commit method.
func (c *conn) Commit() (err error) {
if atomic.LoadInt32(&c.closed) != 0 {
return driver.ErrBadConn
}
if !c.inTransaction {
return sql.ErrTxDone
}
defer func() {
c.queries = c.queries[:0]
c.inTransaction = false
}()
if len(c.queries) > 0 {
// send query
if _, _, _, err = c.sendQuery(context.Background(), types.WriteQuery, c.queries); err != nil {
return
}
}
return
}
// Rollback implements the driver.Tx.Rollback method.
func (c *conn) Rollback() error {
if atomic.LoadInt32(&c.closed) != 0 {
return driver.ErrBadConn
}
if !c.inTransaction {
return sql.ErrTxDone
}
defer func() {
c.queries = c.queries[:0]
c.inTransaction = false
}()
if len(c.queries) == 0 {
return sql.ErrTxDone
}
return nil
}
func (c *conn) addQuery(ctx context.Context, queryType types.QueryType, query *types.Query) (affectedRows int64, lastInsertID int64, rows driver.Rows, err error) {
if c.inTransaction {
// check query type, enqueue query
if queryType == types.ReadQuery {
// read query is not supported in transaction
err = ErrQueryInTransaction
return
}
// append queries
c.queries = append(c.queries, *query)
log.WithFields(log.Fields{
"pattern": query.Pattern,
"args": query.Args,
}).Debug("add query to tx")
return
}
log.WithFields(log.Fields{
"pattern": query.Pattern,
"args": query.Args,
}).Debug("execute query")
return c.sendQuery(ctx, queryType, []types.Query{*query})
}
func (c *conn) sendQuery(ctx context.Context, queryType types.QueryType, queries []types.Query) (affectedRows int64, lastInsertID int64, rows driver.Rows, err error) {
var uc *pconn // peer connection used to execute the queries
uc = c.leader
// use follower pconn only when the query is readonly
if queryType == types.ReadQuery && c.follower != nil {
uc = c.follower
}
if uc == nil {
uc = c.follower
}
// allocate sequence
connID, seqNo := allocateConnAndSeq()
defer putBackConn(connID)
defer func() {
log.WithFields(log.Fields{
"count": len(queries),
"type": queryType.String(),
"connID": connID,
"seqNo": seqNo,
"target": uc.pCaller.Target(),
"source": c.localNodeID,
}).WithError(err).Debug("send query")
}()
// build request
req := &types.Request{
Header: types.SignedRequestHeader{
RequestHeader: types.RequestHeader{
QueryType: queryType,
NodeID: c.localNodeID,
DatabaseID: c.dbID,
ConnectionID: connID,
SeqNo: seqNo,
Timestamp: getLocalTime(),
},
},
Payload: types.RequestPayload{
Queries: queries,
},
}
if err = req.Sign(c.privKey); err != nil {
return
}
// set receipt if key exists in context
if val := ctx.Value(&ctxReceiptKey); val != nil {
val.(*atomic.Value).Store(&Receipt{
RequestHash: req.Header.Hash(),
})
}
var response types.Response
if err = uc.pCaller.Call(route.DBSQuery.String(), req, &response); err != nil {
return
}
rows = newRows(&response)
if queryType == types.WriteQuery {
affectedRows = response.Header.AffectedRows
lastInsertID = response.Header.LastInsertID
}
// build ack
func() {
defer trace.StartRegion(ctx, "ackEnqueue").End()
if uc.ackCh != nil {
uc.ackCh <- &types.Ack{
Header: types.SignedAckHeader{
AckHeader: types.AckHeader{
Response: response.Header.ResponseHeader,
ResponseHash: response.Header.Hash(),
NodeID: c.localNodeID,
Timestamp: getLocalTime(),
},
},
}
}
}()
return
}
func getLocalTime() time.Time {
return time.Now().UTC()
}
func convertQuery(query string, args []driver.NamedValue) (sq *types.Query) {
// rebuild args to named args
sq = &types.Query{
Pattern: query,
}
sq.Args = make([]types.NamedArg, len(args))
for i, v := range args {
sq.Args[i].Name = v.Name
sq.Args[i].Value = v.Value
}
return
}