Uh oh!
There was an error while loading. Please reload this page.
forked from CovenantSQL/CovenantSQL
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconn.go
More file actions
Latest commit
494 lines (413 loc) · 11.1 KB
/
Copy pathconn.go
File metadata and controls
494 lines (413 loc) · 11.1 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
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.
typeconnstruct {
dbID proto.DatabaseID
queries []types.Query
localNodeID proto.NodeID
privKey*asymmetric.PrivateKey
inTransactionbool
closedint32
leader*pconn
follower*pconn
}
// pconn represents a connection to a peer.
typepconnstruct {
wg*sync.WaitGroup
parent*conn
ackChchan*types.Ack
pCaller rpc.PCaller
}
constworkerCountint=2
funcnewConn(cfg*Config) (c*conn, errerror) {
// get local node id
varlocalNodeID proto.NodeID
iflocalNodeID, err=kms.GetLocalNodeID(); err!=nil {
return
}
// get local private key
varprivKey*asymmetric.PrivateKey
ifprivKey, 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
varpeers*proto.Peers
ifpeers, err=cacheGetPeers(c.dbID, c.privKey); err!=nil {
returnnil, errors.WithMessage(err, "cacheGetPeers failed")
}
ifcfg.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 {
ifcfg.UseLeader {
varcaller rpc.PCaller
ifcfg.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
ifcfg.UseFollower&&len(peers.Servers) >1 {
for {
node:=peers.Servers[randSource.Intn(len(peers.Servers))]
ifnode!=peers.Leader {
varcaller rpc.PCaller
ifcfg.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
}
}
}
ifc.leader==nil&&c.follower==nil {
returnnil, errors.New("no follower peers found")
}
ifc.leader!=nil {
iferr:=c.leader.startAckWorkers(); err!=nil {
returnnil, errors.WithMessage(err, "leader startAckWorkers failed")
}
}
ifc.follower!=nil {
iferr:=c.follower.startAckWorkers(); err!=nil {
returnnil, errors.WithMessage(err, "follower startAckWorkers failed")
}
}
}
log.WithField("db", c.dbID).Debug("new connection to database")
return
}
func (c*pconn) startAckWorkers() (errerror) {
fori:=0; i<workerCount; i++ {
c.wg.Add(1)
goc.ackWorker()
}
return
}
func (c*pconn) stopAckWorkers() {
ifc.ackCh!=nil {
close(c.ackCh)
}
}
func (c*pconn) ackWorker() {
deferc.wg.Done()
var (
oneTime sync.Once
pc rpc.PCaller
errerror
)
ackWorkerLoop:
for {
ack, got:=<-c.ackCh
if!got { // closed and empty
break ackWorkerLoop
}
oneTime.Do(func() {
pc=c.pCaller.New()
})
iferr=ack.Sign(c.parent.privKey); err!=nil {
log.WithField("target", pc.Target()).WithError(err).Error("failed to sign ack")
continue
}
varackRes types.AckResponse
// send ack back
iferr=pc.Call(route.DBSAck.String(), ack, &ackRes); err!=nil {
log.WithError(err).Debug("send ack failed")
continue
}
}
ifpc!=nil {
pc.Close()
}
log.Debug("ack worker quiting")
}
func (c*pconn) close() error {
c.stopAckWorkers()
c.wg.Wait()
ifc.pCaller!=nil {
c.pCaller.Close()
}
returnnil
}
// Prepare implements the driver.Conn.Prepare method.
func (c*conn) Prepare(querystring) (driver.Stmt, error) {
returnc.PrepareContext(context.Background(), query)
}
// Close implements the driver.Conn.Close method.
func (c*conn) Close() error {
// close the meta connection
ifatomic.CompareAndSwapInt32(&c.closed, 0, 1) {
log.WithField("db", c.dbID).Debug("closed connection")
}
ifc.leader!=nil {
c.leader.close()
}
ifc.follower!=nil {
c.follower.close()
}
returnnil
}
// Begin implements the driver.Conn.Begin method.
func (c*conn) Begin() (driver.Tx, error) {
returnc.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) {
ifatomic.LoadInt32(&c.closed) !=0 {
returnnil, driver.ErrBadConn
}
// start transaction
log.WithField("inTx", c.inTransaction).Debug("begin transaction")
ifc.inTransaction {
returnnil, sql.ErrTxDone
}
// TODO(xq262144): make use of the ctx argument
c.inTransaction=true
c.queries=c.queries[:0]
returnc, nil
}
// PrepareContext implements the driver.ConnPrepareContext.ConnPrepareContext method.
func (c*conn) PrepareContext(ctx context.Context, querystring) (driver.Stmt, error) {
ifatomic.LoadInt32(&c.closed) !=0 {
returnnil, driver.ErrBadConn
}
log.WithField("query", query).Debug("prepared statement")
// prepare the statement
returnnewStmt(c, query), nil
}
// ExecContext implements the driver.ExecerContext.ExecContext method.
func (c*conn) ExecContext(ctx context.Context, querystring, args []driver.NamedValue) (result driver.Result, errerror) {
defertrace.StartRegion(ctx, "dbExec").End()
ifatomic.LoadInt32(&c.closed) !=0 {
err=driver.ErrBadConn
return
}
// TODO(xq262144): make use of the ctx argument
sq:=convertQuery(query, args)
varaffectedRows, lastInsertIDint64
ifaffectedRows, 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, querystring, args []driver.NamedValue) (rows driver.Rows, errerror) {
defertrace.StartRegion(ctx, "dbQuery").End()
ifatomic.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() (errerror) {
ifatomic.LoadInt32(&c.closed) !=0 {
returndriver.ErrBadConn
}
if!c.inTransaction {
returnsql.ErrTxDone
}
deferfunc() {
c.queries=c.queries[:0]
c.inTransaction=false
}()
iflen(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 {
ifatomic.LoadInt32(&c.closed) !=0 {
returndriver.ErrBadConn
}
if!c.inTransaction {
returnsql.ErrTxDone
}
deferfunc() {
c.queries=c.queries[:0]
c.inTransaction=false
}()
iflen(c.queries) ==0 {
returnsql.ErrTxDone
}
returnnil
}
func (c*conn) addQuery(ctx context.Context, queryType types.QueryType, query*types.Query) (affectedRowsint64, lastInsertIDint64, rows driver.Rows, errerror) {
ifc.inTransaction {
// check query type, enqueue query
ifqueryType==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")
returnc.sendQuery(ctx, queryType, []types.Query{*query})
}
func (c*conn) sendQuery(ctx context.Context, queryType types.QueryType, queries []types.Query) (affectedRowsint64, lastInsertIDint64, rows driver.Rows, errerror) {
varuc*pconn// peer connection used to execute the queries
uc=c.leader
// use follower pconn only when the query is readonly
ifqueryType==types.ReadQuery&&c.follower!=nil {
uc=c.follower
}
ifuc==nil {
uc=c.follower
}
// allocate sequence
connID, seqNo:=allocateConnAndSeq()
deferputBackConn(connID)
deferfunc() {
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,
},
}
iferr=req.Sign(c.privKey); err!=nil {
return
}
// set receipt if key exists in context
ifval:=ctx.Value(&ctxReceiptKey); val!=nil {
val.(*atomic.Value).Store(&Receipt{
RequestHash: req.Header.Hash(),
})
}
varresponse types.Response
iferr=uc.pCaller.Call(route.DBSQuery.String(), req, &response); err!=nil {
return
}
rows=newRows(&response)
ifqueryType==types.WriteQuery {
affectedRows=response.Header.AffectedRows
lastInsertID=response.Header.LastInsertID
}
// build ack
func() {
defertrace.StartRegion(ctx, "ackEnqueue").End()
ifuc.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
}
funcgetLocalTime() time.Time {
returntime.Now().UTC()
}
funcconvertQuery(querystring, args []driver.NamedValue) (sq*types.Query) {
// rebuild args to named args
sq=&types.Query{
Pattern: query,
}
sq.Args=make([]types.NamedArg, len(args))
fori, v:=rangeargs {
sq.Args[i].Name=v.Name
sq.Args[i].Value=v.Value
}
return
}