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 pathdriver.go
More file actions
Latest commit
700 lines (601 loc) · 17.7 KB
/
Copy pathdriver.go
File metadata and controls
700 lines (601 loc) · 17.7 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
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
/*
* 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"
"fmt"
"math/rand"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pkg/errors"
bp "github.com/CovenantSQL/CovenantSQL/blockproducer"
"github.com/CovenantSQL/CovenantSQL/blockproducer/interfaces"
"github.com/CovenantSQL/CovenantSQL/conf"
"github.com/CovenantSQL/CovenantSQL/crypto"
"github.com/CovenantSQL/CovenantSQL/crypto/asymmetric"
"github.com/CovenantSQL/CovenantSQL/crypto/hash"
"github.com/CovenantSQL/CovenantSQL/crypto/kms"
"github.com/CovenantSQL/CovenantSQL/proto"
"github.com/CovenantSQL/CovenantSQL/route"
rpc "github.com/CovenantSQL/CovenantSQL/rpc/mux"
"github.com/CovenantSQL/CovenantSQL/types"
"github.com/CovenantSQL/CovenantSQL/utils"
"github.com/CovenantSQL/CovenantSQL/utils/log"
)
const (
// DBScheme defines the dsn scheme.
DBScheme="covenantsql"
// DBSchemeAlias defines the alias dsn scheme.
DBSchemeAlias="cql"
// DefaultGasPrice defines the default gas price for new created database.
DefaultGasPrice=1
// DefaultAdvancePayment defines the default advance payment for new created database.
DefaultAdvancePayment=20000000
)
var (
// PeersUpdateInterval defines peers list refresh interval for client.
PeersUpdateInterval=time.Second*5
driverInitializeduint32
peersUpdaterRunninguint32
peerList sync.Map// map[proto.DatabaseID]*proto.Peers
connIDLock sync.Mutex
connIDAvail []uint64
globalSeqNouint64
randSource=rand.New(rand.NewSource(time.Now().UnixNano()))
// DefaultConfigFile is the default path of config file
DefaultConfigFile="~/.cql/config.yaml"
)
funcinit() {
d:=new(covenantSQLDriver)
sql.Register(DBScheme, d)
sql.Register(DBSchemeAlias, d)
log.Debug("CovenantSQL driver registered.")
}
// covenantSQLDriver implements sql.Driver interface.
typecovenantSQLDriverstruct {
}
// Open returns new db connection.
func (d*covenantSQLDriver) Open(dsnstring) (conn driver.Conn, errerror) {
varcfg*Config
ifcfg, err=ParseDSN(dsn); err!=nil {
return
}
ifatomic.LoadUint32(&driverInitialized) ==0 {
err=defaultInit()
iferr!=nil&&err!=ErrAlreadyInitialized {
return
}
}
returnnewConn(cfg)
}
// ResourceMeta defines new database resources requirement descriptions.
typeResourceMetastruct {
// copied fields from types.ResourceMeta
TargetMiners []proto.AccountAddress`json:"target-miners,omitempty"`// designated miners
Nodeuint16`json:"node,omitempty"`// reserved node count
Spaceuint64`json:"space,omitempty"`// reserved storage space in bytes
Memoryuint64`json:"memory,omitempty"`// reserved memory in bytes
LoadAvgPerCPUfloat64`json:"load-avg-per-cpu,omitempty"`// max loadAvg15 per CPU
EncryptionKeystring`json:"encrypt-key,omitempty"`// encryption key for database instance
UseEventualConsistencybool`json:"eventual-consistency,omitempty"`// use eventual consistency replication if enabled
ConsistencyLevelfloat64`json:"consistency-level,omitempty"`// customized strong consistency level
IsolationLevelint`json:"isolation-level,omitempty"`// customized isolation level
GasPriceuint64`json:"gas-price"`// customized gas price
AdvancePaymentuint64`json:"advance-payment"`// customized advance payment
}
funcdefaultInit() (errerror) {
configFile:=utils.HomeDirExpand(DefaultConfigFile)
ifconfigFile==DefaultConfigFile {
//System not support ~ dir, need Init manually.
log.Debugf("Could not find CovenantSQL default config location: %v", configFile)
returnErrNotInitialized
}
log.Debugf("Using CovenantSQL default config location: %v", configFile)
returnInit(configFile, []byte(""))
}
// Init defines init process for client.
funcInit(configFilestring, masterKey []byte) (errerror) {
if!atomic.CompareAndSwapUint32(&driverInitialized, 0, 1) {
err=ErrAlreadyInitialized
return
}
// load config
ifconf.GConf, err=conf.LoadConfig(configFile); err!=nil {
return
}
route.InitKMS(conf.GConf.PubKeyStoreFile)
iferr=kms.InitLocalKeyPair(conf.GConf.PrivateKeyFile, masterKey); err!=nil {
return
}
// ping block producer to register node
iferr=registerNode(); err!=nil {
return
}
// run peers updater
iferr=runPeerListUpdater(); err!=nil {
return
}
return
}
// Create sends create database operation to block producer.
funcCreate(metaResourceMeta) (txHash hash.Hash, dsnstring, errerror) {
ifatomic.LoadUint32(&driverInitialized) ==0 {
err=ErrNotInitialized
return
}
var (
nonceReq=new(types.NextAccountNonceReq)
nonceResp=new(types.NextAccountNonceResp)
req=new(types.AddTxReq)
resp=new(types.AddTxResp)
privateKey*asymmetric.PrivateKey
clientAddr proto.AccountAddress
)
ifprivateKey, err=kms.GetLocalPrivateKey(); err!=nil {
err=errors.Wrap(err, "get local private key failed")
return
}
ifclientAddr, err=crypto.PubKeyHash(privateKey.PubKey()); err!=nil {
err=errors.Wrap(err, "get local account address failed")
return
}
// allocate nonce
nonceReq.Addr=clientAddr
iferr=requestBP(route.MCCNextAccountNonce, nonceReq, nonceResp); err!=nil {
err=errors.Wrap(err, "allocate create database transaction nonce failed")
return
}
ifmeta.GasPrice==0 {
meta.GasPrice=DefaultGasPrice
}
ifmeta.AdvancePayment==0 {
meta.AdvancePayment=DefaultAdvancePayment
}
req.TTL=1
req.Tx=types.NewCreateDatabase(&types.CreateDatabaseHeader{
Owner: clientAddr,
ResourceMeta: types.ResourceMeta{
TargetMiners: meta.TargetMiners,
Node: meta.Node,
Space: meta.Space,
Memory: meta.Memory,
LoadAvgPerCPU: meta.LoadAvgPerCPU,
EncryptionKey: meta.EncryptionKey,
UseEventualConsistency: meta.UseEventualConsistency,
ConsistencyLevel: meta.ConsistencyLevel,
IsolationLevel: meta.IsolationLevel,
},
GasPrice: meta.GasPrice,
AdvancePayment: meta.AdvancePayment,
TokenType: types.Particle,
Nonce: nonceResp.Nonce,
})
iferr=req.Tx.Sign(privateKey); err!=nil {
err=errors.Wrap(err, "sign request failed")
return
}
iferr=requestBP(route.MCCAddTx, req, resp); err!=nil {
err=errors.Wrap(err, "call create database transaction failed")
return
}
txHash=req.Tx.Hash()
cfg:=NewConfig()
cfg.DatabaseID=string(proto.FromAccountAndNonce(clientAddr, uint32(nonceResp.Nonce)))
dsn=cfg.FormatDSN()
return
}
// WaitDBCreation waits for database creation complete.
funcWaitDBCreation(ctx context.Context, dsnstring) (errerror) {
dsnCfg, err:=ParseDSN(dsn)
iferr!=nil {
return
}
db, err:=sql.Open("covenantsql", dsn)
deferdb.Close()
iferr!=nil {
return
}
// wait for creation
err=WaitBPDatabaseCreation(ctx, proto.DatabaseID(dsnCfg.DatabaseID), db, 3*time.Second)
return
}
// WaitBPDatabaseCreation waits for database creation complete.
funcWaitBPDatabaseCreation(
ctx context.Context,
dbID proto.DatabaseID,
db*sql.DB,
period time.Duration,
) (errerror) {
var (
ticker=time.NewTicker(period)
req=&types.QuerySQLChainProfileReq{
DBID: dbID,
}
count=0
)
deferticker.Stop()
deferfmt.Printf("\n")
for {
select {
case<-ticker.C:
count++
iferr=rpc.RequestBP(
route.MCCQuerySQLChainProfile.String(), req, nil,
); err!=nil {
if!strings.Contains(err.Error(), bp.ErrDatabaseNotFound.Error()) {
// err != nil && err != ErrDatabaseNotFound (unexpected error)
return
}
} else {
// err == nil (creation done on BP): try to use database connection
ifdb==nil {
return
}
if_, err=db.ExecContext(ctx, "SHOW TABLES"); err==nil {
// err == nil (connect to Miner OK)
return
}
}
fmt.Printf("\rQuerying SQLChain Profile %vs", count*int(period.Seconds()))
case<-ctx.Done():
iferr!=nil {
returnerrors.Wrapf(ctx.Err(), "last error: %s", err.Error())
}
returnctx.Err()
}
}
}
// Drop sends drop database operation to block producer.
funcDrop(dsnstring) (txHash hash.Hash, errerror) {
ifatomic.LoadUint32(&driverInitialized) ==0 {
err=ErrNotInitialized
return
}
varcfg*Config
ifcfg, err=ParseDSN(dsn); err!=nil {
return
}
peerList.Delete(cfg.DatabaseID)
//TODO(laodouya) currently not supported
//err = errors.New("drop db current not support")
return
}
// GetTokenBalance get the token balance of current account.
funcGetTokenBalance(tt types.TokenType) (balanceuint64, errerror) {
ifatomic.LoadUint32(&driverInitialized) ==0 {
err=ErrNotInitialized
return
}
req:=new(types.QueryAccountTokenBalanceReq)
resp:=new(types.QueryAccountTokenBalanceResp)
varpubKey*asymmetric.PublicKey
ifpubKey, err=kms.GetLocalPublicKey(); err!=nil {
return
}
ifreq.Addr, err=crypto.PubKeyHash(pubKey); err!=nil {
return
}
req.TokenType=tt
iferr=requestBP(route.MCCQueryAccountTokenBalance, req, resp); err==nil {
if!resp.OK {
err=ErrNoSuchTokenBalance
return
}
balance=resp.Balance
}
return
}
// UpdatePermission sends UpdatePermission transaction to chain.
funcUpdatePermission(targetUser proto.AccountAddress,
targetChain proto.AccountAddress, perm*types.UserPermission) (txHash hash.Hash, errerror) {
ifatomic.LoadUint32(&driverInitialized) ==0 {
err=ErrNotInitialized
return
}
var (
pubKey*asymmetric.PublicKey
privKey*asymmetric.PrivateKey
addr proto.AccountAddress
nonce interfaces.AccountNonce
)
ifpubKey, err=kms.GetLocalPublicKey(); err!=nil {
return
}
ifprivKey, err=kms.GetLocalPrivateKey(); err!=nil {
return
}
ifaddr, err=crypto.PubKeyHash(pubKey); err!=nil {
return
}
nonce, err=getNonce(addr)
iferr!=nil {
return
}
up:=types.NewUpdatePermission(&types.UpdatePermissionHeader{
TargetSQLChain: targetChain,
TargetUser: targetUser,
Permission: perm,
Nonce: nonce,
})
err=up.Sign(privKey)
iferr!=nil {
log.WithError(err).Warning("sign failed")
return
}
addTxReq:=new(types.AddTxReq)
addTxResp:=new(types.AddTxResp)
addTxReq.Tx=up
err=requestBP(route.MCCAddTx, addTxReq, addTxResp)
iferr!=nil {
log.WithError(err).Warning("send tx failed")
return
}
txHash=up.Hash()
return
}
// TransferToken send Transfer transaction to chain.
funcTransferToken(targetUser proto.AccountAddress, amountuint64, tokenType types.TokenType) (
txHash hash.Hash, errerror,
) {
ifatomic.LoadUint32(&driverInitialized) ==0 {
err=ErrNotInitialized
return
}
var (
pubKey*asymmetric.PublicKey
privKey*asymmetric.PrivateKey
addr proto.AccountAddress
nonce interfaces.AccountNonce
)
ifpubKey, err=kms.GetLocalPublicKey(); err!=nil {
return
}
ifprivKey, err=kms.GetLocalPrivateKey(); err!=nil {
return
}
ifaddr, err=crypto.PubKeyHash(pubKey); err!=nil {
return
}
nonce, err=getNonce(addr)
iferr!=nil {
return
}
tran:=types.NewTransfer(&types.TransferHeader{
Sender: addr,
Receiver: targetUser,
Amount: amount,
TokenType: tokenType,
Nonce: nonce,
})
err=tran.Sign(privKey)
iferr!=nil {
log.WithError(err).Warning("sign failed")
return
}
addTxReq:=new(types.AddTxReq)
addTxResp:=new(types.AddTxResp)
addTxReq.Tx=tran
err=requestBP(route.MCCAddTx, addTxReq, addTxResp)
iferr!=nil {
log.WithError(err).Warning("send tx failed")
return
}
txHash=tran.Hash()
return
}
// WaitTxConfirmation waits for the transaction with target hash txHash to be confirmed. It also
// returns if any error occurs or a final state is returned from BP.
funcWaitTxConfirmation(
ctx context.Context, txHash hash.Hash) (state interfaces.TransactionState, errerror,
) {
var (
ticker=time.NewTicker(1*time.Second)
method=route.MCCQueryTxState
req=&types.QueryTxStateReq{Hash: txHash}
resp=&types.QueryTxStateResp{}
count=0
)
deferticker.Stop()
deferfmt.Printf("\n")
for {
iferr=requestBP(method, req, resp); err!=nil {
err=errors.Wrapf(err, "failed to call %s", method)
return
}
state=resp.State
count++
fmt.Printf("\rWaiting blockproducers confirmation %vs, state: %v\033[0K", count, state)
log.WithFields(log.Fields{
"tx_hash": txHash,
"tx_state": state,
}).Debug("waiting for tx confirmation")
switchstate {
caseinterfaces.TransactionStatePending:
caseinterfaces.TransactionStatePacked:
caseinterfaces.TransactionStateConfirmed,
interfaces.TransactionStateExpired,
interfaces.TransactionStateNotFound:
return
default:
err=errors.Errorf("unknown transaction state %d", state)
return
}
select {
case<-ticker.C:
case<-ctx.Done():
err=ctx.Err()
return
}
}
}
funcgetNonce(addr proto.AccountAddress) (nonce interfaces.AccountNonce, errerror) {
nonceReq:=new(types.NextAccountNonceReq)
nonceResp:=new(types.NextAccountNonceResp)
nonceReq.Addr=addr
err=requestBP(route.MCCNextAccountNonce, nonceReq, nonceResp)
iferr!=nil {
log.WithError(err).Warning("get nonce failed")
return
}
nonce=nonceResp.Nonce
return
}
funcrequestBP(method route.RemoteFunc, requestinterface{}, responseinterface{}) (errerror) {
varbpNodeID proto.NodeID
ifbpNodeID, err=rpc.GetCurrentBP(); err!=nil {
return
}
returnrpc.NewCaller().CallNode(bpNodeID, method.String(), request, response)
}
funcregisterNode() (errerror) {
varnodeID proto.NodeID
ifnodeID, err=kms.GetLocalNodeID(); err!=nil {
return
}
varnodeInfo*proto.Node
ifnodeInfo, err=kms.GetNodeInfo(nodeID); err!=nil {
return
}
ifnodeInfo.Role!=proto.Leader&&nodeInfo.Role!=proto.Follower {
log.Infof("Self register to blockproducer: %v", conf.GConf.BP.NodeID)
err=rpc.PingBP(nodeInfo, conf.GConf.BP.NodeID)
}
return
}
funcrunPeerListUpdater() (errerror) {
varprivKey*asymmetric.PrivateKey
ifprivKey, err=kms.GetLocalPrivateKey(); err!=nil {
return
}
if!atomic.CompareAndSwapUint32(&peersUpdaterRunning, 0, 1) {
return
}
gofunc() {
for {
ifatomic.LoadUint32(&peersUpdaterRunning) ==0 {
return
}
varwg sync.WaitGroup
peerList.Range(func(rawDBID, _interface{}) bool {
dbID:=rawDBID.(proto.DatabaseID)
wg.Add(1)
gofunc(dbID proto.DatabaseID) {
deferwg.Done()
varerrerror
if_, err=getPeers(dbID, privKey); err!=nil {
log.WithField("db", dbID).
WithError(err).
Debug("update peers failed")
// TODO(xq262144), better rpc remote error judgement
ifstrings.Contains(err.Error(), bp.ErrNoSuchDatabase.Error()) {
log.WithField("db", dbID).
Warning("database no longer exists, stopping peers update")
peerList.Delete(dbID)
}
}
}(dbID)
returntrue
})
wg.Wait()
time.Sleep(PeersUpdateInterval)
}
}()
return
}
funcstopPeersUpdater() {
atomic.StoreUint32(&peersUpdaterRunning, 0)
}
funccacheGetPeers(dbID proto.DatabaseID, privKey*asymmetric.PrivateKey) (peers*proto.Peers, errerror) {
varokbool
varrawPeersinterface{}
varcacheHitbool
deferfunc() {
log.WithFields(log.Fields{
"db": dbID,
"hit": cacheHit,
}).WithError(err).Debug("cache get peers for database")
}()
ifrawPeers, ok=peerList.Load(dbID); ok {
ifpeers, ok=rawPeers.(*proto.Peers); ok {
cacheHit=true
return
}
}
// get peers using non-cache method
returngetPeers(dbID, privKey)
}
funcgetPeers(dbID proto.DatabaseID, privKey*asymmetric.PrivateKey) (peers*proto.Peers, errerror) {
deferfunc() {
log.WithFields(log.Fields{
"db": dbID,
"peers": peers,
}).WithError(err).Debug("get peers for database")
}()
profileReq:=&types.QuerySQLChainProfileReq{}
profileResp:=&types.QuerySQLChainProfileResp{}
profileReq.DBID=dbID
err=rpc.RequestBP(route.MCCQuerySQLChainProfile.String(), profileReq, profileResp)
iferr!=nil {
err=errors.Wrap(err, "get sqlchain profile failed in getPeers")
return
}
nodeIDs:=make([]proto.NodeID, len(profileResp.Profile.Miners))
iflen(profileResp.Profile.Miners) <=0 {
err=errors.Wrap(ErrInvalidProfile, "unexpected error in getPeers")
return
}
fori, mi:=rangeprofileResp.Profile.Miners {
nodeIDs[i] =mi.NodeID
}
peers=&proto.Peers{
PeersHeader: proto.PeersHeader{
Leader: nodeIDs[0],
Servers: nodeIDs[:],
},
}
err=peers.Sign(privKey)
iferr!=nil {
err=errors.Wrap(err, "sign peers failed in getPeers")
return
}
// set peers in the updater cache
peerList.Store(dbID, peers)
return
}
funcallocateConnAndSeq() (connIDuint64, seqNouint64) {
connIDLock.Lock()
deferconnIDLock.Unlock()
iflen(connIDAvail) ==0 {
// generate one
connID=randSource.Uint64()
seqNo=atomic.AddUint64(&globalSeqNo, 1)
return
}
// pop one conn
connID=connIDAvail[0]
connIDAvail=connIDAvail[1:]
seqNo=atomic.AddUint64(&globalSeqNo, 1)
return
}
funcputBackConn(connIDuint64) {
connIDLock.Lock()
deferconnIDLock.Unlock()
connIDAvail=append(connIDAvail, connID)
}