You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1135 lines
30 KiB

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