-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
kv_mdbx.go
2204 lines (1935 loc) · 56.1 KB
/
kv_mdbx.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 2021 Erigon contributors
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 mdbx
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/c2h5oh/datasize"
"github.com/erigontech/mdbx-go/mdbx"
stack2 "github.com/go-stack/stack"
"github.com/ledgerwatch/log/v3"
"golang.org/x/exp/maps"
"golang.org/x/sync/semaphore"
"github.com/ledgerwatch/erigon-lib/common/dbg"
"github.com/ledgerwatch/erigon-lib/common/dir"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/ledgerwatch/erigon-lib/kv/iter"
"github.com/ledgerwatch/erigon-lib/kv/order"
"github.com/ledgerwatch/erigon-lib/mmap"
)
const NonExistingDBI kv.DBI = 999_999_999
type TableCfgFunc func(defaultBuckets kv.TableCfg) kv.TableCfg
func WithChaindataTables(defaultBuckets kv.TableCfg) kv.TableCfg {
return defaultBuckets
}
type MdbxOpts struct {
// must be in the range from 12.5% (almost empty) to 50% (half empty)
// which corresponds to the range from 8192 and to 32768 in units respectively
log log.Logger
roTxsLimiter *semaphore.Weighted
bucketsCfg TableCfgFunc
path string
syncPeriod time.Duration
mapSize datasize.ByteSize
growthStep datasize.ByteSize
shrinkThreshold int
flags uint
pageSize uint64
dirtySpace uint64 // if exeed this space, modified pages will `spill` to disk
mergeThreshold uint64
verbosity kv.DBVerbosityLvl
label kv.Label // marker to distinct db instances - one process may open many databases. for example to collect metrics of only 1 database
inMem bool
}
const DefaultMapSize = 2 * datasize.TB
const DefaultGrowthStep = 2 * datasize.GB
func NewMDBX(log log.Logger) MdbxOpts {
opts := MdbxOpts{
bucketsCfg: WithChaindataTables,
flags: mdbx.NoReadahead | mdbx.Coalesce | mdbx.Durable,
log: log,
pageSize: kv.DefaultPageSize(),
mapSize: DefaultMapSize,
growthStep: DefaultGrowthStep,
mergeThreshold: 3 * 8192,
shrinkThreshold: -1, // default
label: kv.InMem,
}
return opts
}
func (opts MdbxOpts) GetLabel() kv.Label { return opts.label }
func (opts MdbxOpts) GetInMem() bool { return opts.inMem }
func (opts MdbxOpts) GetPageSize() uint64 { return opts.pageSize }
func (opts MdbxOpts) Label(label kv.Label) MdbxOpts {
opts.label = label
return opts
}
func (opts MdbxOpts) DirtySpace(s uint64) MdbxOpts {
opts.dirtySpace = s
return opts
}
func (opts MdbxOpts) RoTxsLimiter(l *semaphore.Weighted) MdbxOpts {
opts.roTxsLimiter = l
return opts
}
func (opts MdbxOpts) PageSize(v uint64) MdbxOpts {
opts.pageSize = v
return opts
}
func (opts MdbxOpts) GrowthStep(v datasize.ByteSize) MdbxOpts {
opts.growthStep = v
return opts
}
func (opts MdbxOpts) Path(path string) MdbxOpts {
opts.path = path
return opts
}
func (opts MdbxOpts) Set(opt MdbxOpts) MdbxOpts {
return opt
}
func (opts MdbxOpts) InMem(tmpDir string) MdbxOpts {
if tmpDir != "" {
if err := os.MkdirAll(tmpDir, 0755); err != nil {
panic(err)
}
}
path, err := os.MkdirTemp(tmpDir, "erigon-memdb-")
if err != nil {
panic(err)
}
opts.path = path
opts.inMem = true
opts.flags = mdbx.UtterlyNoSync | mdbx.NoMetaSync | mdbx.NoMemInit
opts.growthStep = 2 * datasize.MB
opts.mapSize = 512 * datasize.MB
opts.dirtySpace = uint64(128 * datasize.MB)
opts.shrinkThreshold = 0 // disable
opts.label = kv.InMem
return opts
}
func (opts MdbxOpts) Exclusive() MdbxOpts {
opts.flags = opts.flags | mdbx.Exclusive
return opts
}
func (opts MdbxOpts) Flags(f func(uint) uint) MdbxOpts {
opts.flags = f(opts.flags)
return opts
}
func (opts MdbxOpts) HasFlag(flag uint) bool { return opts.flags&flag != 0 }
func (opts MdbxOpts) Readonly() MdbxOpts {
opts.flags = opts.flags | mdbx.Readonly
return opts
}
func (opts MdbxOpts) Accede() MdbxOpts {
opts.flags = opts.flags | mdbx.Accede
return opts
}
func (opts MdbxOpts) SyncPeriod(period time.Duration) MdbxOpts {
opts.syncPeriod = period
return opts
}
func (opts MdbxOpts) DBVerbosity(v kv.DBVerbosityLvl) MdbxOpts {
opts.verbosity = v
return opts
}
func (opts MdbxOpts) MapSize(sz datasize.ByteSize) MdbxOpts {
opts.mapSize = sz
return opts
}
func (opts MdbxOpts) WriteMap() MdbxOpts {
opts.flags |= mdbx.WriteMap
return opts
}
func (opts MdbxOpts) LifoReclaim() MdbxOpts {
opts.flags |= mdbx.LifoReclaim
return opts
}
func (opts MdbxOpts) WriteMergeThreshold(v uint64) MdbxOpts {
opts.mergeThreshold = v
return opts
}
func (opts MdbxOpts) WithTableCfg(f TableCfgFunc) MdbxOpts {
opts.bucketsCfg = f
return opts
}
var pathDbMap = map[string]kv.RoDB{}
var pathDbMapLock sync.Mutex
func addToPathDbMap(path string, db kv.RoDB) {
pathDbMapLock.Lock()
defer pathDbMapLock.Unlock()
pathDbMap[path] = db
}
func removeFromPathDbMap(path string) {
pathDbMapLock.Lock()
defer pathDbMapLock.Unlock()
delete(pathDbMap, path)
}
func PathDbMap() map[string]kv.RoDB {
pathDbMapLock.Lock()
defer pathDbMapLock.Unlock()
return maps.Clone(pathDbMap)
}
var ErrDBDoesNotExists = fmt.Errorf("can't create database - because opening in `Accede` mode. probably another (main) process can create it")
func (opts MdbxOpts) Open(ctx context.Context) (kv.RwDB, error) {
if dbg.WriteMap() {
opts = opts.WriteMap() //nolint
}
if dbg.DirtySpace() > 0 {
opts = opts.DirtySpace(dbg.DirtySpace()) //nolint
}
if dbg.NoSync() {
opts = opts.Flags(func(u uint) uint { return u | mdbx.SafeNoSync }) //nolint
}
if dbg.MergeTr() > 0 {
opts = opts.WriteMergeThreshold(uint64(dbg.MergeTr() * 8192)) //nolint
}
if dbg.MdbxReadAhead() {
opts = opts.Flags(func(u uint) uint { return u &^ mdbx.NoReadahead }) //nolint
}
if opts.flags&mdbx.Accede != 0 || opts.flags&mdbx.Readonly != 0 {
for retry := 0; ; retry++ {
exists := dir.FileExist(filepath.Join(opts.path, "mdbx.dat"))
if exists {
break
}
if retry >= 5 {
return nil, fmt.Errorf("%w, label: %s, path: %s", ErrDBDoesNotExists, opts.label.String(), opts.path)
}
select {
case <-time.After(500 * time.Millisecond):
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
env, err := mdbx.NewEnv()
if err != nil {
return nil, err
}
if opts.label == kv.ChainDB && opts.verbosity != -1 {
err = env.SetDebug(mdbx.LogLvl(opts.verbosity), mdbx.DbgDoNotChange, mdbx.LoggerDoNotChange) // temporary disable error, because it works if call it 1 time, but returns error if call it twice in same process (what often happening in tests)
if err != nil {
return nil, fmt.Errorf("db verbosity set: %w", err)
}
}
if err = env.SetOption(mdbx.OptMaxDB, 200); err != nil {
return nil, err
}
if err = env.SetOption(mdbx.OptMaxReaders, kv.ReadersLimit); err != nil {
return nil, err
}
if !opts.HasFlag(mdbx.Accede) {
if err = env.SetGeometry(-1, -1, int(opts.mapSize), int(opts.growthStep), opts.shrinkThreshold, int(opts.pageSize)); err != nil {
return nil, err
}
if err = os.MkdirAll(opts.path, 0744); err != nil {
return nil, fmt.Errorf("could not create dir: %s, %w", opts.path, err)
}
}
// erigon using big transactions
// increase "page measured" options. need do it after env.Open() because default are depend on pageSize known only after env.Open()
if !opts.HasFlag(mdbx.Readonly) {
// 1/8 is good for transactions with a lot of modifications - to reduce invalidation size.
// But Erigon app now using Batch and etl.Collectors to avoid writing to DB frequently changing data.
// It means most of our writes are: APPEND or "single UPSERT per key during transaction"
//if err = env.SetOption(mdbx.OptSpillMinDenominator, 8); err != nil {
// return nil, err
//}
txnDpInitial, err := env.GetOption(mdbx.OptTxnDpInitial)
if err != nil {
return nil, err
}
if opts.label == kv.ChainDB {
if err = env.SetOption(mdbx.OptTxnDpInitial, txnDpInitial*2); err != nil {
return nil, err
}
dpReserveLimit, err := env.GetOption(mdbx.OptDpReverseLimit)
if err != nil {
return nil, err
}
if err = env.SetOption(mdbx.OptDpReverseLimit, dpReserveLimit*2); err != nil {
return nil, err
}
}
// before env.Open() we don't know real pageSize. but will be implemented soon: https://gitflic.ru/project/erthink/libmdbx/issue/15
// but we want call all `SetOption` before env.Open(), because:
// - after they will require rwtx-lock, which is not acceptable in ACCEDEE mode.
pageSize := opts.pageSize
if pageSize == 0 {
pageSize = kv.DefaultPageSize()
}
var dirtySpace uint64
if opts.dirtySpace > 0 {
dirtySpace = opts.dirtySpace
} else {
dirtySpace = mmap.TotalMemory() / 42 // it's default of mdbx, but our package also supports cgroups and GOMEMLIMIT
// clamp to max size
const dirtySpaceMaxChainDB = uint64(1 * datasize.GB)
const dirtySpaceMaxDefault = uint64(128 * datasize.MB)
if opts.label == kv.ChainDB && dirtySpace > dirtySpaceMaxChainDB {
dirtySpace = dirtySpaceMaxChainDB
} else if opts.label != kv.ChainDB && dirtySpace > dirtySpaceMaxDefault {
dirtySpace = dirtySpaceMaxDefault
}
}
//can't use real pagesize here - it will be known only after env.Open()
if err = env.SetOption(mdbx.OptTxnDpLimit, dirtySpace/pageSize); err != nil {
return nil, err
}
// must be in the range from 12.5% (almost empty) to 50% (half empty)
// which corresponds to the range from 8192 and to 32768 in units respectively
if err = env.SetOption(mdbx.OptMergeThreshold16dot16Percent, opts.mergeThreshold); err != nil {
return nil, err
}
}
err = env.Open(opts.path, opts.flags, 0664)
if err != nil {
return nil, fmt.Errorf("%w, label: %s, trace: %s", err, opts.label.String(), stack2.Trace().String())
}
// mdbx will not change pageSize if db already exists. means need read real value after env.open()
in, err := env.Info(nil)
if err != nil {
return nil, fmt.Errorf("%w, label: %s, trace: %s", err, opts.label.String(), stack2.Trace().String())
}
opts.pageSize = uint64(in.PageSize)
opts.mapSize = datasize.ByteSize(in.MapSize)
if opts.label == kv.ChainDB {
opts.log.Info("[db] open", "label", opts.label, "sizeLimit", opts.mapSize, "pageSize", opts.pageSize)
} else {
opts.log.Debug("[db] open", "label", opts.label, "sizeLimit", opts.mapSize, "pageSize", opts.pageSize)
}
dirtyPagesLimit, err := env.GetOption(mdbx.OptTxnDpLimit)
if err != nil {
return nil, err
}
if opts.syncPeriod != 0 {
if err = env.SetSyncPeriod(opts.syncPeriod); err != nil {
env.Close()
return nil, err
}
}
//if err := env.SetOption(mdbx.OptSyncBytes, uint64(math2.MaxUint64)); err != nil {
// return nil, err
//}
if opts.roTxsLimiter == nil {
targetSemCount := int64(runtime.GOMAXPROCS(-1) * 16)
opts.roTxsLimiter = semaphore.NewWeighted(targetSemCount) // 1 less than max to allow unlocking to happen
}
txsCountMutex := &sync.Mutex{}
db := &MdbxKV{
opts: opts,
env: env,
log: opts.log,
buckets: kv.TableCfg{},
txSize: dirtyPagesLimit * opts.pageSize,
roTxsLimiter: opts.roTxsLimiter,
txsCountMutex: txsCountMutex,
txsAllDoneOnCloseCond: sync.NewCond(txsCountMutex),
leakDetector: dbg.NewLeakDetector("db."+opts.label.String(), dbg.SlowTx()),
MaxBatchSize: DefaultMaxBatchSize,
MaxBatchDelay: DefaultMaxBatchDelay,
}
customBuckets := opts.bucketsCfg(kv.ChaindataTablesCfg)
for name, cfg := range customBuckets { // copy map to avoid changing global variable
db.buckets[name] = cfg
}
buckets := bucketSlice(db.buckets)
if err := db.openDBIs(buckets); err != nil {
return nil, err
}
// Configure buckets and open deprecated buckets
if err := env.View(func(tx *mdbx.Txn) error {
for _, name := range buckets {
// Open deprecated buckets if they exist, don't create
if !db.buckets[name].IsDeprecated {
continue
}
cnfCopy := db.buckets[name]
dbi, createErr := tx.OpenDBI(name, mdbx.DBAccede, nil, nil)
if createErr != nil {
if mdbx.IsNotFound(createErr) {
cnfCopy.DBI = NonExistingDBI
db.buckets[name] = cnfCopy
continue // if deprecated bucket couldn't be open - then it's deleted and it's fine
} else {
return fmt.Errorf("bucket: %s, %w", name, createErr)
}
}
cnfCopy.DBI = kv.DBI(dbi)
db.buckets[name] = cnfCopy
}
return nil
}); err != nil {
return nil, err
}
if !opts.inMem {
if staleReaders, err := db.env.ReaderCheck(); err != nil {
db.log.Error("failed ReaderCheck", "err", err)
} else if staleReaders > 0 {
db.log.Info("cleared reader slots from dead processes", "amount", staleReaders)
}
}
db.path = opts.path
addToPathDbMap(opts.path, db)
return db, nil
}
func (opts MdbxOpts) MustOpen() kv.RwDB {
db, err := opts.Open(context.Background())
if err != nil {
panic(fmt.Errorf("fail to open mdbx: %w", err))
}
return db
}
type MdbxKV struct {
log log.Logger
env *mdbx.Env
buckets kv.TableCfg
roTxsLimiter *semaphore.Weighted // does limit amount of concurrent Ro transactions - in most casess runtime.NumCPU() is good value for this channel capacity - this channel can be shared with other components (like Decompressor)
opts MdbxOpts
txSize uint64
closed atomic.Bool
path string
txsCount uint
txsCountMutex *sync.Mutex
txsAllDoneOnCloseCond *sync.Cond
leakDetector *dbg.LeakDetector
// MaxBatchSize is the maximum size of a batch. Default value is
// copied from DefaultMaxBatchSize in Open.
//
// If <=0, disables batching.
//
// Do not change concurrently with calls to Batch.
MaxBatchSize int
// MaxBatchDelay is the maximum delay before a batch starts.
// Default value is copied from DefaultMaxBatchDelay in Open.
//
// If <=0, effectively disables batching.
//
// Do not change concurrently with calls to Batch.
MaxBatchDelay time.Duration
batchMu sync.Mutex
batch *batch
}
// Default values if not set in a DB instance.
const (
DefaultMaxBatchSize int = 1000
DefaultMaxBatchDelay = 10 * time.Millisecond
)
type batch struct {
db *MdbxKV
timer *time.Timer
start sync.Once
calls []call
}
type call struct {
fn func(kv.RwTx) error
err chan<- error
}
// trigger runs the batch if it hasn't already been run.
func (b *batch) trigger() {
b.start.Do(b.run)
}
// run performs the transactions in the batch and communicates results
// back to DB.Batch.
func (b *batch) run() {
b.db.batchMu.Lock()
b.timer.Stop()
// Make sure no new work is added to this batch, but don't break
// other batches.
if b.db.batch == b {
b.db.batch = nil
}
b.db.batchMu.Unlock()
retry:
for len(b.calls) > 0 {
var failIdx = -1
err := b.db.Update(context.Background(), func(tx kv.RwTx) error {
for i, c := range b.calls {
if err := safelyCall(c.fn, tx); err != nil {
failIdx = i
return err
}
}
return nil
})
if failIdx >= 0 {
// take the failing transaction out of the batch. it's
// safe to shorten b.calls here because db.batch no longer
// points to us, and we hold the mutex anyway.
c := b.calls[failIdx]
b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1]
// tell the submitter re-run it solo, continue with the rest of the batch
c.err <- trySolo
continue retry
}
// pass success, or bolt internal errors, to all callers
for _, c := range b.calls {
c.err <- err
}
break retry
}
}
// trySolo is a special sentinel error value used for signaling that a
// transaction function should be re-run. It should never be seen by
// callers.
var trySolo = errors.New("batch function returned an error and should be re-run solo")
type panicked struct {
reason interface{}
}
func (p panicked) Error() string {
if err, ok := p.reason.(error); ok {
return err.Error()
}
return fmt.Sprintf("panic: %v", p.reason)
}
func safelyCall(fn func(tx kv.RwTx) error, tx kv.RwTx) (err error) {
defer func() {
if p := recover(); p != nil {
err = panicked{p}
}
}()
return fn(tx)
}
// Batch is only useful when there are multiple goroutines calling it.
// It behaves similar to Update, except:
//
// 1. concurrent Batch calls can be combined into a single RwTx.
//
// 2. the function passed to Batch may be called multiple times,
// regardless of whether it returns error or not.
//
// This means that Batch function side effects must be idempotent and
// take permanent effect only after a successful return is seen in
// caller.
//
// Example of bad side-effects: print messages, mutate external counters `i++`
//
// The maximum batch size and delay can be adjusted with DB.MaxBatchSize
// and DB.MaxBatchDelay, respectively.
func (db *MdbxKV) Batch(fn func(tx kv.RwTx) error) error {
errCh := make(chan error, 1)
db.batchMu.Lock()
if (db.batch == nil) || (db.batch != nil && len(db.batch.calls) >= db.MaxBatchSize) {
// There is no existing batch, or the existing batch is full; start a new one.
db.batch = &batch{
db: db,
}
db.batch.timer = time.AfterFunc(db.MaxBatchDelay, db.batch.trigger)
}
db.batch.calls = append(db.batch.calls, call{fn: fn, err: errCh})
if len(db.batch.calls) >= db.MaxBatchSize {
// wake up batch, it's ready to run
go db.batch.trigger()
}
db.batchMu.Unlock()
err := <-errCh
if errors.Is(err, trySolo) {
err = db.Update(context.Background(), fn)
}
return err
}
func (db *MdbxKV) Path() string { return db.opts.path }
func (db *MdbxKV) PageSize() uint64 { return db.opts.pageSize }
func (db *MdbxKV) ReadOnly() bool { return db.opts.HasFlag(mdbx.Readonly) }
func (db *MdbxKV) Accede() bool { return db.opts.HasFlag(mdbx.Accede) }
func (db *MdbxKV) CHandle() unsafe.Pointer {
return db.env.CHandle()
}
// openDBIs - first trying to open existing DBI's in RO transaction
// otherwise re-try by RW transaction
// it allow open DB from another process - even if main process holding long RW transaction
func (db *MdbxKV) openDBIs(buckets []string) error {
if db.ReadOnly() || db.Accede() {
return db.View(context.Background(), func(tx kv.Tx) error {
for _, name := range buckets {
if db.buckets[name].IsDeprecated {
continue
}
if err := tx.(kv.BucketMigrator).CreateBucket(name); err != nil {
return err
}
}
return tx.Commit() // when open db as read-only, commit of this RO transaction is required
})
}
return db.Update(context.Background(), func(tx kv.RwTx) error {
for _, name := range buckets {
if db.buckets[name].IsDeprecated {
continue
}
if err := tx.(kv.BucketMigrator).CreateBucket(name); err != nil {
return err
}
}
return nil
})
}
func (db *MdbxKV) trackTxBegin() bool {
db.txsCountMutex.Lock()
defer db.txsCountMutex.Unlock()
isOpen := !db.closed.Load()
if isOpen {
db.txsCount++
}
return isOpen
}
func (db *MdbxKV) hasTxsAllDoneAndClosed() bool {
return (db.txsCount == 0) && db.closed.Load()
}
func (db *MdbxKV) trackTxEnd() {
db.txsCountMutex.Lock()
defer db.txsCountMutex.Unlock()
if db.txsCount > 0 {
db.txsCount--
} else {
panic("MdbxKV: unmatched trackTxEnd")
}
if db.hasTxsAllDoneAndClosed() {
db.txsAllDoneOnCloseCond.Signal()
}
}
func (db *MdbxKV) waitTxsAllDoneOnClose() {
db.txsCountMutex.Lock()
defer db.txsCountMutex.Unlock()
for !db.hasTxsAllDoneAndClosed() {
db.txsAllDoneOnCloseCond.Wait()
}
}
// Close closes db
// All transactions must be closed before closing the database.
func (db *MdbxKV) Close() {
if ok := db.closed.CompareAndSwap(false, true); !ok {
return
}
db.waitTxsAllDoneOnClose()
db.env.Close()
db.env = nil
if db.opts.inMem {
if err := os.RemoveAll(db.opts.path); err != nil {
db.log.Warn("failed to remove in-mem db file", "err", err)
}
}
removeFromPathDbMap(db.path)
}
func (db *MdbxKV) BeginRo(ctx context.Context) (txn kv.Tx, err error) {
// don't try to acquire if the context is already done
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
// otherwise carry on
}
if !db.trackTxBegin() {
return nil, fmt.Errorf("db closed")
}
// will return nil err if context is cancelled (may appear to acquire the semaphore)
if semErr := db.roTxsLimiter.Acquire(ctx, 1); semErr != nil {
db.trackTxEnd()
return nil, semErr
}
defer func() {
if txn == nil {
// on error, or if there is whatever reason that we don't return a tx,
// we need to free up the limiter slot, otherwise it could lead to deadlocks
db.roTxsLimiter.Release(1)
db.trackTxEnd()
}
}()
tx, err := db.env.BeginTxn(nil, mdbx.Readonly)
if err != nil {
return nil, fmt.Errorf("%w, label: %s, trace: %s", err, db.opts.label.String(), stack2.Trace().String())
}
return &MdbxTx{
ctx: ctx,
db: db,
tx: tx,
readOnly: true,
id: db.leakDetector.Add(),
}, nil
}
func (db *MdbxKV) BeginRw(ctx context.Context) (kv.RwTx, error) {
return db.beginRw(ctx, 0)
}
func (db *MdbxKV) BeginRwNosync(ctx context.Context) (kv.RwTx, error) {
return db.beginRw(ctx, mdbx.TxNoSync)
}
func (db *MdbxKV) beginRw(ctx context.Context, flags uint) (txn kv.RwTx, err error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
if !db.trackTxBegin() {
return nil, fmt.Errorf("db closed")
}
runtime.LockOSThread()
tx, err := db.env.BeginTxn(nil, flags)
if err != nil {
runtime.UnlockOSThread() // unlock only in case of error. normal flow is "defer .Rollback()"
db.trackTxEnd()
return nil, fmt.Errorf("%w, lable: %s, trace: %s", err, db.opts.label.String(), stack2.Trace().String())
}
return &MdbxTx{
db: db,
tx: tx,
ctx: ctx,
id: db.leakDetector.Add(),
}, nil
}
type MdbxTx struct {
tx *mdbx.Txn
id uint64 // set only if TRACE_TX=true
db *MdbxKV
statelessCursors map[string]kv.RwCursor
readOnly bool
ctx context.Context
cursors map[uint64]*mdbx.Cursor
cursorID uint64
streams map[int]kv.Closer
streamID int
}
type MdbxCursor struct {
tx *MdbxTx
c *mdbx.Cursor
bucketName string
bucketCfg kv.TableCfgItem
dbi mdbx.DBI
id uint64
}
func (db *MdbxKV) Env() *mdbx.Env {
return db.env
}
func (db *MdbxKV) AllDBI() map[string]kv.DBI {
res := map[string]kv.DBI{}
for name, cfg := range db.buckets {
res[name] = cfg.DBI
}
return res
}
func (db *MdbxKV) AllTables() kv.TableCfg {
return db.buckets
}
func (tx *MdbxTx) IsRo() bool { return tx.readOnly }
func (tx *MdbxTx) ViewID() uint64 { return tx.tx.ID() }
func (tx *MdbxTx) CollectMetrics() {
if tx.db.opts.label != kv.ChainDB {
return
}
info, err := tx.db.env.Info(tx.tx)
if err != nil {
return
}
if info.SinceReaderCheck.Hours() > 1 {
if staleReaders, err := tx.db.env.ReaderCheck(); err != nil {
tx.db.log.Error("failed ReaderCheck", "err", err)
} else if staleReaders > 0 {
tx.db.log.Info("cleared reader slots from dead processes", "amount", staleReaders)
}
}
kv.DbSize.SetUint64(info.Geo.Current)
kv.DbPgopsNewly.SetUint64(info.PageOps.Newly)
kv.DbPgopsCow.SetUint64(info.PageOps.Cow)
kv.DbPgopsClone.SetUint64(info.PageOps.Clone)
kv.DbPgopsSplit.SetUint64(info.PageOps.Split)
kv.DbPgopsMerge.SetUint64(info.PageOps.Merge)
kv.DbPgopsSpill.SetUint64(info.PageOps.Spill)
kv.DbPgopsUnspill.SetUint64(info.PageOps.Unspill)
kv.DbPgopsWops.SetUint64(info.PageOps.Wops)
txInfo, err := tx.tx.Info(true)
if err != nil {
return
}
kv.TxDirty.SetUint64(txInfo.SpaceDirty)
kv.TxLimit.SetUint64(tx.db.txSize)
kv.TxSpill.SetUint64(txInfo.Spill)
kv.TxUnspill.SetUint64(txInfo.Unspill)
gc, err := tx.BucketStat("gc")
if err != nil {
return
}
kv.GcLeafMetric.SetUint64(gc.LeafPages)
kv.GcOverflowMetric.SetUint64(gc.OverflowPages)
kv.GcPagesMetric.SetUint64((gc.LeafPages + gc.OverflowPages) * tx.db.opts.pageSize / 8)
}
// ListBuckets - all buckets stored as keys of un-named bucket
func (tx *MdbxTx) ListBuckets() ([]string, error) { return tx.tx.ListDBI() }
func (db *MdbxKV) View(ctx context.Context, f func(tx kv.Tx) error) (err error) {
// can't use db.env.View method - because it calls commit for read transactions - it conflicts with write transactions.
tx, err := db.BeginRo(ctx)
if err != nil {
return err
}
defer tx.Rollback()
return f(tx)
}
func (db *MdbxKV) UpdateNosync(ctx context.Context, f func(tx kv.RwTx) error) (err error) {
tx, err := db.BeginRwNosync(ctx)
if err != nil {
return err
}
defer tx.Rollback()
err = f(tx)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (db *MdbxKV) Update(ctx context.Context, f func(tx kv.RwTx) error) (err error) {
tx, err := db.BeginRw(ctx)
if err != nil {
return err
}
defer tx.Rollback()
err = f(tx)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (tx *MdbxTx) CreateBucket(name string) error {
cnfCopy := tx.db.buckets[name]
dbi, err := tx.tx.OpenDBI(name, mdbx.DBAccede, nil, nil)
if err != nil && !mdbx.IsNotFound(err) {
return fmt.Errorf("create table: %s, %w", name, err)
}
if err == nil {
cnfCopy.DBI = kv.DBI(dbi)
var flags uint
flags, err = tx.tx.Flags(dbi)
if err != nil {
return err
}
cnfCopy.Flags = kv.TableFlags(flags)
tx.db.buckets[name] = cnfCopy
return nil
}
// if bucket doesn't exists - create it
var flags = tx.db.buckets[name].Flags
var nativeFlags uint
if !(tx.db.ReadOnly() || tx.db.Accede()) {
nativeFlags |= mdbx.Create
}
if flags&kv.DupSort != 0 {
nativeFlags |= mdbx.DupSort
flags ^= kv.DupSort
}
if flags != 0 {
return fmt.Errorf("some not supported flag provided for bucket")
}
dbi, err = tx.tx.OpenDBI(name, nativeFlags, nil, nil)
if err != nil {
return fmt.Errorf("create table: %s, %w", name, err)
}
cnfCopy.DBI = kv.DBI(dbi)
tx.db.buckets[name] = cnfCopy
return nil
}
func (tx *MdbxTx) dropEvenIfBucketIsNotDeprecated(name string) error {
dbi := tx.db.buckets[name].DBI
// if bucket was not open on db start, then it's may be deprecated
// try to open it now without `Create` flag, and if fail then nothing to drop
if dbi == NonExistingDBI {