Debian Codegraph @

db.go

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