Debian Codegraph @

tx.go

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