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.

db.go 32KB

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