-
Notifications
You must be signed in to change notification settings - Fork 82
/
db.go
2214 lines (1808 loc) · 53.4 KB
/
db.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
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////////////////////////////////////////////////////////////////////////////////
// //
// Copyright 2019 Broadcom. The term Broadcom refers to Broadcom Inc. and/or //
// its subsidiaries. //
// //
// 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 db implements a wrapper over the go-redis/redis.
There may be an attempt to mimic sonic-py-swsssdk to ease porting of
code written in python using that SDK to Go Language.
Example:
- Initialization:
d, _ := db.NewDB(db.Options {
DBNo : db.ConfigDB,
InitIndicator : "CONFIG_DB_INITIALIZED",
TableNameSeparator: "|",
KeySeparator : "|",
})
- Close:
d.DeleteDB()
- No-Transaction SetEntry
tsa := db.TableSpec { Name: "ACL_TABLE" }
tsr := db.TableSpec { Name: "ACL_RULE" }
ca := make([]string, 1, 1)
ca[0] = "MyACL1_ACL_IPV4"
akey := db.Key { Comp: ca}
avalue := db.Value {map[string]string {"ports":"eth0","type":"mirror" }}
d.SetEntry(&tsa, akey, avalue)
- GetEntry
avalue, _ := d.GetEntry(&tsa, akey)
- GetKeys
keys, _ := d.GetKeys(&tsa);
- GetKeysPattern
keys, _ := d.GetKeys(&tsa, akeyPattern);
- No-Transaction DeleteEntry
d.DeleteEntry(&tsa, akey)
- GetTable
ta, _ := d.GetTable(&tsa)
- No-Transaction DeleteTable
d.DeleteTable(&ts)
- Transaction
rkey := db.Key { Comp: []string { "MyACL2_ACL_IPV4", "RULE_1" }}
rvalue := db.Value { Field: map[string]string {
"priority" : "0",
"packet_action" : "eth1",
},
}
d.StartTx([]db.WatchKeys { {Ts: &tsr, Key: &rkey} },
[]*db.TableSpec { &tsa, &tsr })
d.SetEntry( &tsa, akey, avalue)
d.SetEntry( &tsr, rkey, rvalue)
e := d.CommitTx()
- Transaction Abort
d.StartTx([]db.WatchKeys {},
[]*db.TableSpec { &tsa, &tsr })
d.DeleteEntry( &tsa, rkey)
d.AbortTx()
*/
package db
import (
"fmt"
"strconv"
// "reflect"
"errors"
"strings"
"time"
"github.com/Azure/sonic-mgmt-common/cvl"
cmn "github.com/Azure/sonic-mgmt-common/cvl/common"
"github.com/Azure/sonic-mgmt-common/translib/tlerr"
"github.com/go-redis/redis/v7"
"github.com/golang/glog"
)
const (
DefaultRedisUNIXSocket string = "/var/run/redis/redis.sock"
DefaultRedisLocalTCPEP string = "localhost:6379"
DefaultRedisRemoteTCPEP string = "127.0.0.1:6379"
DefaultRedisUNIXNetwork string = "unix"
DefaultRedisTCPNetwork string = "tcp"
)
func init() {
dbConfigInit()
}
// DBNum type indicates the type of DB (Eg: ConfigDB, ApplDB, ...).
type DBNum int
const (
ApplDB DBNum = iota // 0
AsicDB // 1
CountersDB // 2
LogLevelDB // 3
ConfigDB // 4
FlexCounterDB // 5
StateDB // 6
SnmpDB // 7
ErrorDB // 8
EventDB // 9
// All DBs added above this line, please ----
MaxDB // The Number of DBs
)
func (dbNo DBNum) String() string {
return getDBInstName(dbNo)
}
// ID returns the redis db id for this DBNum
func (dbNo DBNum) ID() int {
name := getDBInstName(dbNo)
if len(name) == 0 {
panic("Invalid DBNum " + fmt.Sprintf("%d", dbNo))
}
return getDbId(name)
}
// Options gives parameters for opening the redis client.
type Options struct {
DBNo DBNum
InitIndicator string
TableNameSeparator string //Overriden by the DB config file's separator.
KeySeparator string //Overriden by the DB config file's separator.
IsWriteDisabled bool //Is write/set mode disabled ?
IsCacheEnabled bool //Is cache (Per Connection) allowed?
// OnChange caching for the DBs passed from Translib's Subscribe Infra
// to the Apps. SDB is the SubscribeDB() returned handle on which
// notifications of change are received.
IsOnChangeEnabled bool // whether OnChange cache enabled
SDB *DB //The subscribeDB handle (Future Use)
IsSubscribeDB bool // Opened by SubscribeDB(Sess)?
IsSession bool // Is this a Candidate Config DB ?
ConfigDBLazyLock bool // For Non-CCDB Action()/RPC (may write to ConfigDB)
TxCmdsLim int // Tx Limit for Candidate Config DB
IsReplaced bool // Is candidate Config DB updated by config-replace operation.
IsCommitted bool // Is candidate Config DB committed.
// Alternate Datastore: By default, we query redis CONFIG_DB.
// Front-end an alternate source of data. (Eg: config_db.cp.json
// from a saved commit-id, or snapshot)
Datastore DBDatastore
DisableCVLCheck bool
}
func (o Options) String() string {
return fmt.Sprintf(
"{ DBNo: %v, InitIndicator: %v, TableNameSeparator: %v, KeySeparator: %v, IsWriteDisabled: %v, IsCacheEnabled: %v, IsOnChangeEnabled: %v, SDB: %v, DisableCVLCheck: %v, IsSession: %v, ConfigDBLazyLock: %v, TxCmdsLim: %v }",
o.DBNo, o.InitIndicator, o.TableNameSeparator, o.KeySeparator,
o.IsWriteDisabled, o.IsCacheEnabled, o.IsOnChangeEnabled, o.SDB,
o.DisableCVLCheck, o.IsSession, o.ConfigDBLazyLock, o.TxCmdsLim)
}
type _txState int
const (
txStateNone _txState = iota // Idle (No transaction)
txStateWatch // WATCH issued
txStateSet // At least one Set|Mod|Delete done.
txStateMultiExec // Between MULTI & EXEC
)
func (s _txState) String() string {
var state string
switch s {
case txStateNone:
state = "txStateNone"
case txStateWatch:
state = "txStateWatch"
case txStateSet:
state = "txStateSet"
case txStateMultiExec:
state = "txStateMultiExec"
default:
state = "Unknown _txState"
}
return state
}
const (
InitialTxPipelineSize int = 100
InitialTablesCount int = 20
InitialTableEntryCount int = 50
InitialTablePatternCount int = 5
InitialMapsCount int = 10
InitialMapKeyCount int = 50
)
// TableSpec gives the name of the table, and other per-table customizations.
// (Eg: { Name: ACL_TABLE" }).
type TableSpec struct {
Name string
// https://github.com/project-arlo/sonic-mgmt-framework/issues/29
// CompCt tells how many components in the key. Only the last component
// can have TableSeparator as part of the key. Otherwise, we cannot
// tell where the key component begins.
CompCt int
// NoDelete flag (if it is set to true) is to skip the row entry deletion from
// the table when the "SetEntry" or "ModEntry" method is called with empty Value Field map.
NoDelete bool
}
const (
ConnectionClosed = tlerr.TranslibDBInvalidState("connection closed")
OnChangeDisabled = tlerr.TranslibDBInvalidState("OnChange disabled")
SupportsReadOnly = tlerr.TranslibDBInvalidState("Supported on read only")
OnChangeNoSupport = tlerr.TranslibDBInvalidState("OnChange not supported")
SupportsCfgDBOnly = tlerr.TranslibDBInvalidState("Supported on CfgDB only")
UseGetEntry = tlerr.TranslibDBInvalidState("Use GetEntry()")
)
type _txOp int
const (
txOpNone _txOp = iota // No Op
txOpHMSet // key, value gives the field:value to be set in key
txOpHDel // key, value gives the fields to be deleted in key
txOpDel // key
)
type _txCmd struct {
ts *TableSpec
op _txOp
key *Key
value *Value
}
// DB is the main type.
type DB struct {
client *redis.Client
Opts *Options
txState _txState
txCmds []_txCmd
txTsEntryMap map[string]map[string]Value //map[TableSpec.Name]map[Entry]Value
// For Config Session only, cache the HGetAll for restoring the
// txTsEntryMap on error recovery/rollback. This avoids the duplicate
// read for recovery/rollback. The Config DB is locked, therefore
// it need not be read again.
txTsEntryHGetAll map[string]map[string]Value //map[TableSpec.Name]map[Entry]Value
cv *cvl.CVL
cvlHintsB4Open map[string]interface{} // Hints set before CVLSess Opened
cvlEditConfigData []cmn.CVLEditConfigData
// If there is an error while Rollback (or similar), set this flag.
// In this state, all writes are disabled, and this error is returned.
err error // CVL Rollback/CVL/Commit error
sPubSub *redis.PubSub // PubSub. non-Nil implies SubscribeDB
sCIP bool // Close in Progress
sOnCCacheDB *DB // Update this DB for PubSub notifications
dbStatsConfig DBStatsConfig
dbCacheConfig DBCacheConfig
// DBStats is used by both PerConnection cache, and OnChange cache
// On a DB handle, the two are mutually exclusive.
stats DBStats
cache dbCache
onCReg dbOnChangeReg // holds OnChange enabled table names
// PubSubRpc
rPubSub *redis.PubSub
// Non-Session Config DB Lock acquired
configDBLocked bool
}
func (d DB) String() string {
return fmt.Sprintf("{ client: %v, Opts: %v, txState: %v, tsCmds: %v }",
d.client, d.Opts, d.txState, d.txCmds)
}
func (dbNo DBNum) Name() string {
return (getDBInstName(dbNo))
}
func (d *DB) IsDirtified() bool {
return (len(d.txCmds) > 0)
}
func getDBInstName(dbNo DBNum) string {
switch dbNo {
case ApplDB:
return "APPL_DB"
case AsicDB:
return "ASIC_DB"
case CountersDB:
return "COUNTERS_DB"
case LogLevelDB:
return "LOGLEVEL_DB"
case ConfigDB:
return "CONFIG_DB"
case FlexCounterDB:
return "FLEX_COUNTER_DB"
case StateDB:
return "STATE_DB"
case SnmpDB:
return "SNMP_OVERLAY_DB"
case ErrorDB:
return "ERROR_DB"
case EventDB:
return "EVENT_DB"
}
return ""
}
func GetdbNameToIndex(dbName string) DBNum {
dbIndex := ConfigDB
switch dbName {
case "APPL_DB":
dbIndex = ApplDB
case "ASIC_DB":
dbIndex = AsicDB
case "COUNTERS_DB":
dbIndex = CountersDB
case "LOGLEVEL_DB":
dbIndex = LogLevelDB
case "CONFIG_DB":
dbIndex = ConfigDB
case "FLEX_COUNTER_DB":
dbIndex = FlexCounterDB
case "STATE_DB":
dbIndex = StateDB
case "ERROR_DB":
dbIndex = ErrorDB
case "EVENT_DB":
dbIndex = EventDB
}
return dbIndex
}
// NewDB is the factory method to create new DB's.
func NewDB(opt Options) (*DB, error) {
var e error
if glog.V(3) {
glog.Info("NewDB: Begin: opt: ", opt)
}
// Time Start
var now time.Time
var dur time.Duration
now = time.Now()
d := DB{client: redis.NewClient(adjustRedisOpts(&opt)),
Opts: &opt,
txState: txStateNone,
txCmds: make([]_txCmd, 0, InitialTxPipelineSize),
cvlEditConfigData: make([]cmn.CVLEditConfigData, 0, InitialTxPipelineSize),
dbStatsConfig: getDBStatsConfig(),
stats: DBStats{Tables: make(map[string]Stats, InitialTablesCount), Maps: make(map[string]Stats, InitialMapsCount)},
dbCacheConfig: getDBCacheConfig(),
cache: dbCache{Tables: make(map[string]Table, InitialTablesCount), Maps: make(map[string]MAP, InitialMapsCount)},
}
if d.client == nil {
glog.Error("NewDB: Could not create redis client: ", d.Name())
e = tlerr.TranslibDBCannotOpen{}
goto NewDBExit
}
if opt.IsCacheEnabled && opt.IsOnChangeEnabled {
glog.Error("Per Connection cache cannot be enabled with OnChange cache")
glog.Error("Disabling Per Connection caching")
opt.IsCacheEnabled = false
}
if opt.IsOnChangeEnabled && !opt.IsWriteDisabled {
glog.Errorf("NewDB: IsEnableOnChange cannot be set on write enabled DB")
e = tlerr.TranslibDBCannotOpen{}
goto NewDBExit
}
if !d.Opts.IsWriteDisabled {
if d.dbCacheConfig.PerConnection {
glog.Info("NewDB: IsWriteDisabled false. Disable Cache")
}
d.dbCacheConfig.PerConnection = false
}
if !d.Opts.IsCacheEnabled {
if d.dbCacheConfig.PerConnection {
glog.Info("NewDB: IsCacheEnabled false. Disable Cache")
}
d.dbCacheConfig.PerConnection = false
}
if opt.IsSession && d.dbCacheConfig.PerConnection {
if d.dbCacheConfig.PerConnection {
glog.Info("NewDB: IsSession true. Disable Cache")
}
d.dbCacheConfig.PerConnection = false
}
if opt.IsSession && opt.IsOnChangeEnabled {
glog.Error("NewDB: Subscription on Config Session not supported : ",
d.Name())
d.client.Close()
e = tlerr.TranslibDBNotSupported{
Description: "Subscription on Config Session not supported"}
goto NewDBExit
}
if opt.IsSession && opt.DBNo != ConfigDB {
glog.Error("NewDB: Non-Config DB on Config Session not supported : ",
d.Name())
d.client.Close()
e = tlerr.TranslibDBNotSupported{
Description: "Non-Config DB on Config Session not supported"}
goto NewDBExit
}
if opt.IsOnChangeEnabled {
d.onCReg = dbOnChangeReg{CacheTables: make(map[string]bool, InitialTablesCount)}
}
if opt.DBNo != ConfigDB {
if glog.V(3) {
glog.Info("NewDB: ! ConfigDB. Skip init. check.")
}
goto NewDBSkipInitIndicatorCheck
}
if len(d.Opts.InitIndicator) == 0 {
if glog.V(3) {
glog.Info("NewDB: Init indication not requested")
}
} else {
glog.V(3).Info("NewDB: RedisCmd: ", d.Name(), ": ", "GET ",
d.Opts.InitIndicator)
if init, err := d.client.Get(d.Opts.InitIndicator).Int(); init != 1 {
glog.Error("NewDB: Database not inited: ", d.Name(), ": GET ",
d.Opts.InitIndicator)
if err != nil {
glog.Error("NewDB: Database not inited: ", d.Name(), ": GET ",
d.Opts.InitIndicator, " returns err: ", err)
}
d.client.Close()
e = tlerr.TranslibDBNotInit{}
goto NewDBExit
}
}
// Lazy ConfigDBLock, because Action()/RPC ConfigDB Modifiers do not
// tell in advance whether they are going to perform a Write Operation,
// and we do not want to block a Read Operation on Action()/RPC
if opt.DBNo == ConfigDB && !opt.IsSession &&
!opt.IsWriteDisabled && !opt.ConfigDBLazyLock {
if e = ConfigDBTryLock(noSessionToken); e != nil {
glog.Errorf("NewDB: ConfigDB possibly locked: %s", e)
d.client.Close()
goto NewDBExit
}
d.configDBLocked = true
}
// Register Candidate Config (Session) DBs
if opt.IsSession {
d.registerSessionDB()
}
NewDBSkipInitIndicatorCheck:
NewDBExit:
if d.dbStatsConfig.TimeStats {
dur = time.Since(now)
}
dbGlobalStats.updateStats(d.Opts.DBNo, true, dur, &(d.stats))
if glog.V(3) {
glog.Info("NewDB: End: d: ", d, " e: ", e)
}
return &d, e
}
// DeleteDB is the gentle way to close the DB connection.
func (d *DB) DeleteDB() error {
if d == nil {
return nil
}
if glog.V(3) {
glog.Info("DeleteDB: Begin: d: ", d)
}
// Release the ConfigDB Lock if we placed on in NewDB()
if d.configDBLocked {
ConfigDBUnlock(noSessionToken)
d.configDBLocked = false
}
if !d.IsOpen() {
return ConnectionClosed
}
dbGlobalStats.updateStats(d.Opts.DBNo, false, 0, &(d.stats))
if d.txState != txStateNone {
glog.Warning("DeleteDB: not txStateNone, txState: ", d.txState)
}
// Unregister Candidate Config (Session) DB
if d.Opts.IsSession {
d.unRegisterSessionDB()
}
err := d.client.Close()
d.client = nil
return err
}
func (d *DB) IsOpen() bool {
return d != nil && d.client != nil
}
func (d *DB) key2redis(ts *TableSpec, key Key) string {
if glog.V(5) {
glog.Info("key2redis: Begin: ",
ts.Name+
d.Opts.TableNameSeparator+
strings.Join(key.Comp, d.Opts.KeySeparator))
}
return ts.Name +
d.Opts.TableNameSeparator +
strings.Join(key.Comp, d.Opts.KeySeparator)
}
func (d *DB) redis2key(ts *TableSpec, redisKey string) Key {
splitTable := strings.SplitN(redisKey, d.Opts.TableNameSeparator, 2)
if ts.CompCt > 0 {
return Key{strings.SplitN(splitTable[1], d.Opts.KeySeparator, ts.CompCt)}
} else {
return Key{strings.Split(splitTable[1], d.Opts.KeySeparator)}
}
}
// redis2ts_key works only if keys don't contain the (Table|Key)Separator char
// (The TableSpec does not have the CompCt)
func (d *DB) redis2ts_key(redisKey string) (TableSpec, Key) {
splitTable := strings.SplitN(redisKey, d.Opts.TableNameSeparator, 2)
return TableSpec{Name: splitTable[0]},
Key{strings.Split(splitTable[1], d.Opts.KeySeparator)}
}
func (d *DB) ts2redisUpdated(ts *TableSpec) string {
if glog.V(5) {
glog.Info("ts2redisUpdated: Begin: ", ts.Name)
}
var updated string
if strings.Contains(ts.Name, "*") {
updated = string("CONFIG_DB_UPDATED")
} else {
updated = string("CONFIG_DB_UPDATED_") + ts.Name
}
return updated
}
// GetEntry retrieves an entry(row) from the table.
func (d *DB) GetEntry(ts *TableSpec, key Key) (Value, error) {
if !d.IsOpen() {
return Value{}, ConnectionClosed
}
return d.getEntry(ts, key, false)
}
func (d *DB) getEntry(ts *TableSpec, key Key, forceReadDB bool) (Value, error) {
if glog.V(3) {
glog.Info("GetEntry: Begin: ", d.Name(), ": ts: ", ts, " key: ", key)
}
// GetEntryHits
// Time Start
var cacheHit bool
var txCacheHit bool
var now time.Time
var dur time.Duration
var stats Stats
if d.dbStatsConfig.TimeStats {
now = time.Now()
}
var table Table
var value Value
var e error
var v map[string]string
var ok bool
entry := d.key2redis(ts, key)
useCache := ((d.Opts.IsOnChangeEnabled && d.onCReg.isCacheTable(ts.Name)) ||
(d.dbCacheConfig.PerConnection &&
d.dbCacheConfig.isCacheTable(ts.Name)))
// check in Tx cache first
if value, ok = d.txTsEntryMap[ts.Name][entry]; !ok {
// If cache GetFromCache (CacheHit?)
if useCache && !forceReadDB {
if table, ok = d.cache.Tables[ts.Name]; ok {
if value, ok = table.entry[entry]; ok {
value = value.Copy()
cacheHit = true
}
}
}
} else {
value = value.Copy()
txCacheHit = true
}
if !cacheHit && !txCacheHit {
// Increase (i.e. more verbose) V() level if it gets too noisy.
if glog.V(3) {
glog.Info("getEntry: RedisCmd: ", d.Name(), ": ", "HGETALL ", entry)
}
v, e = d.client.HGetAll(entry).Result()
value = Value{Field: v}
}
if e != nil {
if glog.V(2) {
glog.Errorf("GetEntry: %s: HGetAll(%q) error: %v", d.Name(),
entry, e)
}
value = Value{}
} else if !value.IsPopulated() {
if glog.V(4) {
glog.Info("GetEntry: HGetAll(): empty map")
}
e = tlerr.TranslibRedisClientEntryNotExist{Entry: d.key2redis(ts, key)}
} else if !cacheHit && !txCacheHit && useCache {
if _, ok := d.cache.Tables[ts.Name]; !ok {
if d.cache.Tables == nil {
d.cache.Tables = make(map[string]Table, d.onCReg.size())
}
d.cache.Tables[ts.Name] = Table{
ts: ts,
entry: make(map[string]Value, InitialTableEntryCount),
complete: false,
patterns: make(map[string][]Key, InitialTablePatternCount),
db: d,
}
}
d.cache.Tables[ts.Name].entry[entry] = value.Copy()
}
// Time End, Time, Peak
if d.dbStatsConfig.TableStats {
stats = d.stats.Tables[ts.Name]
} else {
stats = d.stats.AllTables
}
stats.Hits++
stats.GetEntryHits++
if cacheHit {
stats.GetEntryCacheHits++
}
if d.dbStatsConfig.TimeStats {
dur = time.Since(now)
if dur > stats.Peak {
stats.Peak = dur
}
stats.Time += dur
if dur > stats.GetEntryPeak {
stats.GetEntryPeak = dur
}
stats.GetEntryTime += dur
}
if d.dbStatsConfig.TableStats {
d.stats.Tables[ts.Name] = stats
} else {
d.stats.AllTables = stats
}
if glog.V(3) {
glog.Info("GetEntry: End: ", "value: ", value, " e: ", e)
}
return value, e
}
// GetKeys retrieves all entry/row keys.
func (d *DB) GetKeys(ts *TableSpec) ([]Key, error) {
// If ts contains (Key|TableName)Separator (Eg: "|"), translate this to
// a GetKeysPattern, by extracting the initial Key Comps from TableName
// Slice into the t(able) (a)N(d) k(ey)Pat(tern) if any
if tNkPat := strings.SplitN(ts.Name, d.Opts.TableNameSeparator,
2); len(tNkPat) == 2 {
tsNk := &TableSpec{Name: tNkPat[0], CompCt: ts.CompCt}
pat := Key{Comp: append(strings.Split(tNkPat[1], d.Opts.KeySeparator),
"*")}
glog.Warningf("GetKeys: Separator in TableSpec %v is Deprecated. "+
"Using TableSpec.Name %s, Pattern %v", ts, tsNk.Name, pat)
return d.GetKeysPattern(tsNk, pat)
}
return d.GetKeysPattern(ts, Key{Comp: []string{"*"}})
}
func (d *DB) GetKeysPattern(ts *TableSpec, pat Key) ([]Key, error) {
// GetKeysHits
// Time Start
var cacheHit bool
var now time.Time
var dur time.Duration
var stats Stats
var table Table
var keys []Key
var e error
if glog.V(3) {
glog.Info("GetKeys: Begin: ", d.Name(), ": ts: ", ts, "pat: ", pat)
}
if !d.IsOpen() {
return keys, ConnectionClosed
}
defer func() {
if e != nil {
glog.Error("GetKeys: ts: ", ts, " e: ", e)
}
if glog.V(3) {
glog.Info("GetKeys: End: ", "keys: ", keys, " e: ", e)
}
}()
if d.dbStatsConfig.TimeStats {
now = time.Now()
}
// If cache GetFromCache (CacheHit?)
if d.dbCacheConfig.PerConnection && d.dbCacheConfig.isCacheTable(ts.Name) {
var ok bool
if table, ok = d.cache.Tables[ts.Name]; ok {
if keys, ok = table.patterns[d.key2redis(ts, pat)]; ok {
cacheHit = true
}
}
}
if !cacheHit {
// Increase (i.e. more verbose) V() level if it gets too noisy.
if glog.V(3) {
glog.Info("GetKeysPattern: RedisCmd: ", d.Name(), ": ", "KEYS ", d.key2redis(ts, pat))
}
var redisKeys []string
redisKeys, e = d.client.Keys(d.key2redis(ts, pat)).Result()
keys = make([]Key, 0, len(redisKeys))
// On error, return promptly
if e != nil {
return keys, e
}
for i := 0; i < len(redisKeys); i++ {
keys = append(keys, d.redis2key(ts, redisKeys[i]))
}
// If cache SetCache (i.e. a cache miss)
if d.dbCacheConfig.PerConnection && d.dbCacheConfig.isCacheTable(ts.Name) {
if _, ok := d.cache.Tables[ts.Name]; !ok {
d.cache.Tables[ts.Name] = Table{
ts: ts,
entry: make(map[string]Value, InitialTableEntryCount),
complete: false,
patterns: make(map[string][]Key, InitialTablePatternCount),
db: d,
}
}
// Make a copy for the Per Connection cache which is always
// *before* adjusting with Redis CAS Tx Cache.
keysCopy := make([]Key, len(keys))
for i, key := range keys {
keysCopy[i] = key.Copy()
}
d.cache.Tables[ts.Name].patterns[d.key2redis(ts, pat)] = keysCopy
}
}
for k := range d.txTsEntryMap[ts.Name] {
if patternMatch(k, 0, d.key2redis(ts, pat), 0) {
var present bool
var index int
key := d.redis2key(ts, k)
for i := 0; i < len(keys); i++ {
index = i
if key.Equals(keys[i]) {
present = true
break
}
}
if !present {
if len(d.txTsEntryMap[ts.Name][k].Field) > 0 {
keys = append(keys, key)
}
} else {
if len(d.txTsEntryMap[ts.Name][k].Field) == 0 {
keys = append(keys[:index], keys[index+1:]...)
}
}
}
}
// Time End, Time, Peak
if d.dbStatsConfig.TableStats {
stats = d.stats.Tables[ts.Name]
} else {
stats = d.stats.AllTables
}
stats.Hits++
stats.GetKeysPatternHits++
if cacheHit {
stats.GetKeysPatternCacheHits++
}
if (len(pat.Comp) == 1) && (pat.Comp[0] == "*") {
stats.GetKeysHits++
if cacheHit {
stats.GetKeysCacheHits++
}
}
if d.dbStatsConfig.TimeStats {
dur = time.Since(now)
if dur > stats.Peak {
stats.Peak = dur
}
stats.Time += dur
if dur > stats.GetKeysPatternPeak {
stats.GetKeysPatternPeak = dur
}
stats.GetKeysPatternTime += dur
if (len(pat.Comp) == 1) && (pat.Comp[0] == "*") {
if dur > stats.GetKeysPeak {
stats.GetKeysPeak = dur
}
stats.GetKeysTime += dur
}
}
if d.dbStatsConfig.TableStats {
d.stats.Tables[ts.Name] = stats
} else {
d.stats.AllTables = stats
}
return keys, e
}
// GetKeysByPattern retrieves all entry/row keys matching with the given pattern
// Deprecated: use GetKeysPattern()
func (d *DB) GetKeysByPattern(ts *TableSpec, pattern string) ([]Key, error) {
glog.Warning("GetKeysByPattern() is deprecated and it will be removed in the future, please use GetKeysPattern()")
return d.GetKeysPattern(ts, Key{Comp: []string{pattern}})
}
// DeleteKeys deletes all entry/row keys matching a pattern.
func (d *DB) DeleteKeys(ts *TableSpec, key Key) error {
if glog.V(3) {
glog.Info("DeleteKeys: Begin: ", d.Name(), ": ts: ", ts, " key: ", key)
}
if !d.IsOpen() {
return ConnectionClosed
}
// This can be done via a LUA script as well. For now do this. TBD
redisKeys, e := d.GetKeysPattern(ts, key)
if glog.V(4) {
glog.Info("DeleteKeys: redisKeys: ", redisKeys, " e: ", e)
}
for i := 0; i < len(redisKeys); i++ {
if glog.V(4) {
glog.Info("DeleteKeys: Deleting redisKey: ", redisKeys[i])
}
e = d.DeleteEntry(ts, redisKeys[i])
if e != nil {
glog.Warning("DeleteKeys: Deleting: ts: ", ts, " key",
redisKeys[i], " : ", e)
}
}
if glog.V(3) {
glog.Info("DeleteKeys: End: e: ", e)
}
return e
}
func (d *DB) doCVL(ts *TableSpec, cvlOps []cmn.CVLOperation, key Key, vals []Value) error {
var e error = nil
var cvlRetCode cvl.CVLRetCode
var cei cvl.CVLErrorInfo
if d.err != nil {
e = d.err
glog.Error("doCVL: DB in error: ", e)
goto doCVLExit
}
if d.Opts.DisableCVLCheck {
glog.Info("doCVL: CVL Disabled. Skipping CVL")
goto doCVLExit
}
// No Transaction case. No CVL.
if d.txState == txStateNone {
glog.Info("doCVL: No Transactions. Skipping CVL")
goto doCVLExit
}
if len(cvlOps) != len(vals) {