Debian Codegraph @

vendor/github.com/coreos/bbolt/tx.go

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