This repository has been archived by the owner on Feb 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 231
/
lmdb.go
1715 lines (1447 loc) · 45.6 KB
/
lmdb.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 2020 Pilosa Corp.
//
// 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.
// +build amd64
package pilosa
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"github.com/glycerine/lmdb-go/lmdb"
"github.com/pilosa/pilosa/v2/hash"
"github.com/pilosa/pilosa/v2/roaring"
"github.com/pilosa/pilosa/v2/txkey"
"github.com/pkg/errors"
)
// Linux builds note:
//
// This setting of -DMDB_USE_SYSV_SEM=1 is required in the cgo build
// under Linux to avoid a random deadlock occurance deep inside
// the LMDB C code.
//
// Futher documentation here: https://github.com/bmatsuo/lmdb-go/issues/94
//
// The effect of the -D define above is to that the LMDB C code then
// uses SysV semaphores and avoids POSIX thread-local semaphores. SysV semaphores
// are stored system-wide. POSIX semaphores are kept on thread-local storage,
// which is apparently problematic.
// lmdbRegistrar facilitates shutdown
// of all the lmdb databases started under
// tests. Its needed because most tests don't cleanup
// the *Index(es) they create. But we still
// want to shutdown lmdbDB goroutines
// after tests run.
//
// It also allows opening the same path twice to
// result in sharing the same open database handle, and
// thus the same transactional guarantees.
//
type lmdbRegistrar struct {
mu sync.Mutex
mp map[*LMDBWrapper]bool
path2db map[string]*LMDBWrapper
}
func (r *lmdbRegistrar) Size() int {
r.mu.Lock()
defer r.mu.Unlock()
nmp := len(r.mp)
npa := len(r.path2db)
if nmp != npa {
panic(fmt.Sprintf("nmp=%v, vs npa=%v", nmp, npa))
}
return nmp
}
var globalLMDBReg *lmdbRegistrar = newLMDBTestRegistrar()
var globalNextTxSnLMDB int64
func newLMDBTestRegistrar() *lmdbRegistrar {
return &lmdbRegistrar{
mp: make(map[*LMDBWrapper]bool),
path2db: make(map[string]*LMDBWrapper),
}
}
// register each lmdb created under tests, so we
// can clean them up. This is called by openLMDBWrapper() while
// holding the r.mu.Lock, since it needs to atomically
// check the registry and make a new instance only
// if one does not exist for its path, and otherwise
// return the existing instance.
func (r *lmdbRegistrar) unprotectedRegister(w *LMDBWrapper) {
r.mp[w] = true
r.path2db[w.path] = w
}
// unregister removes w from r
func (r *lmdbRegistrar) unregister(w *LMDBWrapper) {
r.mu.Lock()
delete(r.mp, w)
delete(r.path2db, w.path)
r.mu.Unlock()
}
func DumpAllLMDB() {
short := true
globalLMDBReg.mu.Lock()
defer globalLMDBReg.mu.Unlock()
for w := range globalLMDBReg.mp {
AlwaysPrintf("this lmdb path='%v' has: \n%v\n", w.path, w.StringifiedLMDBKeys(nil, short))
}
}
// lmdbPath is a helper for determining the full directory
// in which the lmdb database will be stored.
func lmdbPath(path string) string {
if !strings.HasSuffix(path, "-lmdb@") {
return path + "-lmdb@"
}
return path
}
// openLMDBDB opens the database in the bpath directoy
// without deleting any prior content. Any LMDBDB
// database directory will have the "-lmdb" suffix.
//
// openLMDBDB will check the registry and make a new instance only
// if one does not exist for its bpath. Otherwise it returns
// the existing instance. This insures only one lmdbDB
// per bpath in this pilosa node.
func (r *lmdbRegistrar) OpenDBWrapper(path0 string, doAllocZero bool) (DBWrapper, error) {
path := lmdbPath(path0)
r.mu.Lock()
defer r.mu.Unlock()
w, ok := r.path2db[path]
if ok {
// creates the effect of having only one lmdb open per pilosa node.
return w, nil
}
// otherwise, make a new lmdb and store it in globalLMDBReg
runtime.LockOSThread()
defer runtime.UnlockOSThread()
const MaxReaders = 126 // default is 126
env, err := lmdb.NewEnvMaxReaders(MaxReaders)
panicOn(err)
err = env.SetMaxDBs(1)
panicOn(err)
//err = env.SetMapSize(256 << 30) // 256GB
err = env.SetMapSize(4 << 30) // 4GB
panicOn(err)
panicOn(os.MkdirAll(filepath.Dir(path), 0755))
//flags := uint(lmdb.NoReadahead | lmdb.NoSubdir)
//flags := uint(lmdb.NoSubdir) // no difference without the No.Readahead on ./query.
// NoReadahead should be better for random workloads or those bigger than memory,
// as it avoids loading extra pages which then evict pages you are using.
//flags := uint(lmdb.NoReadahead)
flags := uint(0)
// unsafe, but get upper bound on performance.
// WriteMap = C.MDB_WRITEMAP // Use a writable memory map.
// NoMetaSync = C.MDB_NOMETASYNC // Don't fsync metapage after commit.
// NoSync = C.MDB_NOSYNC // Don't fsync after commit.
// flags = flags | lmdb.WriteMap | lmdb.NoMetaSync | lmdb.NoSync // about the same speed
// flags = flags | lmdb.NoMetaSync | lmdb.NoSync // slows things down
// TODO(jea): we got an odd segfault in the roaring/ pkg when we went to read-only mmap
// with the row-cache off; probably means we were trying to write to mmap-ed
// memory. Investigate at some point. reference: 2a77b25d ja/write_map_prevents_segfault
//
// Update: added COW to roaring/roaring.go:3282 func (c *Container) arrayRemove(),
// seems to fix the issue.
//
//flags = flags | lmdb.WriteMap // seems faster than without: or maybe not. not sure.
// kRemove N= 710401 avg/op: 7.714µs sd: 27.83µs total: 5.480656859s
// kAdd N= 722835 avg/op: 9.096µs sd: 105.787µs total: 6.575497725s
// ACI not ACID at the moment; no durability
flags = flags |
lmdb.NoMemInit | // Disable LMDB memory initialization
// Note that lmdb.WriteMap requests a big, writable, memory map.
// On my darwin/OSX laptop with 16GB ram, for instance, we
// can have difficulty obtaining this, resulting in
// panic: mdb_env_open: no space left on device
lmdb.WriteMap | // Use a writable memory map.
// default ACI (not Durable) transactions; 300% faster write speed results.
lmdb.NoMetaSync | // Don't fsync metapage after commit.
lmdb.NoSync | // Don't fsync after commit.
lmdb.MapAsync // Flush asynchronously when using the WriteMap flag.
if !DirExists(path) {
panicOn(os.MkdirAll(path, 0755))
}
err = env.Open(path, flags, 0644)
if err != nil {
AlwaysPrintf("error env.Open(path='%v'): '%v'; on gid = '%v'", path, err, curGID())
}
panicOn(err)
// In any real application it is important to check for readers that were
// never closed by their owning process, and for which the owning process
// has exited. See the documentation on transactions for more information.
staleReaders, err := env.ReaderCheck()
panicOn(err)
if staleReaders > 0 {
log.Printf("cleared %d reader slots from dead processes", staleReaders)
}
// Open a database handle that will be used for the entire lifetime of this
// application. Because the database may not have existed before, and the
// database may need to be created, we need to get the database handle in
// an update transacation.
var dbi lmdb.DBI
name := filepath.Base(path)
err = env.Update(func(txn *lmdb.Txn) (err error) {
dbi, err = txn.CreateDBI(name)
return err
})
panicOn(err)
w = &LMDBWrapper{
name: name,
env: env,
reg: r,
path: path,
dbi: dbi,
doAllocZero: doAllocZero,
openTx: make(map[*LMDBTx]bool),
}
r.unprotectedRegister(w)
return w, nil
}
func (w *LMDBWrapper) Path() string {
return w.path
}
func (w *LMDBWrapper) HasData() (has bool, err error) {
tx, err := w.NewTx(!writable, "", Txo{})
if err != nil {
return false, errors.Wrap(err, "HasData NewTx")
}
defer tx.Rollback()
bi := NewLMDBIterator(tx.(*LMDBTx), nil)
defer bi.Close()
for bi.Next() {
return true, nil
}
return false, nil
}
func (w *LMDBWrapper) CleanupTx(tx Tx) {
// inlined into Rollback and Commit, so this is a no-op, just here to satisfy the interface.
}
func (tx *LMDBTx) IsDone() (done bool) {
tx.mu.Lock()
done = tx.unlocked
tx.mu.Unlock()
return
}
func (w *LMDBWrapper) OpenListString() (r string) {
list := w.listopen()
if len(list) == 0 {
return "<no open LMDBTx>"
}
for i, ltx := range list {
if ltx.o.Write {
r += fmt.Sprintf("[%v]write: _sn_ %v %v, \n", i, ltx.sn, ltx.o)
} else {
r += fmt.Sprintf("[%v]read : _sn_ %v %v, \n", i, ltx.sn, ltx.o)
}
}
return
}
func (w *LMDBWrapper) listopen() (slc []*LMDBTx) {
w.muDb.Lock()
for v := range w.openTx {
slc = append(slc, v)
}
w.muDb.Unlock()
return
}
func (w *LMDBWrapper) OpenSnList() (slc []int64) {
w.muDb.Lock()
for v := range w.openTx {
slc = append(slc, v.sn)
}
w.muDb.Unlock()
return
}
var ErrShutdown = fmt.Errorf("shutting down")
// DeleteIndex deletes all the containers associated with
// the named index from the lmdb database.
func (w *LMDBWrapper) DeleteIndex(indexName string) error {
// We use the apostrophie rune `'` to locate the end of the
// index name in the key prefix, so we cannot allow indexNames
// themselves to contain apostrophies.
if strings.Contains(indexName, "/") {
return fmt.Errorf("error: bad indexName `%v` in LMDBWrapper.DeleteIndex() call: indexName cannot contain '/'.", indexName)
}
prefix := txkey.IndexOnlyPrefix(indexName)
return w.DeletePrefix(prefix)
}
// statically confirm that LMDBTx satisfies the Tx interface.
var _ Tx = (*LMDBTx)(nil)
// LMDBWrapper provides the NewTx() method.
type LMDBWrapper struct {
env *lmdb.Env
muDb sync.Mutex
path string
name string
dbi lmdb.DBI
// track our registrar for Close / goro leak reporting purposes.
reg *lmdbRegistrar
// make LMDBWrapper.Close() idempotent, avoiding panic on double Close()
closed bool
// doAllocZero sets the corresponding flag on all new LMDBTx.
// When doAllocZero is true, we zero out any data from lmdb
// after transcation commit and rollback. This simulates
// what would happen if we were to use the mmap-ed data
// from lmdb directly. Currently we copy by default for
// safety because otherwise TestAPI_ImportColumnAttrs sees
// corrupted data.
doAllocZero bool
DeleteEmptyContainer bool
openTx map[*LMDBTx]bool
}
func (w *LMDBWrapper) SetHolder(h *Holder) {
// don't need it at the moment
//w.h = h
}
// NewTxWRITE lets us see in the callstack dumps where the WRITE tx are.
// Can't have more than one active write per database, so the
// 2nd one will block until the first finishes.
func (w *LMDBWrapper) NewTxWRITE() *lmdb.Txn {
lmdbTxn, err := w.env.BeginTxn(nil, 0)
panicOn(err)
return lmdbTxn
}
// NewTxREAD lets us see in the callstack dumps where the READ tx are.
func (w *LMDBWrapper) NewTxREAD() *lmdb.Txn {
if w.env == nil {
panic("cannot call NewTxREAD() on closed LMDBWrapper() -- open a new Wrapper first")
}
lmdbTxn, err := w.env.BeginTxn(nil, lmdb.Readonly)
panicOn(err)
return lmdbTxn
}
// NewTx produces LMDB based ACID or ACI transactions. If
// the transaction will modify data, then the write flag must be true.
// Read-only queries should set write to false, to allow more concurrency.
// Methods on a LMDBTx are thread-safe, and can be called from
// different goroutines.
//
// initialIndexName is optional. It is set by the TxFactory from the Txo
// options provided at the Tx creation point. It allows us to recognize
// and isolate cross-index queries more quickly. It can always be empty ""
// but when set is highly useful for debugging. It has no impact
// on transaction behavior.
//
func (w *LMDBWrapper) NewTx(write bool, initialIndexName string, o Txo) (tx Tx, err error) {
sn := atomic.AddInt64(&globalNextTxSnLMDB, 1)
//vv("lmdb new tx _sn_ %v; openTx='%v', stack \n%v", sn, w.OpenListString(), stack())
//vv("lmdb new (write=%v, shard=%v) tx _sn_ %v; openTx='%v'", write, o.Shard, sn, w.OpenListString())
runtime.LockOSThread()
var lmdbTxn *lmdb.Txn
if write {
// see the WRITE tx on the callstack.
lmdbTxn = w.NewTxWRITE()
} else {
// see the READ tx on the callstack.
lmdbTxn = w.NewTxREAD()
}
lmdbTxn.RawRead = true
ltx := &LMDBTx{
sn: sn,
write: write,
tx: lmdbTxn,
dbi: w.dbi,
Db: w,
frag: o.Fragment,
doAllocZero: w.doAllocZero,
initialIndexName: initialIndexName,
DeleteEmptyContainer: w.DeleteEmptyContainer,
o: o,
gid: curGID(),
}
tx = ltx
w.muDb.Lock()
w.openTx[ltx] = true
w.muDb.Unlock()
return
}
// Close shuts down the LMDB database.
func (w *LMDBWrapper) Close() (err error) {
w.muDb.Lock()
defer w.muDb.Unlock()
if !w.closed {
// complain if there are still Tx in flight, b/c otherwise we will see
// the somewhat mysterious 'panic: should not be in ReadSlot.free() with slot still owned by gid=107043; refCount=1'
if len(w.openTx) > 0 {
AlwaysPrintf("error: cannot close LMDBWrapper with Tx still in flight.")
return
}
w.reg.unregister(w)
w.closed = true
w.env.CloseDBI(w.dbi)
w.env.Close()
w.env = nil
}
return nil
}
func (w *LMDBWrapper) IsClosed() (closed bool) {
w.muDb.Lock()
closed = w.closed
w.muDb.Unlock()
return
}
// LMDBTx wraps a lmdb.Txn and provides the Tx interface
// method implementations.
// The methods on LMDBTx are thread-safe, and can be called
// from different goroutines.
type LMDBTx struct {
// mu serializes lmdb operations on this single txn instance.
mu sync.Mutex
sn int64 // serial number
write bool
dbi lmdb.DBI
Db *LMDBWrapper
tx *lmdb.Txn
frag *fragment
opcount int
//initloc string // stack trace of where we were initially created.
doAllocZero bool
initialIndexName string
DeleteEmptyContainer bool
unlocked bool // runtime.UnlockOSThread has been done.
o Txo
// NewTx, write operations, Commit and/or Rollback must all take place on
// the same gid and it must the runtime.LockOSThreaded first. Verify
// that we are using the right goroutine in a debug build using the
// gid, stored here, used for NewTx().
gid uint64
}
// sanity check that database is open.
func (tx *LMDBTx) sanity() {
if tx.Db.IsClosed() {
panic("cannot operate on closed LMDB")
}
}
// debugOnlyGidcheck is expected to be sort of slow. So once we are sure
// of correctness, turn it off.
// func (tx *LMDBTx) debugOnlyGidcheck() {
//
// // only applies to write txn. Reads should be able to share the txn.
// if tx.o.Write {
// cur := curGID()
// if cur != tx.gid {
// panic(fmt.Sprintf("must use write LMDBTx from same gid that created it! creator gid=%v, but user gid now =%v", tx.gid, cur))
// }
// }
//
// }
func (tx *LMDBTx) Group() *TxGroup {
return tx.o.Group
}
func (tx *LMDBTx) Type() string {
return LmdbTxn
}
func (tx *LMDBTx) UseRowCache() bool {
return false
}
// Pointer gives us a memory address for the underlying transaction for debugging.
// It is public because we use it in roaring to report invalid container memory access
// outside of a transaction.
func (tx *LMDBTx) Pointer() string {
return fmt.Sprintf("%p", tx)
}
// Rollback rolls back the transaction.
func (tx *LMDBTx) Rollback() {
tx.sanity()
//vv("lmdb rollback tx _sn_ %v; stack \n%v", tx.sn) // , stack())
tx.Db.muDb.Lock()
delete(tx.Db.openTx, tx)
tx.Db.muDb.Unlock()
tx.mu.Lock()
defer tx.mu.Unlock()
//tx.debugOnlyGidcheck()
tx.tx.Abort() // must hold tx.mu mutex lock
if !tx.unlocked {
runtime.UnlockOSThread()
tx.unlocked = true
tx.o.dbs.Cleanup(tx)
}
}
// Commit commits the transaction to permanent storage.
// Commits can handle up to 100k updates to fragments
// at once, but not more. This is a LMDBDB imposed limit.
func (tx *LMDBTx) Commit() error {
tx.sanity()
//vv("lmdb commit tx _sn_ %v; stack \n%v", tx.sn, stack())
tx.Db.muDb.Lock()
delete(tx.Db.openTx, tx)
tx.Db.muDb.Unlock()
tx.mu.Lock()
defer tx.mu.Unlock()
//tx.debugOnlyGidcheck()
err := tx.tx.Commit() // must hold tx.mu mutex lock
panicOn(err)
if !tx.unlocked {
runtime.UnlockOSThread()
tx.unlocked = true
tx.o.dbs.Cleanup(tx)
}
return err
}
// Readonly returns true iff the LMDBTx is read-only.
func (tx *LMDBTx) Readonly() bool {
return !tx.write
}
// RoaringBitmap returns the roaring.Bitmap for all bits in the fragment.
func (tx *LMDBTx) RoaringBitmap(index, field, view string, shard uint64) (*roaring.Bitmap, error) {
return tx.OffsetRange(index, field, view, shard, 0, 0, LeftShifted16MaxContainerKey)
}
// Container returns the requested roaring.Container, selected by fragment and ckey
func (tx *LMDBTx) Container(index, field, view string, shard uint64, ckey uint64) (c *roaring.Container, err error) {
// values returned from Get() are only valid while the transaction
// is open. If you need to use a value outside of the transaction then
// you must use copy() to copy it to another byte slice.
// BUT here we are already inside the Txn.
bkey := txkey.Key(index, field, view, shard, ckey)
tx.mu.Lock()
//tx.debugOnlyGidcheck()
v, err := tx.tx.Get(tx.dbi, bkey)
tx.mu.Unlock()
if lmdb.IsNotFound(err) {
// Seems crazy, but we, for now at least,
// match what RoaringTx does by returning nil, nil.
return nil, nil
} else {
if err != nil {
panicOn(err)
return nil, nil
}
}
n := len(v)
if n > 0 {
c = tx.toContainer(v[n-1], v[0:(n-1)])
}
return
}
// PutContainer stores rc under the specified fragment and container ckey.
func (tx *LMDBTx) PutContainer(index, field, view string, shard uint64, ckey uint64, rc *roaring.Container) error {
bkey := txkey.Key(index, field, view, shard, ckey)
var by []byte
ct := roaring.ContainerType(rc)
switch ct {
case roaring.ContainerArray:
by = fromArray16(roaring.AsArray(rc))
case roaring.ContainerBitmap:
by = fromArray64(roaring.AsBitmap(rc))
case roaring.ContainerRun:
by = fromInterval16(roaring.AsRuns(rc))
case roaring.ContainerNil:
panic("wat? nil container is unexpected, no?!?")
default:
panic(fmt.Sprintf("unknown container type: %v", ct))
}
tx.mu.Lock()
//tx.debugOnlyGidcheck()
err := tx.tx.Put(tx.dbi, bkey, append(by, ct), 0) // TODO: this might make a copy; can meta byte be stored elsewhere?
tx.mu.Unlock()
// TODO(jea): need to handle?
// lmdb.TxnFull
// lmdb.CursorFull
// lmdb.PageFull
return err
}
// RemoveContainer deletes the container specified by the shard and container key ckey
func (tx *LMDBTx) RemoveContainer(index, field, view string, shard uint64, ckey uint64) error {
bkey := txkey.Key(index, field, view, shard, ckey)
tx.mu.Lock()
//tx.debugOnlyGidcheck()
err := tx.tx.Del(tx.dbi, bkey, nil)
tx.mu.Unlock()
if lmdb.IsNotFound(err) {
return nil
}
return err
}
// Add sets all the a bits hot in the specified fragment.
func (tx *LMDBTx) Add(index, field, view string, shard uint64, batched bool, a ...uint64) (changeCount int, err error) {
return tx.addOrRemove(index, field, view, shard, batched, false, a...)
}
// Remove clears all the specified a bits in the chosen fragment.
func (tx *LMDBTx) Remove(index, field, view string, shard uint64, a ...uint64) (changeCount int, err error) {
const batched = false
const remove = true
return tx.addOrRemove(index, field, view, shard, batched, remove, a...)
}
func (tx *LMDBTx) addOrRemove(index, field, view string, shard uint64, batched, remove bool, a ...uint64) (changeCount int, err error) {
// pure hack to match RoaringTx
defer func() {
if !remove && !batched {
if changeCount > 0 {
changeCount = 1
}
}
}()
if len(a) == 0 {
return 0, nil
}
// have to sort, b/c input is not always sorted.
sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })
var lastHi uint64 = math.MaxUint64 // highbits is always less than this starter.
var rc *roaring.Container
var hi uint64
var lo uint16
for i, v := range a {
hi, lo = highbits(v), lowbits(v)
if hi != lastHi {
// either first time through, or changed to a different container.
// do we need put the last updated container now?
if i > 0 {
// not first time through, write what we got.
if remove && (rc == nil || rc.N() == 0) {
err = tx.RemoveContainer(index, field, view, shard, lastHi)
panicOn(err)
} else {
err = tx.PutContainer(index, field, view, shard, lastHi, rc)
panicOn(err)
}
}
// get the next container
rc, err = tx.Container(index, field, view, shard, hi)
panicOn(err)
} // else same container, keep adding bits to rct.
chng := false
// rc can be nil before, and nil after, in both Remove/Add below.
// The roaring container add() and remove() methods handle this.
if remove {
rc, chng = rc.Remove(lo)
} else {
rc, chng = rc.Add(lo)
}
if chng {
changeCount++
}
lastHi = hi
}
// write the last updates.
if remove {
if rc == nil || rc.N() == 0 {
err = tx.RemoveContainer(index, field, view, shard, hi)
panicOn(err)
} else {
err = tx.PutContainer(index, field, view, shard, hi, rc)
panicOn(err)
}
} else {
if rc == nil || rc.N() == 0 {
panic("there should be no way to have an empty bitmap AFTER an Add() operation")
}
err = tx.PutContainer(index, field, view, shard, hi, rc)
panicOn(err)
}
return
}
// Contains returns exists true iff the bit chosen by key is
// hot (set to 1) in specified fragment.
func (tx *LMDBTx) Contains(index, field, view string, shard uint64, key uint64) (exists bool, err error) {
lo, hi := lowbits(key), highbits(key)
bkey := txkey.Key(index, field, view, shard, hi)
tx.mu.Lock()
var v []byte
//tx.debugOnlyGidcheck()
v, err = tx.tx.Get(tx.dbi, bkey)
tx.mu.Unlock()
if lmdb.IsNotFound(err) {
return false, nil
}
if err != nil {
return false, err
}
n := len(v)
if n > 0 {
c := tx.toContainer(v[n-1], v[0:(n-1)])
exists = c.Contains(lo)
}
return exists, err
}
func (tx *LMDBTx) SliceOfShards(index, field, view, optionalViewPath string) (sliceOfShards []uint64, err error) {
prefix := txkey.AllShardPrefix(index, field, view)
bi := NewLMDBIterator(tx, prefix)
defer bi.Close()
lastShard := uint64(0)
firstDone := false
for bi.Next() {
shard := txkey.ShardFromKey(bi.lastKey)
if firstDone {
if shard != lastShard {
sliceOfShards = append(sliceOfShards, shard)
}
lastShard = shard
} else {
// first time
lastShard = shard
firstDone = true
sliceOfShards = append(sliceOfShards, shard)
}
}
return
}
// key is the container key for the first roaring Container
// roaring docs: Iterator returns a ContainterIterator which *after* a call to Next(), a call to Value() will
// return the first container at or after key. found will be true if a
// container is found at key.
//
// LMDBTx notes: We auto-stop at the end of this shard, not going beyond.
func (tx *LMDBTx) ContainerIterator(index, field, view string, shard uint64, firstRoaringContainerKey uint64) (citer roaring.ContainerIterator, found bool, err error) {
// needle example: "idx:'i';fld:'f';vw:'v';shd:'00000000000000000000';key@00000000000000000000"
needle := txkey.Key(index, field, view, shard, firstRoaringContainerKey)
// prefix example: "idx:'i';fld:'f';vw:'v';shard:'00000000000000000000';key@"
prefix := txkey.Prefix(index, field, view, shard)
bi := NewLMDBIterator(tx, prefix)
ok := bi.Seek(needle)
if !ok {
return bi, false, nil
}
// have to compare b/c lmdb might give us valid iterator
// that is past our needle if needle isn't present.
return bi, bytes.Equal(bi.lastKey, needle), nil
}
// LMDBIterator is the iterator returned from a LMDBTx.ContainerIterator() call.
// It implements the roaring.ContainerIterator interface.
type LMDBIterator struct {
tx *LMDBTx
cur *lmdb.Cursor
dbi lmdb.DBI
prefix []byte
seekto []byte
// seen counts how many Next() calls we have seen.
// It is used to match roaring.ContainerIterator semantics.
// Also useful for testing.
seen int
lastKey []byte
lastVal []byte // *roaring.Container
lastOK bool
lastConsumed bool
}
// NewLMDBIterator creates an iterator on tx that will
// only return badgerKeys that start with prefix.
func NewLMDBIterator(tx *LMDBTx, prefix []byte) (bi *LMDBIterator) {
tx.mu.Lock()
//tx.debugOnlyGidcheck()
cur, err := tx.tx.OpenCursor(tx.dbi)
tx.mu.Unlock()
panicOn(err)
bi = &LMDBIterator{
dbi: tx.dbi,
tx: tx,
cur: cur,
prefix: prefix,
}
return
}
// Close tells the database and transaction that the user is done
// with the iterator.
func (bi *LMDBIterator) Close() {
bi.tx.mu.Lock()
//bi.tx.debugOnlyGidcheck()
bi.cur.Close()
bi.tx.mu.Unlock()
}
// Valid returns false if there are no more values in the iterator's range.
func (bi *LMDBIterator) Valid() bool {
return bi.lastOK
}
// Seek allows the iterator to start at needle instead of the global begining.
func (bi *LMDBIterator) Seek(needle []byte) (ok bool) {
bi.tx.mu.Lock()
defer bi.tx.mu.Unlock()
bi.seen++ // if ommited, red TestLMDB_ContainerIterator_empty_iteration_loop() in lmdb_test.go.
//bi.tx.debugOnlyGidcheck()
var k, v []byte
var err error
getflag := uint(lmdb.SetRange)
if len(needle) == 0 {
k, v, err = bi.cur.Get(oneByteSliceOfZero, nil, getflag)
} else {
k, v, err = bi.cur.Get(needle, nil, getflag)
}
if lmdb.IsNotFound(err) {
bi.lastKey = nil
bi.lastVal = nil
bi.lastOK = false
bi.lastConsumed = false
return false
}
if len(bi.prefix) > 0 {
ok = bytes.HasPrefix(k, bi.prefix)
if !ok {
bi.lastKey = nil
bi.lastVal = nil
bi.lastOK = false
bi.lastConsumed = false
return false
}
}
if len(k) == 0 {
bi.lastKey = nil
bi.lastVal = nil
bi.lastOK = false
bi.lastConsumed = false
return false
}
bi.lastKey = k
bi.lastVal = v
bi.lastOK = true
bi.lastConsumed = false
return true
}
func (bi *LMDBIterator) ValidForPrefix(prefix []byte) bool {
if !bi.lastOK {
return false
}
if len(bi.prefix) == 0 {
return true
}
return bytes.HasPrefix(bi.lastKey, bi.prefix)
}
func (bi *LMDBIterator) String() (r string) {
return fmt.Sprintf("LMDBIterator{prefix: '%v', seekto: '%v', seen:%v, lastKey:'%v', lastOK:%v, lastConsumed:%v}", string(bi.prefix), string(bi.seekto), bi.seen, string(bi.lastKey), bi.lastOK, bi.lastConsumed)
}
var oneByteSliceOfZero = []byte{0}
// Next advances the iterator.
func (bi *LMDBIterator) Next() (ok bool) {
if bi.lastOK && !bi.lastConsumed {
bi.seen++
bi.lastConsumed = true
if len(bi.lastVal) == 0 {
panic("bi.lastVal should not have len 0 if lastOK true")
}
return true
}
getflag := uint(lmdb.Next)
prefix := bi.prefix
if bi.seen == 0 {
if len(bi.prefix) > 0 {
getflag = lmdb.SetRange
}
} else {
prefix = nil
}
bi.seen++