db.go 29 KB

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