Debian Codegraph @

vendor/github.com/coreos/bbolt/db.go

raw
1 package bolt
2
3 import (
4 "errors"
5 "fmt"
6 "hash/fnv"
7 "log"
8 "os"
9 "runtime"
10 "sort"
11 "sync"
12 "time"
13 "unsafe"
14 )
15
16 // The largest step that can be taken when remapping the mmap.
17 const maxMmapStep = 1 << 30 // 1GB
18
19 // The data file format version.
20 const version = 2
21
22 // Represents a marker value to indicate that a file is a Bolt DB.
23 const magic uint32 = 0xED0CDAED
24
25 const pgidNoFreelist pgid = 0xffffffffffffffff
26
27 // IgnoreNoSync specifies whether the NoSync field of a DB is ignored when
28 // syncing changes to a file. This is required as some operating systems,
29 // such as OpenBSD, do not have a unified buffer cache (UBC) and writes
30 // must be synchronized using the msync(2) syscall.
31 const IgnoreNoSync = runtime.GOOS == "openbsd"
32
33 // Default values if not set in a DB instance.
34 const (
35 DefaultMaxBatchSize int = 1000
36 DefaultMaxBatchDelay = 10 * time.Millisecond
37 DefaultAllocSize = 16 * 1024 * 1024
38 )
39
40 // default page size for db is set to the OS page size.
41 var defaultPageSize = os.Getpagesize()
42
43 // The time elapsed between consecutive file locking attempts.
44 const flockRetryTimeout = 50 * time.Millisecond
45
46 // DB represents a collection of buckets persisted to a file on disk.
47 // All data access is performed through transactions which can be obtained through the DB.
48 // All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called.
49 type DB struct {
50 // When enabled, the database will perform a Check() after every commit.
51 // A panic is issued if the database is in an inconsistent state. This
52 // flag has a large performance impact so it should only be used for
53 // debugging purposes.
54 StrictMode bool
55
56 // Setting the NoSync flag will cause the database to skip fsync()
57 // calls after each commit. This can be useful when bulk loading data
58 // into a database and you can restart the bulk load in the event of
59 // a system failure or database corruption. Do not set this flag for
60 // normal use.
61 //
62 // If the package global IgnoreNoSync constant is true, this value is
63 // ignored. See the comment on that constant for more details.
64 //
65 // THIS IS UNSAFE. PLEASE USE WITH CAUTION.
66 NoSync bool
67
68 // When true, skips syncing freelist to disk. This improves the database
69 // write performance under normal operation, but requires a full database
70 // re-sync during recovery.
71 NoFreelistSync bool
72
73 // When true, skips the truncate call when growing the database.
74 // Setting this to true is only safe on non-ext3/ext4 systems.
75 // Skipping truncation avoids preallocation of hard drive space and
76 // bypasses a truncate() and fsync() syscall on remapping.
77 //
78 // https://github.com/boltdb/bolt/issues/284
79 NoGrowSync bool
80
81 // If you want to read the entire database fast, you can set MmapFlag to
82 // syscall.MAP_POPULATE on Linux 2.6.23+ for sequential read-ahead.
83 MmapFlags int
84
85 // MaxBatchSize is the maximum size of a batch. Default value is
86 // copied from DefaultMaxBatchSize in Open.
87 //
88 // If <=0, disables batching.
89 //
90 // Do not change concurrently with calls to Batch.
91 MaxBatchSize int
92
93 // MaxBatchDelay is the maximum delay before a batch starts.
94 // Default value is copied from DefaultMaxBatchDelay in Open.
95 //
96 // If <=0, effectively disables batching.
97 //
98 // Do not change concurrently with calls to Batch.
99 MaxBatchDelay time.Duration
100
101 // AllocSize is the amount of space allocated when the database
102 // needs to create new pages. This is done to amortize the cost
103 // of truncate() and fsync() when growing the data file.
104 AllocSize int
105
106 path string
107 file *os.File
108 lockfile *os.File // windows only
109 dataref []byte // mmap'ed readonly, write throws SEGV
110 data *[maxMapSize]byte
111 datasz int
112 filesz int // current on disk file size
113 meta0 *meta
114 meta1 *meta
115 pageSize int
116 opened bool
117 rwtx *Tx
118 txs []*Tx
119 stats Stats
120
121 freelist *freelist
122 freelistLoad sync.Once
123
124 pagePool sync.Pool
125
126 batchMu sync.Mutex
127 batch *batch
128
129 rwlock sync.Mutex // Allows only one writer at a time.
130 metalock sync.Mutex // Protects meta page access.
131 mmaplock sync.RWMutex // Protects mmap access during remapping.
132 statlock sync.RWMutex // Protects stats access.
133
134 ops struct {
135 writeAt func(b []byte, off int64) (n int, err error)
136 }
137
138 // Read only mode.
139 // When true, Update() and Begin(true) return ErrDatabaseReadOnly immediately.
140 readOnly bool
141 }
142
143 // Path returns the path to currently open database file.
144 func (db *DB) Path() string {
145 return db.path
146 }
147
148 // GoString returns the Go string representation of the database.
149 func (db *DB) GoString() string {
150 return fmt.Sprintf("bolt.DB{path:%q}", db.path)
151 }
152
153 // String returns the string representation of the database.
154 func (db *DB) String() string {
155 return fmt.Sprintf("DB<%q>", db.path)
156 }
157
158 // Open creates and opens a database at the given path.
159 // If the file does not exist then it will be created automatically.
160 // Passing in nil options will cause Bolt to open the database with the default options.
161 func Open(path string, mode os.FileMode, options *Options) (*DB, error) {
162 db := &DB{
163 opened: true,
164 }
165 // Set default options if no options are provided.
166 if options == nil {
167 options = DefaultOptions
168 }
169 db.NoSync = options.NoSync
170 db.NoGrowSync = options.NoGrowSync
171 db.MmapFlags = options.MmapFlags
172 db.NoFreelistSync = options.NoFreelistSync
173
174 // Set default values for later DB operations.
175 db.MaxBatchSize = DefaultMaxBatchSize
176 db.MaxBatchDelay = DefaultMaxBatchDelay
177 db.AllocSize = DefaultAllocSize
178
179 flag := os.O_RDWR
180 if options.ReadOnly {
181 flag = os.O_RDONLY
182 db.readOnly = true
183 }
184
185 // Open data file and separate sync handler for metadata writes.
186 db.path = path
187 var err error
188 if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil {
189 _ = db.close()
190 return nil, err
191 }
192
193 // Lock file so that other processes using Bolt in read-write mode cannot
194 // use the database at the same time. This would cause corruption since
195 // the two processes would write meta pages and free pages separately.
196 // The database file is locked exclusively (only one process can grab the lock)
197 // if !options.ReadOnly.
198 // The database file is locked using the shared lock (more than one process may
199 // hold a lock at the same time) otherwise (options.ReadOnly is set).
200 if err := flock(db, mode, !db.readOnly, options.Timeout); err != nil {
201 db.lockfile = nil // make 'unused' happy. TODO: rework locks
202 _ = db.close()
203 return nil, err
204 }
205
206 // Default values for test hooks
207 db.ops.writeAt = db.file.WriteAt
208
209 if db.pageSize = options.PageSize; db.pageSize == 0 {
210 // Set the default page size to the OS page size.
211 db.pageSize = defaultPageSize
212 }
213
214 // Initialize the database if it doesn't exist.
215 if info, err := db.file.Stat(); err != nil {
216 return nil, err
217 } else if info.Size() == 0 {
218 // Initialize new files with meta pages.
219 if err := db.init(); err != nil {
220 return nil, err
221 }
222 } else {
223 // Read the first meta page to determine the page size.
224 var buf [0x1000]byte
225 // If we can't read the page size, but can read a page, assume
226 // it's the same as the OS or one given -- since that's how the
227 // page size was chosen in the first place.
228 //
229 // If the first page is invalid and this OS uses a different
230 // page size than what the database was created with then we
231 // are out of luck and cannot access the database.
232 //
233 // TODO: scan for next page
234 if bw, err := db.file.ReadAt(buf[:], 0); err == nil && bw == len(buf) {
235 if m := db.pageInBuffer(buf[:], 0).meta(); m.validate() == nil {
236 db.pageSize = int(m.pageSize)
237 }
238 } else {
239 return nil, ErrInvalid
240 }
241 }
242
243 // Initialize page pool.
244 db.pagePool = sync.Pool{
245 New: func() interface{} {
246 return make([]byte, db.pageSize)
247 },
248 }
249
250 // Memory map the data file.
251 if err := db.mmap(options.InitialMmapSize); err != nil {
252 _ = db.close()
253 return nil, err
254 }
255
256 if db.readOnly {
257 return db, nil
258 }
259
260 db.loadFreelist()
261
262 // Flush freelist when transitioning from no sync to sync so
263 // NoFreelistSync unaware boltdb can open the db later.
264 if !db.NoFreelistSync && !db.hasSyncedFreelist() {
265 tx, err := db.Begin(true)
266 if tx != nil {
267 err = tx.Commit()
268 }
269 if err != nil {
270 _ = db.close()
271 return nil, err
272 }
273 }
274
275 // Mark the database as opened and return.
276 return db, nil
277 }
278
279 // loadFreelist reads the freelist if it is synced, or reconstructs it
280 // by scanning the DB if it is not synced. It assumes there are no
281 // concurrent accesses being made to the freelist.
282 func (db *DB) loadFreelist() {
283 db.freelistLoad.Do(func() {
284 db.freelist = newFreelist()
285 if !db.hasSyncedFreelist() {
286 // Reconstruct free list by scanning the DB.
287 db.freelist.readIDs(db.freepages())
288 } else {
289 // Read free list from freelist page.
290 db.freelist.read(db.page(db.meta().freelist))
291 }
292 db.stats.FreePageN = len(db.freelist.ids)
293 })
294 }
295
296 func (db *DB) hasSyncedFreelist() bool {
297 return db.meta().freelist != pgidNoFreelist
298 }
299
300 // mmap opens the underlying memory-mapped file and initializes the meta references.
301 // minsz is the minimum size that the new mmap can be.
302 func (db *DB) mmap(minsz int) error {
303 db.mmaplock.Lock()
304 defer db.mmaplock.Unlock()
305
306 info, err := db.file.Stat()
307 if err != nil {
308 return fmt.Errorf("mmap stat error: %s", err)
309 } else if int(info.Size()) < db.pageSize*2 {
310 return fmt.Errorf("file size too small")
311 }
312
313 // Ensure the size is at least the minimum size.
314 var size = int(info.Size())
315 if size < minsz {
316 size = minsz
317 }
318 size, err = db.mmapSize(size)
319 if err != nil {
320 return err
321 }
322
323 // Dereference all mmap references before unmapping.
324 if db.rwtx != nil {
325 db.rwtx.root.dereference()
326 }
327
328 // Unmap existing data before continuing.
329 if err := db.munmap(); err != nil {
330 return err
331 }
332
333 // Memory-map the data file as a byte slice.
334 if err := mmap(db, size); err != nil {
335 return err
336 }
337
338 // Save references to the meta pages.
339 db.meta0 = db.page(0).meta()
340 db.meta1 = db.page(1).meta()
341
342 // Validate the meta pages. We only return an error if both meta pages fail
343 // validation, since meta0 failing validation means that it wasn't saved
344 // properly -- but we can recover using meta1. And vice-versa.
345 err0 := db.meta0.validate()
346 err1 := db.meta1.validate()
347 if err0 != nil && err1 != nil {
348 return err0
349 }
350
351 return nil
352 }
353
354 // munmap unmaps the data file from memory.
355 func (db *DB) munmap() error {
356 if err := munmap(db); err != nil {
357 return fmt.Errorf("unmap error: " + err.Error())
358 }
359 return nil
360 }
361
362 // mmapSize determines the appropriate size for the mmap given the current size
363 // of the database. The minimum size is 32KB and doubles until it reaches 1GB.
364 // Returns an error if the new mmap size is greater than the max allowed.
365 func (db *DB) mmapSize(size int) (int, error) {
366 // Double the size from 32KB until 1GB.
367 for i := uint(15); i <= 30; i++ {
368 if size <= 1<<i {
369 return 1 << i, nil
370 }
371 }
372
373 // Verify the requested size is not above the maximum allowed.
374 if size > maxMapSize {
375 return 0, fmt.Errorf("mmap too large")
376 }
377
378 // If larger than 1GB then grow by 1GB at a time.
379 sz := int64(size)
380 if remainder := sz % int64(maxMmapStep); remainder > 0 {
381 sz += int64(maxMmapStep) - remainder
382 }
383
384 // Ensure that the mmap size is a multiple of the page size.
385 // This should always be true since we're incrementing in MBs.
386 pageSize := int64(db.pageSize)
387 if (sz % pageSize) != 0 {
388 sz = ((sz / pageSize) + 1) * pageSize
389 }
390
391 // If we've exceeded the max size then only grow up to the max size.
392 if sz > maxMapSize {
393 sz = maxMapSize
394 }
395
396 return int(sz), nil
397 }
398
399 // init creates a new database file and initializes its meta pages.
400 func (db *DB) init() error {
401 // Create two meta pages on a buffer.
402 buf := make([]byte, db.pageSize*4)
403 for i := 0; i < 2; i++ {
404 p := db.pageInBuffer(buf[:], pgid(i))
405 p.id = pgid(i)
406 p.flags = metaPageFlag
407
408 // Initialize the meta page.
409 m := p.meta()
410 m.magic = magic
411 m.version = version
412 m.pageSize = uint32(db.pageSize)
413 m.freelist = 2
414 m.root = bucket{root: 3}
415 m.pgid = 4
416 m.txid = txid(i)
417 m.checksum = m.sum64()
418 }
419
420 // Write an empty freelist at page 3.
421 p := db.pageInBuffer(buf[:], pgid(2))
422 p.id = pgid(2)
423 p.flags = freelistPageFlag
424 p.count = 0
425
426 // Write an empty leaf page at page 4.
427 p = db.pageInBuffer(buf[:], pgid(3))
428 p.id = pgid(3)
429 p.flags = leafPageFlag
430 p.count = 0
431
432 // Write the buffer to our data file.
433 if _, err := db.ops.writeAt(buf, 0); err != nil {
434 return err
435 }
436 if err := fdatasync(db); err != nil {
437 return err
438 }
439
440 return nil
441 }
442
443 // Close releases all database resources.
444 // All transactions must be closed before closing the database.
445 func (db *DB) Close() error {
446 db.rwlock.Lock()
447 defer db.rwlock.Unlock()
448
449 db.metalock.Lock()
450 defer db.metalock.Unlock()
451
452 db.mmaplock.RLock()
453 defer db.mmaplock.RUnlock()
454
455 return db.close()
456 }
457
458 func (db *DB) close() error {
459 if !db.opened {
460 return nil
461 }
462
463 db.opened = false
464
465 db.freelist = nil
466
467 // Clear ops.
468 db.ops.writeAt = nil
469
470 // Close the mmap.
471 if err := db.munmap(); err != nil {
472 return err
473 }
474
475 // Close file handles.
476 if db.file != nil {
477 // No need to unlock read-only file.
478 if !db.readOnly {
479 // Unlock the file.
480 if err := funlock(db); err != nil {
481 log.Printf("bolt.Close(): funlock error: %s", err)
482 }
483 }
484
485 // Close the file descriptor.
486 if err := db.file.Close(); err != nil {
487 return fmt.Errorf("db file close: %s", err)
488 }
489 db.file = nil
490 }
491
492 db.path = ""
493 return nil
494 }
495
496 // Begin starts a new transaction.
497 // Multiple read-only transactions can be used concurrently but only one
498 // write transaction can be used at a time. Starting multiple write transactions
499 // will cause the calls to block and be serialized until the current write
500 // transaction finishes.
501 //
502 // Transactions should not be dependent on one another. Opening a read
503 // transaction and a write transaction in the same goroutine can cause the
504 // writer to deadlock because the database periodically needs to re-mmap itself
505 // as it grows and it cannot do that while a read transaction is open.
506 //
507 // If a long running read transaction (for example, a snapshot transaction) is
508 // needed, you might want to set DB.InitialMmapSize to a large enough value
509 // to avoid potential blocking of write transaction.
510 //
511 // IMPORTANT: You must close read-only transactions after you are finished or
512 // else the database will not reclaim old pages.
513 func (db *DB) Begin(writable bool) (*Tx, error) {
514 if writable {
515 return db.beginRWTx()
516 }
517 return db.beginTx()
518 }
519
520 func (db *DB) beginTx() (*Tx, error) {
521 // Lock the meta pages while we initialize the transaction. We obtain
522 // the meta lock before the mmap lock because that's the order that the
523 // write transaction will obtain them.
524 db.metalock.Lock()
525
526 // Obtain a read-only lock on the mmap. When the mmap is remapped it will
527 // obtain a write lock so all transactions must finish before it can be
528 // remapped.
529 db.mmaplock.RLock()
530
531 // Exit if the database is not open yet.
532 if !db.opened {
533 db.mmaplock.RUnlock()
534 db.metalock.Unlock()
535 return nil, ErrDatabaseNotOpen
536 }
537
538 // Create a transaction associated with the database.
539 t := &Tx{}
540 t.init(db)
541
542 // Keep track of transaction until it closes.
543 db.txs = append(db.txs, t)
544 n := len(db.txs)
545
546 // Unlock the meta pages.
547 db.metalock.Unlock()
548
549 // Update the transaction stats.
550 db.statlock.Lock()
551 db.stats.TxN++
552 db.stats.OpenTxN = n
553 db.statlock.Unlock()
554
555 return t, nil
556 }
557
558 func (db *DB) beginRWTx() (*Tx, error) {
559 // If the database was opened with Options.ReadOnly, return an error.
560 if db.readOnly {
561 return nil, ErrDatabaseReadOnly
562 }
563
564 // Obtain writer lock. This is released by the transaction when it closes.
565 // This enforces only one writer transaction at a time.
566 db.rwlock.Lock()
567
568 // Once we have the writer lock then we can lock the meta pages so that
569 // we can set up the transaction.
570 db.metalock.Lock()
571 defer db.metalock.Unlock()
572
573 // Exit if the database is not open yet.
574 if !db.opened {
575 db.rwlock.Unlock()
576 return nil, ErrDatabaseNotOpen
577 }
578
579 // Create a transaction associated with the database.
580 t := &Tx{writable: true}
581 t.init(db)
582 db.rwtx = t
583 db.freePages()
584 return t, nil
585 }
586
587 // freePages releases any pages associated with closed read-only transactions.
588 func (db *DB) freePages() {
589 // Free all pending pages prior to earliest open transaction.
590 sort.Sort(txsById(db.txs))
591 minid := txid(0xFFFFFFFFFFFFFFFF)
592 if len(db.txs) > 0 {
593 minid = db.txs[0].meta.txid
594 }
595 if minid > 0 {
596 db.freelist.release(minid - 1)
597 }
598 // Release unused txid extents.
599 for _, t := range db.txs {
600 db.freelist.releaseRange(minid, t.meta.txid-1)
601 minid = t.meta.txid + 1
602 }
603 db.freelist.releaseRange(minid, txid(0xFFFFFFFFFFFFFFFF))
604 // Any page both allocated and freed in an extent is safe to release.
605 }
606
607 type txsById []*Tx
608
609 func (t txsById) Len() int { return len(t) }
610 func (t txsById) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
611 func (t txsById) Less(i, j int) bool { return t[i].meta.txid < t[j].meta.txid }
612
613 // removeTx removes a transaction from the database.
614 func (db *DB) removeTx(tx *Tx) {
615 // Release the read lock on the mmap.
616 db.mmaplock.RUnlock()
617
618 // Use the meta lock to restrict access to the DB object.
619 db.metalock.Lock()
620
621 // Remove the transaction.
622 for i, t := range db.txs {
623 if t == tx {
624 last := len(db.txs) - 1
625 db.txs[i] = db.txs[last]
626 db.txs[last] = nil
627 db.txs = db.txs[:last]
628 break
629 }
630 }
631 n := len(db.txs)
632
633 // Unlock the meta pages.
634 db.metalock.Unlock()
635
636 // Merge statistics.
637 db.statlock.Lock()
638 db.stats.OpenTxN = n
639 db.stats.TxStats.add(&tx.stats)
640 db.statlock.Unlock()
641 }
642
643 // Update executes a function within the context of a read-write managed transaction.
644 // If no error is returned from the function then the transaction is committed.
645 // If an error is returned then the entire transaction is rolled back.
646 // Any error that is returned from the function or returned from the commit is
647 // returned from the Update() method.
648 //
649 // Attempting to manually commit or rollback within the function will cause a panic.
650 func (db *DB) Update(fn func(*Tx) error) error {
651 t, err := db.Begin(true)
652 if err != nil {
653 return err
654 }
655
656 // Make sure the transaction rolls back in the event of a panic.
657 defer func() {
658 if t.db != nil {
659 t.rollback()
660 }
661 }()
662
663 // Mark as a managed tx so that the inner function cannot manually commit.
664 t.managed = true
665
666 // If an error is returned from the function then rollback and return error.
667 err = fn(t)
668 t.managed = false
669 if err != nil {
670 _ = t.Rollback()
671 return err
672 }
673
674 return t.Commit()
675 }
676
677 // View executes a function within the context of a managed read-only transaction.
678 // Any error that is returned from the function is returned from the View() method.
679 //
680 // Attempting to manually rollback within the function will cause a panic.
681 func (db *DB) View(fn func(*Tx) error) error {
682 t, err := db.Begin(false)
683 if err != nil {
684 return err
685 }
686
687 // Make sure the transaction rolls back in the event of a panic.
688 defer func() {
689 if t.db != nil {
690 t.rollback()
691 }
692 }()
693
694 // Mark as a managed tx so that the inner function cannot manually rollback.
695 t.managed = true
696
697 // If an error is returned from the function then pass it through.
698 err = fn(t)
699 t.managed = false
700 if err != nil {
701 _ = t.Rollback()
702 return err
703 }
704
705 return t.Rollback()
706 }
707
708 // Batch calls fn as part of a batch. It behaves similar to Update,
709 // except:
710 //
711 // 1. concurrent Batch calls can be combined into a single Bolt
712 // transaction.
713 //
714 // 2. the function passed to Batch may be called multiple times,
715 // regardless of whether it returns error or not.
716 //
717 // This means that Batch function side effects must be idempotent and
718 // take permanent effect only after a successful return is seen in
719 // caller.
720 //
721 // The maximum batch size and delay can be adjusted with DB.MaxBatchSize
722 // and DB.MaxBatchDelay, respectively.
723 //
724 // Batch is only useful when there are multiple goroutines calling it.
725 func (db *DB) Batch(fn func(*Tx) error) error {
726 errCh := make(chan error, 1)
727
728 db.batchMu.Lock()
729 if (db.batch == nil) || (db.batch != nil && len(db.batch.calls) >= db.MaxBatchSize) {
730 // There is no existing batch, or the existing batch is full; start a new one.
731 db.batch = &batch{
732 db: db,
733 }
734 db.batch.timer = time.AfterFunc(db.MaxBatchDelay, db.batch.trigger)
735 }
736 db.batch.calls = append(db.batch.calls, call{fn: fn, err: errCh})
737 if len(db.batch.calls) >= db.MaxBatchSize {
738 // wake up batch, it's ready to run
739 go db.batch.trigger()
740 }
741 db.batchMu.Unlock()
742
743 err := <-errCh
744 if err == trySolo {
745 err = db.Update(fn)
746 }
747 return err
748 }
749
750 type call struct {
751 fn func(*Tx) error
752 err chan<- error
753 }
754
755 type batch struct {
756 db *DB
757 timer *time.Timer
758 start sync.Once
759 calls []call
760 }
761
762 // trigger runs the batch if it hasn't already been run.
763 func (b *batch) trigger() {
764 b.start.Do(b.run)
765 }
766
767 // run performs the transactions in the batch and communicates results
768 // back to DB.Batch.
769 func (b *batch) run() {
770 b.db.batchMu.Lock()
771 b.timer.Stop()
772 // Make sure no new work is added to this batch, but don't break
773 // other batches.
774 if b.db.batch == b {
775 b.db.batch = nil
776 }
777 b.db.batchMu.Unlock()
778
779 retry:
780 for len(b.calls) > 0 {
781 var failIdx = -1
782 err := b.db.Update(func(tx *Tx) error {
783 for i, c := range b.calls {
784 if err := safelyCall(c.fn, tx); err != nil {
785 failIdx = i
786 return err
787 }
788 }
789 return nil
790 })
791
792 if failIdx >= 0 {
793 // take the failing transaction out of the batch. it's
794 // safe to shorten b.calls here because db.batch no longer
795 // points to us, and we hold the mutex anyway.
796 c := b.calls[failIdx]
797 b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1]
798 // tell the submitter re-run it solo, continue with the rest of the batch
799 c.err <- trySolo
800 continue retry
801 }
802
803 // pass success, or bolt internal errors, to all callers
804 for _, c := range b.calls {
805 c.err <- err
806 }
807 break retry
808 }
809 }
810
811 // trySolo is a special sentinel error value used for signaling that a
812 // transaction function should be re-run. It should never be seen by
813 // callers.
814 var trySolo = errors.New("batch function returned an error and should be re-run solo")
815
816 type panicked struct {
817 reason interface{}
818 }
819
820 func (p panicked) Error() string {
821 if err, ok := p.reason.(error); ok {
822 return err.Error()
823 }
824 return fmt.Sprintf("panic: %v", p.reason)
825 }
826
827 func safelyCall(fn func(*Tx) error, tx *Tx) (err error) {
828 defer func() {
829 if p := recover(); p != nil {
830 err = panicked{p}
831 }
832 }()
833 return fn(tx)
834 }
835
836 // Sync executes fdatasync() against the database file handle.
837 //
838 // This is not necessary under normal operation, however, if you use NoSync
839 // then it allows you to force the database file to sync against the disk.
840 func (db *DB) Sync() error { return fdatasync(db) }
841
842 // Stats retrieves ongoing performance stats for the database.
843 // This is only updated when a transaction closes.
844 func (db *DB) Stats() Stats {
845 db.statlock.RLock()
846 defer db.statlock.RUnlock()
847 return db.stats
848 }
849
850 // This is for internal access to the raw data bytes from the C cursor, use
851 // carefully, or not at all.
852 func (db *DB) Info() *Info {
853 return &Info{uintptr(unsafe.Pointer(&db.data[0])), db.pageSize}
854 }
855
856 // page retrieves a page reference from the mmap based on the current page size.
857 func (db *DB) page(id pgid) *page {
858 pos := id * pgid(db.pageSize)
859 return (*page)(unsafe.Pointer(&db.data[pos]))
860 }
861
862 // pageInBuffer retrieves a page reference from a given byte array based on the current page size.
863 func (db *DB) pageInBuffer(b []byte, id pgid) *page {
864 return (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)]))
865 }
866
867 // meta retrieves the current meta page reference.
868 func (db *DB) meta() *meta {
869 // We have to return the meta with the highest txid which doesn't fail
870 // validation. Otherwise, we can cause errors when in fact the database is
871 // in a consistent state. metaA is the one with the higher txid.
872 metaA := db.meta0
873 metaB := db.meta1
874 if db.meta1.txid > db.meta0.txid {
875 metaA = db.meta1
876 metaB = db.meta0
877 }
878
879 // Use higher meta page if valid. Otherwise fallback to previous, if valid.
880 if err := metaA.validate(); err == nil {
881 return metaA
882 } else if err := metaB.validate(); err == nil {
883 return metaB
884 }
885
886 // This should never be reached, because both meta1 and meta0 were validated
887 // on mmap() and we do fsync() on every write.
888 panic("bolt.DB.meta(): invalid meta pages")
889 }
890
891 // allocate returns a contiguous block of memory starting at a given page.
892 func (db *DB) allocate(txid txid, count int) (*page, error) {
893 // Allocate a temporary buffer for the page.
894 var buf []byte
895 if count == 1 {
896 buf = db.pagePool.Get().([]byte)
897 } else {
898 buf = make([]byte, count*db.pageSize)
899 }
900 p := (*page)(unsafe.Pointer(&buf[0]))
901 p.overflow = uint32(count - 1)
902
903 // Use pages from the freelist if they are available.
904 if p.id = db.freelist.allocate(txid, count); p.id != 0 {
905 return p, nil
906 }
907
908 // Resize mmap() if we're at the end.
909 p.id = db.rwtx.meta.pgid
910 var minsz = int((p.id+pgid(count))+1) * db.pageSize
911 if minsz >= db.datasz {
912 if err := db.mmap(minsz); err != nil {
913 return nil, fmt.Errorf("mmap allocate error: %s", err)
914 }
915 }
916
917 // Move the page id high water mark.
918 db.rwtx.meta.pgid += pgid(count)
919
920 return p, nil
921 }
922
923 // grow grows the size of the database to the given sz.
924 func (db *DB) grow(sz int) error {
925 // Ignore if the new size is less than available file size.
926 if sz <= db.filesz {
927 return nil
928 }
929
930 // If the data is smaller than the alloc size then only allocate what's needed.
931 // Once it goes over the allocation size then allocate in chunks.
932 if db.datasz < db.AllocSize {
933 sz = db.datasz
934 } else {
935 sz += db.AllocSize
936 }
937
938 // Truncate and fsync to ensure file size metadata is flushed.
939 // https://github.com/boltdb/bolt/issues/284
940 if !db.NoGrowSync && !db.readOnly {
941 if runtime.GOOS != "windows" {
942 if err := db.file.Truncate(int64(sz)); err != nil {
943 return fmt.Errorf("file resize error: %s", err)
944 }
945 }
946 if err := db.file.Sync(); err != nil {
947 return fmt.Errorf("file sync error: %s", err)
948 }
949 }
950
951 db.filesz = sz
952 return nil
953 }
954
955 func (db *DB) IsReadOnly() bool {
956 return db.readOnly
957 }
958
959 func (db *DB) freepages() []pgid {
960 tx, err := db.beginTx()
961 defer func() {
962 err = tx.Rollback()
963 if err != nil {
964 panic("freepages: failed to rollback tx")
965 }
966 }()
967 if err != nil {
968 panic("freepages: failed to open read only tx")
969 }
970
971 reachable := make(map[pgid]*page)
972 nofreed := make(map[pgid]bool)
973 ech := make(chan error)
974 go func() {
975 for e := range ech {
976 panic(fmt.Sprintf("freepages: failed to get all reachable pages (%v)", e))
977 }
978 }()
979 tx.checkBucket(&tx.root, reachable, nofreed, ech)
980 close(ech)
981
982 var fids []pgid
983 for i := pgid(2); i < db.meta().pgid; i++ {
984 if _, ok := reachable[i]; !ok {
985 fids = append(fids, i)
986 }
987 }
988 return fids
989 }
990
991 // Options represents the options that can be set when opening a database.
992 type Options struct {
993 // Timeout is the amount of time to wait to obtain a file lock.
994 // When set to zero it will wait indefinitely. This option is only
995 // available on Darwin and Linux.
996 Timeout time.Duration
997
998 // Sets the DB.NoGrowSync flag before memory mapping the file.
999 NoGrowSync bool
1000
1001 // Do not sync freelist to disk. This improves the database write performance
1002 // under normal operation, but requires a full database re-sync during recovery.
1003 NoFreelistSync bool
1004
1005 // Open database in read-only mode. Uses flock(..., LOCK_SH |LOCK_NB) to
1006 // grab a shared lock (UNIX).
1007 ReadOnly bool
1008
1009 // Sets the DB.MmapFlags flag before memory mapping the file.
1010 MmapFlags int
1011
1012 // InitialMmapSize is the initial mmap size of the database
1013 // in bytes. Read transactions won't block write transaction
1014 // if the InitialMmapSize is large enough to hold database mmap
1015 // size. (See DB.Begin for more information)
1016 //
1017 // If <=0, the initial map size is 0.
1018 // If initialMmapSize is smaller than the previous database size,
1019 // it takes no effect.
1020 InitialMmapSize int
1021
1022 // PageSize overrides the default OS page size.
1023 PageSize int
1024
1025 // NoSync sets the initial value of DB.NoSync. Normally this can just be
1026 // set directly on the DB itself when returned from Open(), but this option
1027 // is useful in APIs which expose Options but not the underlying DB.
1028 NoSync bool
1029 }
1030
1031 // DefaultOptions represent the options used if nil options are passed into Open().
1032 // No timeout is used which will cause Bolt to wait indefinitely for a lock.
1033 var DefaultOptions = &Options{
1034 Timeout: 0,
1035 NoGrowSync: false,
1036 }
1037
1038 // Stats represents statistics about the database.
1039 type Stats struct {
1040 // Freelist stats
1041 FreePageN int // total number of free pages on the freelist
1042 PendingPageN int // total number of pending pages on the freelist
1043 FreeAlloc int // total bytes allocated in free pages
1044 FreelistInuse int // total bytes used by the freelist
1045
1046 // Transaction stats
1047 TxN int // total number of started read transactions
1048 OpenTxN int // number of currently open read transactions
1049
1050 TxStats TxStats // global, ongoing stats.
1051 }
1052
1053 // Sub calculates and returns the difference between two sets of database stats.
1054 // This is useful when obtaining stats at two different points and time and
1055 // you need the performance counters that occurred within that time span.
1056 func (s *Stats) Sub(other *Stats) Stats {
1057 if other == nil {
1058 return *s
1059 }
1060 var diff Stats
1061 diff.FreePageN = s.FreePageN
1062 diff.PendingPageN = s.PendingPageN
1063 diff.FreeAlloc = s.FreeAlloc
1064 diff.FreelistInuse = s.FreelistInuse
1065 diff.TxN = s.TxN - other.TxN
1066 diff.TxStats = s.TxStats.Sub(&other.TxStats)
1067 return diff
1068 }
1069
1070 type Info struct {
1071 Data uintptr
1072 PageSize int
1073 }
1074
1075 type meta struct {
1076 magic uint32
1077 version uint32
1078 pageSize uint32
1079 flags uint32
1080 root bucket
1081 freelist pgid
1082 pgid pgid
1083 txid txid
1084 checksum uint64
1085 }
1086
1087 // validate checks the marker bytes and version of the meta page to ensure it matches this binary.
1088 func (m *meta) validate() error {
1089 if m.magic != magic {
1090 return ErrInvalid
1091 } else if m.version != version {
1092 return ErrVersionMismatch
1093 } else if m.checksum != 0 && m.checksum != m.sum64() {
1094 return ErrChecksum
1095 }
1096 return nil
1097 }
1098
1099 // copy copies one meta object to another.
1100 func (m *meta) copy(dest *meta) {
1101 *dest = *m
1102 }
1103
1104 // write writes the meta onto a page.
1105 func (m *meta) write(p *page) {
1106 if m.root.root >= m.pgid {
1107 panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", m.root.root, m.pgid))
1108 } else if m.freelist >= m.pgid && m.freelist != pgidNoFreelist {
1109 // TODO: reject pgidNoFreeList if !NoFreelistSync
1110 panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", m.freelist, m.pgid))
1111 }
1112
1113 // Page id is either going to be 0 or 1 which we can determine by the transaction ID.
1114 p.id = pgid(m.txid % 2)
1115 p.flags |= metaPageFlag
1116
1117 // Calculate the checksum.
1118 m.checksum = m.sum64()
1119
1120 m.copy(p.meta())
1121 }
1122
1123 // generates the checksum for the meta.
1124 func (m *meta) sum64() uint64 {
1125 var h = fnv.New64a()
1126 _, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:])
1127 return h.Sum64()
1128 }
1129
1130 // _assert will panic with a given formatted message if the given condition is false.
1131 func _assert(condition bool, msg string, v ...interface{}) {
1132 if !condition {
1133 panic(fmt.Sprintf("assertion failed: "+msg, v...))
1134 }
1135 }