tx.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. package bolt
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "sort"
  7. "strings"
  8. "time"
  9. "unsafe"
  10. )
  11. // txid represents the internal transaction identifier.
  12. type txid uint64
  13. // Tx represents a read-only or read/write transaction on the database.
  14. // Read-only transactions can be used for retrieving values for keys and creating cursors.
  15. // Read/write transactions can create and remove buckets and create and remove keys.
  16. //
  17. // IMPORTANT: You must commit or rollback transactions when you are done with
  18. // them. Pages can not be reclaimed by the writer until no more transactions
  19. // are using them. A long running read transaction can cause the database to
  20. // quickly grow.
  21. type Tx struct {
  22. writable bool
  23. managed bool
  24. db *DB
  25. meta *meta
  26. root Bucket
  27. pages map[pgid]*page
  28. stats TxStats
  29. commitHandlers []func()
  30. // WriteFlag specifies the flag for write-related methods like WriteTo().
  31. // Tx opens the database file with the specified flag to copy the data.
  32. //
  33. // By default, the flag is unset, which works well for mostly in-memory
  34. // workloads. For databases that are much larger than available RAM,
  35. // set the flag to syscall.O_DIRECT to avoid trashing the page cache.
  36. WriteFlag int
  37. }
  38. // init initializes the transaction.
  39. func (tx *Tx) init(db *DB) {
  40. tx.db = db
  41. tx.pages = nil
  42. // Copy the meta page since it can be changed by the writer.
  43. tx.meta = &meta{}
  44. db.meta().copy(tx.meta)
  45. // Copy over the root bucket.
  46. tx.root = newBucket(tx)
  47. tx.root.bucket = &bucket{}
  48. *tx.root.bucket = tx.meta.root
  49. // Increment the transaction id and add a page cache for writable transactions.
  50. if tx.writable {
  51. tx.pages = make(map[pgid]*page)
  52. tx.meta.txid += txid(1)
  53. }
  54. }
  55. // ID returns the transaction id.
  56. func (tx *Tx) ID() int {
  57. return int(tx.meta.txid)
  58. }
  59. // DB returns a reference to the database that created the transaction.
  60. func (tx *Tx) DB() *DB {
  61. return tx.db
  62. }
  63. // Size returns current database size in bytes as seen by this transaction.
  64. func (tx *Tx) Size() int64 {
  65. return int64(tx.meta.pgid) * int64(tx.db.pageSize)
  66. }
  67. // Writable returns whether the transaction can perform write operations.
  68. func (tx *Tx) Writable() bool {
  69. return tx.writable
  70. }
  71. // Cursor creates a cursor associated with the root bucket.
  72. // All items in the cursor will return a nil value because all root bucket keys point to buckets.
  73. // The cursor is only valid as long as the transaction is open.
  74. // Do not use a cursor after the transaction is closed.
  75. func (tx *Tx) Cursor() *Cursor {
  76. return tx.root.Cursor()
  77. }
  78. // Stats retrieves a copy of the current transaction statistics.
  79. func (tx *Tx) Stats() TxStats {
  80. return tx.stats
  81. }
  82. // Bucket retrieves a bucket by name.
  83. // Returns nil if the bucket does not exist.
  84. // The bucket instance is only valid for the lifetime of the transaction.
  85. func (tx *Tx) Bucket(name []byte) *Bucket {
  86. return tx.root.Bucket(name)
  87. }
  88. // CreateBucket creates a new bucket.
  89. // Returns an error if the bucket already exists, if the bucket name is blank, or if the bucket name is too long.
  90. // The bucket instance is only valid for the lifetime of the transaction.
  91. func (tx *Tx) CreateBucket(name []byte) (*Bucket, error) {
  92. return tx.root.CreateBucket(name)
  93. }
  94. // CreateBucketIfNotExists creates a new bucket if it doesn't already exist.
  95. // Returns an error if the bucket name is blank, or if the bucket name is too long.
  96. // The bucket instance is only valid for the lifetime of the transaction.
  97. func (tx *Tx) CreateBucketIfNotExists(name []byte) (*Bucket, error) {
  98. return tx.root.CreateBucketIfNotExists(name)
  99. }
  100. // DeleteBucket deletes a bucket.
  101. // Returns an error if the bucket cannot be found or if the key represents a non-bucket value.
  102. func (tx *Tx) DeleteBucket(name []byte) error {
  103. return tx.root.DeleteBucket(name)
  104. }
  105. // ForEach executes a function for each bucket in the root.
  106. // If the provided function returns an error then the iteration is stopped and
  107. // the error is returned to the caller.
  108. func (tx *Tx) ForEach(fn func(name []byte, b *Bucket) error) error {
  109. return tx.root.ForEach(func(k, v []byte) error {
  110. return fn(k, tx.root.Bucket(k))
  111. })
  112. }
  113. // OnCommit adds a handler function to be executed after the transaction successfully commits.
  114. func (tx *Tx) OnCommit(fn func()) {
  115. tx.commitHandlers = append(tx.commitHandlers, fn)
  116. }
  117. // Commit writes all changes to disk and updates the meta page.
  118. // Returns an error if a disk write error occurs, or if Commit is
  119. // called on a read-only transaction.
  120. func (tx *Tx) Commit() error {
  121. _assert(!tx.managed, "managed tx commit not allowed")
  122. if tx.db == nil {
  123. return ErrTxClosed
  124. } else if !tx.writable {
  125. return ErrTxNotWritable
  126. }
  127. // TODO(benbjohnson): Use vectorized I/O to write out dirty pages.
  128. // Rebalance nodes which have had deletions.
  129. var startTime = time.Now()
  130. tx.root.rebalance()
  131. if tx.stats.Rebalance > 0 {
  132. tx.stats.RebalanceTime += time.Since(startTime)
  133. }
  134. // spill data onto dirty pages.
  135. startTime = time.Now()
  136. if err := tx.root.spill(); err != nil {
  137. tx.rollback()
  138. return err
  139. }
  140. tx.stats.SpillTime += time.Since(startTime)
  141. // Free the old root bucket.
  142. tx.meta.root.root = tx.root.root
  143. // Free the old freelist because commit writes out a fresh freelist.
  144. if tx.meta.freelist != pgidNoFreelist {
  145. tx.db.freelist.free(tx.meta.txid, tx.db.page(tx.meta.freelist))
  146. }
  147. if !tx.db.NoFreelistSync {
  148. err := tx.commitFreelist()
  149. if err != nil {
  150. return err
  151. }
  152. } else {
  153. tx.meta.freelist = pgidNoFreelist
  154. }
  155. // Write dirty pages to disk.
  156. startTime = time.Now()
  157. if err := tx.write(); err != nil {
  158. tx.rollback()
  159. return err
  160. }
  161. // If strict mode is enabled then perform a consistency check.
  162. // Only the first consistency error is reported in the panic.
  163. if tx.db.StrictMode {
  164. ch := tx.Check()
  165. var errs []string
  166. for {
  167. err, ok := <-ch
  168. if !ok {
  169. break
  170. }
  171. errs = append(errs, err.Error())
  172. }
  173. if len(errs) > 0 {
  174. panic("check fail: " + strings.Join(errs, "\n"))
  175. }
  176. }
  177. // Write meta to disk.
  178. if err := tx.writeMeta(); err != nil {
  179. tx.rollback()
  180. return err
  181. }
  182. tx.stats.WriteTime += time.Since(startTime)
  183. // Finalize the transaction.
  184. tx.close()
  185. // Execute commit handlers now that the locks have been removed.
  186. for _, fn := range tx.commitHandlers {
  187. fn()
  188. }
  189. return nil
  190. }
  191. func (tx *Tx) commitFreelist() error {
  192. // Allocate new pages for the new free list. This will overestimate
  193. // the size of the freelist but not underestimate the size (which would be bad).
  194. opgid := tx.meta.pgid
  195. p, err := tx.allocate((tx.db.freelist.size() / tx.db.pageSize) + 1)
  196. if err != nil {
  197. tx.rollback()
  198. return err
  199. }
  200. if err := tx.db.freelist.write(p); err != nil {
  201. tx.rollback()
  202. return err
  203. }
  204. tx.meta.freelist = p.id
  205. // If the high water mark has moved up then attempt to grow the database.
  206. if tx.meta.pgid > opgid {
  207. if err := tx.db.grow(int(tx.meta.pgid+1) * tx.db.pageSize); err != nil {
  208. tx.rollback()
  209. return err
  210. }
  211. }
  212. return nil
  213. }
  214. // Rollback closes the transaction and ignores all previous updates. Read-only
  215. // transactions must be rolled back and not committed.
  216. func (tx *Tx) Rollback() error {
  217. _assert(!tx.managed, "managed tx rollback not allowed")
  218. if tx.db == nil {
  219. return ErrTxClosed
  220. }
  221. tx.nonPhysicalRollback()
  222. return nil
  223. }
  224. // nonPhysicalRollback is called when user calls Rollback directly, in this case we do not need to reload the free pages from disk.
  225. func (tx *Tx) nonPhysicalRollback() {
  226. if tx.db == nil {
  227. return
  228. }
  229. if tx.writable {
  230. tx.db.freelist.rollback(tx.meta.txid)
  231. }
  232. tx.close()
  233. }
  234. // rollback needs to reload the free pages from disk in case some system error happens like fsync error.
  235. func (tx *Tx) rollback() {
  236. if tx.db == nil {
  237. return
  238. }
  239. // [Psiphon]
  240. // https://github.com/etcd-io/bbolt/commit/b3e98dcb3752e0a8d5db6503b80fe19e462fdb73
  241. // If the transaction failed due to mmap, rollback is futile.
  242. if tx.db.mmapErr != nil {
  243. tx.close()
  244. return
  245. }
  246. if tx.writable {
  247. tx.db.freelist.rollback(tx.meta.txid)
  248. if !tx.db.hasSyncedFreelist() {
  249. // Reconstruct free page list by scanning the DB to get the whole free page list.
  250. // Note: scaning the whole db is heavy if your db size is large in NoSyncFreeList mode.
  251. tx.db.freelist.noSyncReload(tx.db.freepages())
  252. } else {
  253. // Read free page list from freelist page.
  254. tx.db.freelist.reload(tx.db.page(tx.db.meta().freelist))
  255. }
  256. }
  257. tx.close()
  258. }
  259. func (tx *Tx) close() {
  260. if tx.db == nil {
  261. return
  262. }
  263. if tx.writable {
  264. // Grab freelist stats.
  265. var freelistFreeN = tx.db.freelist.free_count()
  266. var freelistPendingN = tx.db.freelist.pending_count()
  267. var freelistAlloc = tx.db.freelist.size()
  268. // Remove transaction ref & writer lock.
  269. tx.db.rwtx = nil
  270. tx.db.rwlock.Unlock()
  271. // Merge statistics.
  272. tx.db.statlock.Lock()
  273. tx.db.stats.FreePageN = freelistFreeN
  274. tx.db.stats.PendingPageN = freelistPendingN
  275. tx.db.stats.FreeAlloc = (freelistFreeN + freelistPendingN) * tx.db.pageSize
  276. tx.db.stats.FreelistInuse = freelistAlloc
  277. tx.db.stats.TxStats.add(&tx.stats)
  278. tx.db.statlock.Unlock()
  279. } else {
  280. tx.db.removeTx(tx)
  281. }
  282. // Clear all references.
  283. tx.db = nil
  284. tx.meta = nil
  285. tx.root = Bucket{tx: tx}
  286. tx.pages = nil
  287. }
  288. // Copy writes the entire database to a writer.
  289. // This function exists for backwards compatibility.
  290. //
  291. // Deprecated; Use WriteTo() instead.
  292. func (tx *Tx) Copy(w io.Writer) error {
  293. _, err := tx.WriteTo(w)
  294. return err
  295. }
  296. // WriteTo writes the entire database to a writer.
  297. // If err == nil then exactly tx.Size() bytes will be written into the writer.
  298. func (tx *Tx) WriteTo(w io.Writer) (n int64, err error) {
  299. // Attempt to open reader with WriteFlag
  300. f, err := tx.db.openFile(tx.db.path, os.O_RDONLY|tx.WriteFlag, 0)
  301. if err != nil {
  302. return 0, err
  303. }
  304. defer func() {
  305. if cerr := f.Close(); err == nil {
  306. err = cerr
  307. }
  308. }()
  309. // Generate a meta page. We use the same page data for both meta pages.
  310. buf := make([]byte, tx.db.pageSize)
  311. page := (*page)(unsafe.Pointer(&buf[0]))
  312. page.flags = metaPageFlag
  313. *page.meta() = *tx.meta
  314. // Write meta 0.
  315. page.id = 0
  316. page.meta().checksum = page.meta().sum64()
  317. nn, err := w.Write(buf)
  318. n += int64(nn)
  319. if err != nil {
  320. return n, fmt.Errorf("meta 0 copy: %s", err)
  321. }
  322. // Write meta 1 with a lower transaction id.
  323. page.id = 1
  324. page.meta().txid -= 1
  325. page.meta().checksum = page.meta().sum64()
  326. nn, err = w.Write(buf)
  327. n += int64(nn)
  328. if err != nil {
  329. return n, fmt.Errorf("meta 1 copy: %s", err)
  330. }
  331. // Move past the meta pages in the file.
  332. if _, err := f.Seek(int64(tx.db.pageSize*2), io.SeekStart); err != nil {
  333. return n, fmt.Errorf("seek: %s", err)
  334. }
  335. // Copy data pages.
  336. wn, err := io.CopyN(w, f, tx.Size()-int64(tx.db.pageSize*2))
  337. n += wn
  338. if err != nil {
  339. return n, err
  340. }
  341. return n, nil
  342. }
  343. // CopyFile copies the entire database to file at the given path.
  344. // A reader transaction is maintained during the copy so it is safe to continue
  345. // using the database while a copy is in progress.
  346. func (tx *Tx) CopyFile(path string, mode os.FileMode) error {
  347. f, err := tx.db.openFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
  348. if err != nil {
  349. return err
  350. }
  351. err = tx.Copy(f)
  352. if err != nil {
  353. _ = f.Close()
  354. return err
  355. }
  356. return f.Close()
  357. }
  358. // Check performs several consistency checks on the database for this transaction.
  359. // An error is returned if any inconsistency is found.
  360. //
  361. // It can be safely run concurrently on a writable transaction. However, this
  362. // incurs a high cost for large databases and databases with a lot of subbuckets
  363. // because of caching. This overhead can be removed if running on a read-only
  364. // transaction, however, it is not safe to execute other writer transactions at
  365. // the same time.
  366. func (tx *Tx) Check() <-chan error {
  367. ch := make(chan error)
  368. // [Psiphon]
  369. // This code is modified to use the single-error check function while
  370. // preserving the existing bolt Check API.
  371. go func() {
  372. err := tx.check()
  373. if err != nil {
  374. ch <- err
  375. }
  376. close(ch)
  377. }()
  378. return ch
  379. }
  380. // [Psiphon]
  381. // SynchronousCheck performs the Check function in the current goroutine,
  382. // allowing the caller to recover from any panics or faults.
  383. func (tx *Tx) SynchronousCheck() error {
  384. return tx.check()
  385. }
  386. // [Psiphon]
  387. // check is modified to stop and return on the first error. This prevents some
  388. // long running loops, perhaps due to looping based on corrupt data, that we
  389. // have observed when testing check against corrupted database files. Since
  390. // Psiphon will recover by resetting (deleting) the datastore on any error,
  391. // more than one error is not useful information in our case.
  392. func (tx *Tx) check() error {
  393. // Force loading free list if opened in ReadOnly mode.
  394. tx.db.loadFreelist()
  395. // Check if any pages are double freed.
  396. freed := make(map[pgid]bool)
  397. all := make([]pgid, tx.db.freelist.count())
  398. tx.db.freelist.copyall(all)
  399. for _, id := range all {
  400. if freed[id] {
  401. return fmt.Errorf("page %d: already freed", id)
  402. }
  403. freed[id] = true
  404. }
  405. // Track every reachable page.
  406. reachable := make(map[pgid]*page)
  407. reachable[0] = tx.page(0) // meta0
  408. reachable[1] = tx.page(1) // meta1
  409. if tx.meta.freelist != pgidNoFreelist {
  410. for i := uint32(0); i <= tx.page(tx.meta.freelist).overflow; i++ {
  411. reachable[tx.meta.freelist+pgid(i)] = tx.page(tx.meta.freelist)
  412. }
  413. }
  414. // Recursively check buckets.
  415. err := tx.checkBucket(&tx.root, reachable, freed)
  416. if err != nil {
  417. return err
  418. }
  419. // Ensure all pages below high water mark are either reachable or freed.
  420. for i := pgid(0); i < tx.meta.pgid; i++ {
  421. _, isReachable := reachable[i]
  422. if !isReachable && !freed[i] {
  423. return fmt.Errorf("page %d: unreachable unfreed", int(i))
  424. }
  425. }
  426. return nil
  427. }
  428. // [Psiphon]
  429. // checkBucket is modified to stop and return on the first error.
  430. func (tx *Tx) checkBucket(b *Bucket, reachable map[pgid]*page, freed map[pgid]bool) error {
  431. // Ignore inline buckets.
  432. if b.root == 0 {
  433. return nil
  434. }
  435. var err error
  436. // Check every page used by this bucket.
  437. b.tx.forEachPage(b.root, 0, func(p *page, _ int) {
  438. if p.id > tx.meta.pgid {
  439. err = fmt.Errorf("page %d: out of bounds: %d", int(p.id), int(b.tx.meta.pgid))
  440. return
  441. }
  442. // Ensure each page is only referenced once.
  443. for i := pgid(0); i <= pgid(p.overflow); i++ {
  444. var id = p.id + i
  445. if _, ok := reachable[id]; ok {
  446. err = fmt.Errorf("page %d: multiple references", int(id))
  447. return
  448. }
  449. reachable[id] = p
  450. }
  451. // We should only encounter un-freed leaf and branch pages.
  452. if freed[p.id] {
  453. err = fmt.Errorf("page %d: reachable freed", int(p.id))
  454. return
  455. } else if (p.flags&branchPageFlag) == 0 && (p.flags&leafPageFlag) == 0 {
  456. err = fmt.Errorf("page %d: invalid type: %s", int(p.id), p.typ())
  457. return
  458. }
  459. })
  460. if err != nil {
  461. return err
  462. }
  463. // Check each bucket within this bucket.
  464. return b.ForEach(func(k, v []byte) error {
  465. if child := b.Bucket(k); child != nil {
  466. err := tx.checkBucket(child, reachable, freed)
  467. if err != nil {
  468. return err
  469. }
  470. }
  471. return nil
  472. })
  473. }
  474. // allocate returns a contiguous block of memory starting at a given page.
  475. func (tx *Tx) allocate(count int) (*page, error) {
  476. p, err := tx.db.allocate(tx.meta.txid, count)
  477. if err != nil {
  478. return nil, err
  479. }
  480. // Save to our page cache.
  481. tx.pages[p.id] = p
  482. // Update statistics.
  483. tx.stats.PageCount += count
  484. tx.stats.PageAlloc += count * tx.db.pageSize
  485. return p, nil
  486. }
  487. // write writes any dirty pages to disk.
  488. func (tx *Tx) write() error {
  489. // Sort pages by id.
  490. pages := make(pages, 0, len(tx.pages))
  491. for _, p := range tx.pages {
  492. pages = append(pages, p)
  493. }
  494. // Clear out page cache early.
  495. tx.pages = make(map[pgid]*page)
  496. sort.Sort(pages)
  497. // Write pages to disk in order.
  498. for _, p := range pages {
  499. rem := (uint64(p.overflow) + 1) * uint64(tx.db.pageSize)
  500. offset := int64(p.id) * int64(tx.db.pageSize)
  501. var written uintptr
  502. // Write out page in "max allocation" sized chunks.
  503. for {
  504. sz := rem
  505. if sz > maxAllocSize-1 {
  506. sz = maxAllocSize - 1
  507. }
  508. buf := unsafeByteSlice(unsafe.Pointer(p), written, 0, int(sz))
  509. if _, err := tx.db.ops.writeAt(buf, offset); err != nil {
  510. return err
  511. }
  512. // Update statistics.
  513. tx.stats.Write++
  514. // Exit inner for loop if we've written all the chunks.
  515. rem -= sz
  516. if rem == 0 {
  517. break
  518. }
  519. // Otherwise move offset forward and move pointer to next chunk.
  520. offset += int64(sz)
  521. written += uintptr(sz)
  522. }
  523. }
  524. // Ignore file sync if flag is set on DB.
  525. if !tx.db.NoSync || IgnoreNoSync {
  526. if err := fdatasync(tx.db); err != nil {
  527. return err
  528. }
  529. }
  530. // Put small pages back to page pool.
  531. for _, p := range pages {
  532. // Ignore page sizes over 1 page.
  533. // These are allocated using make() instead of the page pool.
  534. if int(p.overflow) != 0 {
  535. continue
  536. }
  537. buf := unsafeByteSlice(unsafe.Pointer(p), 0, 0, tx.db.pageSize)
  538. // See https://go.googlesource.com/go/+/f03c9202c43e0abb130669852082117ca50aa9b1
  539. for i := range buf {
  540. buf[i] = 0
  541. }
  542. tx.db.pagePool.Put(buf)
  543. }
  544. return nil
  545. }
  546. // writeMeta writes the meta to the disk.
  547. func (tx *Tx) writeMeta() error {
  548. // Create a temporary buffer for the meta page.
  549. buf := make([]byte, tx.db.pageSize)
  550. p := tx.db.pageInBuffer(buf, 0)
  551. tx.meta.write(p)
  552. // Write the meta page to file.
  553. if _, err := tx.db.ops.writeAt(buf, int64(p.id)*int64(tx.db.pageSize)); err != nil {
  554. return err
  555. }
  556. if !tx.db.NoSync || IgnoreNoSync {
  557. if err := fdatasync(tx.db); err != nil {
  558. return err
  559. }
  560. }
  561. // Update statistics.
  562. tx.stats.Write++
  563. return nil
  564. }
  565. // page returns a reference to the page with a given id.
  566. // If page has been written to then a temporary buffered page is returned.
  567. func (tx *Tx) page(id pgid) *page {
  568. // Check the dirty pages first.
  569. if tx.pages != nil {
  570. if p, ok := tx.pages[id]; ok {
  571. return p
  572. }
  573. }
  574. // Otherwise return directly from the mmap.
  575. return tx.db.page(id)
  576. }
  577. // forEachPage iterates over every page within a given page and executes a function.
  578. func (tx *Tx) forEachPage(pgid pgid, depth int, fn func(*page, int)) {
  579. p := tx.page(pgid)
  580. // Execute function.
  581. fn(p, depth)
  582. // Recursively loop over children.
  583. if (p.flags & branchPageFlag) != 0 {
  584. for i := 0; i < int(p.count); i++ {
  585. elem := p.branchPageElement(uint16(i))
  586. tx.forEachPage(elem.pgid, depth+1, fn)
  587. }
  588. }
  589. }
  590. // Page returns page information for a given page number.
  591. // This is only safe for concurrent use when used by a writable transaction.
  592. func (tx *Tx) Page(id int) (*PageInfo, error) {
  593. if tx.db == nil {
  594. return nil, ErrTxClosed
  595. } else if pgid(id) >= tx.meta.pgid {
  596. return nil, nil
  597. }
  598. // Build the page info.
  599. p := tx.db.page(pgid(id))
  600. info := &PageInfo{
  601. ID: id,
  602. Count: int(p.count),
  603. OverflowCount: int(p.overflow),
  604. }
  605. // Determine the type (or if it's free).
  606. if tx.db.freelist.freed(pgid(id)) {
  607. info.Type = "free"
  608. } else {
  609. info.Type = p.typ()
  610. }
  611. return info, nil
  612. }
  613. // TxStats represents statistics about the actions performed by the transaction.
  614. type TxStats struct {
  615. // Page statistics.
  616. PageCount int // number of page allocations
  617. PageAlloc int // total bytes allocated
  618. // Cursor statistics.
  619. CursorCount int // number of cursors created
  620. // Node statistics
  621. NodeCount int // number of node allocations
  622. NodeDeref int // number of node dereferences
  623. // Rebalance statistics.
  624. Rebalance int // number of node rebalances
  625. RebalanceTime time.Duration // total time spent rebalancing
  626. // Split/Spill statistics.
  627. Split int // number of nodes split
  628. Spill int // number of nodes spilled
  629. SpillTime time.Duration // total time spent spilling
  630. // Write statistics.
  631. Write int // number of writes performed
  632. WriteTime time.Duration // total time spent writing to disk
  633. }
  634. func (s *TxStats) add(other *TxStats) {
  635. s.PageCount += other.PageCount
  636. s.PageAlloc += other.PageAlloc
  637. s.CursorCount += other.CursorCount
  638. s.NodeCount += other.NodeCount
  639. s.NodeDeref += other.NodeDeref
  640. s.Rebalance += other.Rebalance
  641. s.RebalanceTime += other.RebalanceTime
  642. s.Split += other.Split
  643. s.Spill += other.Spill
  644. s.SpillTime += other.SpillTime
  645. s.Write += other.Write
  646. s.WriteTime += other.WriteTime
  647. }
  648. // Sub calculates and returns the difference between two sets of transaction stats.
  649. // This is useful when obtaining stats at two different points and time and
  650. // you need the performance counters that occurred within that time span.
  651. func (s *TxStats) Sub(other *TxStats) TxStats {
  652. var diff TxStats
  653. diff.PageCount = s.PageCount - other.PageCount
  654. diff.PageAlloc = s.PageAlloc - other.PageAlloc
  655. diff.CursorCount = s.CursorCount - other.CursorCount
  656. diff.NodeCount = s.NodeCount - other.NodeCount
  657. diff.NodeDeref = s.NodeDeref - other.NodeDeref
  658. diff.Rebalance = s.Rebalance - other.Rebalance
  659. diff.RebalanceTime = s.RebalanceTime - other.RebalanceTime
  660. diff.Split = s.Split - other.Split
  661. diff.Spill = s.Spill - other.Spill
  662. diff.SpillTime = s.SpillTime - other.SpillTime
  663. diff.Write = s.Write - other.Write
  664. diff.WriteTime = s.WriteTime - other.WriteTime
  665. return diff
  666. }