package bbolt
import (
"errors"
"fmt"
"io"
"os"
"runtime"
"sort"
"strings"
"sync/atomic"
"time"
"unsafe"
berrors "go.etcd.io/bbolt/errors"
"go.etcd.io/bbolt/internal/common"
)
type Tx struct {
writable bool
managed bool
db *DB
meta *common .Meta
root Bucket
pages map [common .Pgid ]*common .Page
stats TxStats
commitHandlers []func ()
WriteFlag int
}
func (tx *Tx ) init (db *DB ) {
tx .db = db
tx .pages = nil
tx .meta = &common .Meta {}
db .meta ().Copy (tx .meta )
tx .root = newBucket (tx )
tx .root .InBucket = &common .InBucket {}
*tx .root .InBucket = *(tx .meta .RootBucket ())
if tx .writable {
tx .pages = make (map [common .Pgid ]*common .Page )
tx .meta .IncTxid ()
}
}
func (tx *Tx ) ID () int {
if tx == nil || tx .meta == nil {
return -1
}
return int (tx .meta .Txid ())
}
func (tx *Tx ) DB () *DB {
return tx .db
}
func (tx *Tx ) Size () int64 {
return int64 (tx .meta .Pgid ()) * int64 (tx .db .pageSize )
}
func (tx *Tx ) Writable () bool {
return tx .writable
}
func (tx *Tx ) Cursor () *Cursor {
return tx .root .Cursor ()
}
func (tx *Tx ) Stats () TxStats {
return tx .stats
}
func (tx *Tx ) Inspect () BucketStructure {
return tx .root .Inspect ()
}
func (tx *Tx ) Bucket (name []byte ) *Bucket {
return tx .root .Bucket (name )
}
func (tx *Tx ) CreateBucket (name []byte ) (*Bucket , error ) {
return tx .root .CreateBucket (name )
}
func (tx *Tx ) CreateBucketIfNotExists (name []byte ) (*Bucket , error ) {
return tx .root .CreateBucketIfNotExists (name )
}
func (tx *Tx ) DeleteBucket (name []byte ) error {
return tx .root .DeleteBucket (name )
}
func (tx *Tx ) MoveBucket (child []byte , src *Bucket , dst *Bucket ) error {
if src == nil {
src = &tx .root
}
if dst == nil {
dst = &tx .root
}
return src .MoveBucket (child , dst )
}
func (tx *Tx ) ForEach (fn func (name []byte , b *Bucket ) error ) error {
return tx .root .ForEach (func (k , v []byte ) error {
return fn (k , tx .root .Bucket (k ))
})
}
func (tx *Tx ) OnCommit (fn func ()) {
tx .commitHandlers = append (tx .commitHandlers , fn )
}
func (tx *Tx ) Commit () (err error ) {
txId := tx .ID ()
lg := tx .db .Logger ()
if lg != discardLogger {
lg .Debugf ("Committing transaction %d" , txId )
defer func () {
if err != nil {
lg .Errorf ("Committing transaction failed: %v" , err )
} else {
lg .Debugf ("Committing transaction %d successfully" , txId )
}
}()
}
common .Assert (!tx .managed , "managed tx commit not allowed" )
if tx .db == nil {
return berrors .ErrTxClosed
} else if !tx .writable {
return berrors .ErrTxNotWritable
}
var startTime = time .Now ()
tx .root .rebalance ()
if tx .stats .GetRebalance () > 0 {
tx .stats .IncRebalanceTime (time .Since (startTime ))
}
opgid := tx .meta .Pgid ()
startTime = time .Now ()
if err = tx .root .spill (); err != nil {
lg .Errorf ("spilling data onto dirty pages failed: %v" , err )
tx .rollback ()
return err
}
tx .stats .IncSpillTime (time .Since (startTime ))
tx .meta .RootBucket ().SetRootPage (tx .root .RootPage ())
if tx .meta .Freelist () != common .PgidNoFreelist {
tx .db .freelist .Free (tx .meta .Txid (), tx .db .page (tx .meta .Freelist ()))
}
if !tx .db .NoFreelistSync {
err = tx .commitFreelist ()
if err != nil {
lg .Errorf ("committing freelist failed: %v" , err )
return err
}
} else {
tx .meta .SetFreelist (common .PgidNoFreelist )
}
if tx .meta .Pgid () > opgid {
_ = errors .New ("" )
if err = tx .db .grow (int (tx .meta .Pgid ()+1 ) * tx .db .pageSize ); err != nil {
lg .Errorf ("growing db size failed, pgid: %d, pagesize: %d, error: %v" , tx .meta .Pgid (), tx .db .pageSize , err )
tx .rollback ()
return err
}
}
startTime = time .Now ()
if err = tx .write (); err != nil {
lg .Errorf ("writing data failed: %v" , err )
tx .rollback ()
return err
}
if tx .db .StrictMode {
ch := tx .Check ()
var errs []string
for {
chkErr , ok := <-ch
if !ok {
break
}
errs = append (errs , chkErr .Error())
}
if len (errs ) > 0 {
panic ("check fail: " + strings .Join (errs , "\n" ))
}
}
if err = tx .writeMeta (); err != nil {
lg .Errorf ("writeMeta failed: %v" , err )
tx .rollback ()
return err
}
tx .stats .IncWriteTime (time .Since (startTime ))
tx .close ()
for _ , fn := range tx .commitHandlers {
fn ()
}
return nil
}
func (tx *Tx ) commitFreelist () error {
p , err := tx .allocate ((tx .db .freelist .EstimatedWritePageSize () / tx .db .pageSize ) + 1 )
if err != nil {
tx .rollback ()
return err
}
tx .db .freelist .Write (p )
tx .meta .SetFreelist (p .Id ())
return nil
}
func (tx *Tx ) Rollback () error {
common .Assert (!tx .managed , "managed tx rollback not allowed" )
if tx .db == nil {
return berrors .ErrTxClosed
}
tx .nonPhysicalRollback ()
return nil
}
func (tx *Tx ) nonPhysicalRollback () {
if tx .db == nil {
return
}
if tx .writable {
tx .db .freelist .Rollback (tx .meta .Txid ())
}
tx .close ()
}
func (tx *Tx ) rollback () {
if tx .db == nil {
return
}
if tx .writable {
tx .db .freelist .Rollback (tx .meta .Txid ())
if tx .db .data != nil {
if !tx .db .hasSyncedFreelist () {
tx .db .freelist .NoSyncReload (tx .db .freepages ())
} else {
tx .db .freelist .Reload (tx .db .page (tx .db .meta ().Freelist ()))
}
}
}
tx .close ()
}
func (tx *Tx ) close () {
if tx .db == nil {
return
}
if tx .writable {
var freelistFreeN = tx .db .freelist .FreeCount ()
var freelistPendingN = tx .db .freelist .PendingCount ()
var freelistAlloc = tx .db .freelist .EstimatedWritePageSize ()
tx .db .rwtx = nil
tx .db .rwlock .Unlock ()
if tx .db .stats != nil {
tx .db .statlock .Lock ()
tx .db .stats .FreePageN = freelistFreeN
tx .db .stats .PendingPageN = freelistPendingN
tx .db .stats .FreeAlloc = (freelistFreeN + freelistPendingN ) * tx .db .pageSize
tx .db .stats .FreelistInuse = freelistAlloc
tx .db .stats .TxStats .add (&tx .stats )
tx .db .statlock .Unlock ()
}
} else {
tx .db .removeTx (tx )
}
tx .db = nil
tx .meta = nil
tx .root = Bucket {tx : tx }
tx .pages = nil
}
func (tx *Tx ) Copy (w io .Writer ) error {
_ , err := tx .WriteTo (w )
return err
}
func (tx *Tx ) WriteTo (w io .Writer ) (n int64 , err error ) {
var f *os .File
if tx .WriteFlag != 0 {
f , err = tx .db .openFile (tx .db .path , os .O_RDONLY |tx .WriteFlag , 0 )
if err != nil {
return 0 , err
}
if ok , err := sameFile (tx .db .file , f ); !ok {
lg := tx .db .Logger ()
if cerr := f .Close (); cerr != nil {
lg .Errorf ("failed to close the file (%s): %v" , tx .db .path , cerr )
}
lg .Warningf ("The underlying file has changed, so reuse the already opened file (%s): %v" , tx .db .path , err )
f = tx .db .file
} else {
defer func () {
if cerr := f .Close (); err == nil {
err = cerr
}
}()
}
} else {
f = tx .db .file
}
buf := make ([]byte , tx .db .pageSize )
page := (*common .Page )(unsafe .Pointer (&buf [0 ]))
page .SetFlags (common .MetaPageFlag )
*page .Meta () = *tx .meta
page .SetId (0 )
page .Meta ().SetChecksum (page .Meta ().Sum64 ())
nn , err := w .Write (buf )
n += int64 (nn )
if err != nil {
return n , fmt .Errorf ("meta 0 copy: %s" , err )
}
page .SetId (1 )
page .Meta ().DecTxid ()
page .Meta ().SetChecksum (page .Meta ().Sum64 ())
nn , err = w .Write (buf )
n += int64 (nn )
if err != nil {
return n , fmt .Errorf ("meta 1 copy: %s" , err )
}
dataOffset := int64 (tx .db .pageSize * 2 )
dataSize := tx .Size () - dataOffset
sr := io .NewSectionReader (f , dataOffset , dataSize )
wn , err := io .CopyN (w , sr , dataSize )
n += wn
if err != nil {
return n , err
}
return n , nil
}
func sameFile(f1 , f2 *os .File ) (bool , error ) {
fi1 , err := f1 .Stat ()
if err != nil {
return false , fmt .Errorf ("failed to get fileInfo of the first file (%s): %w" , f1 .Name (), err )
}
fi2 , err := f2 .Stat ()
if err != nil {
return false , fmt .Errorf ("failed to get fileInfo of the second file (%s): %w" , f2 .Name (), err )
}
return os .SameFile (fi1 , fi2 ), nil
}
func (tx *Tx ) CopyFile (path string , mode os .FileMode ) error {
f , err := tx .db .openFile (path , os .O_RDWR |os .O_CREATE |os .O_TRUNC , mode )
if err != nil {
return err
}
_, err = tx .WriteTo (f )
if err != nil {
_ = f .Close ()
return err
}
return f .Close ()
}
func (tx *Tx ) allocate (count int ) (*common .Page , error ) {
lg := tx .db .Logger ()
p , err := tx .db .allocate (tx .meta .Txid (), count )
if err != nil {
lg .Errorf ("allocating failed, txid: %d, count: %d, error: %v" , tx .meta .Txid (), count , err )
return nil , err
}
tx .pages [p .Id ()] = p
tx .stats .IncPageCount (int64 (count ))
tx .stats .IncPageAlloc (int64 (count * tx .db .pageSize ))
return p , nil
}
func (tx *Tx ) write () error {
lg := tx .db .Logger ()
pages := make (common .Pages , 0 , len (tx .pages ))
for _ , p := range tx .pages {
pages = append (pages , p )
}
tx .pages = make (map [common .Pgid ]*common .Page )
sort .Sort (pages )
for _ , p := range pages {
rem := (uint64 (p .Overflow ()) + 1 ) * uint64 (tx .db .pageSize )
offset := int64 (p .Id ()) * int64 (tx .db .pageSize )
var written uintptr
for {
sz := rem
if sz > common .MaxAllocSize -1 {
sz = common .MaxAllocSize - 1
}
buf := common .UnsafeByteSlice (unsafe .Pointer (p ), written , 0 , int (sz ))
if _ , err := tx .db .ops .writeAt (buf , offset ); err != nil {
lg .Errorf ("writeAt failed, offset: %d: %w" , offset , err )
return err
}
tx .stats .IncWrite (1 )
rem -= sz
if rem == 0 {
break
}
offset += int64 (sz )
written += uintptr (sz )
}
}
if !tx .db .NoSync || common .IgnoreNoSync {
if err := fdatasync (tx .db ); err != nil {
lg .Errorf ("[GOOS: %s, GOARCH: %s] fdatasync failed: %w" , runtime .GOOS , runtime .GOARCH , err )
return err
}
}
for _ , p := range pages {
if int (p .Overflow ()) != 0 {
continue
}
buf := common .UnsafeByteSlice (unsafe .Pointer (p ), 0 , 0 , tx .db .pageSize )
for i := range buf {
buf [i ] = 0
}
tx .db .pagePool .Put (buf )
}
return nil
}
func (tx *Tx ) writeMeta () error {
lg := tx .db .Logger ()
buf := make ([]byte , tx .db .pageSize )
p := tx .db .pageInBuffer (buf , 0 )
tx .meta .Write (p )
tx .db .metalock .Lock ()
if _ , err := tx .db .ops .writeAt (buf , int64 (p .Id ())*int64 (tx .db .pageSize )); err != nil {
tx .db .metalock .Unlock ()
lg .Errorf ("writeAt failed, pgid: %d, pageSize: %d, error: %v" , p .Id (), tx .db .pageSize , err )
return err
}
tx .db .metalock .Unlock ()
if !tx .db .NoSync || common .IgnoreNoSync {
if err := fdatasync (tx .db ); err != nil {
lg .Errorf ("[GOOS: %s, GOARCH: %s] fdatasync failed: %w" , runtime .GOOS , runtime .GOARCH , err )
return err
}
}
tx .stats .IncWrite (1 )
return nil
}
func (tx *Tx ) page (id common .Pgid ) *common .Page {
if tx .pages != nil {
if p , ok := tx .pages [id ]; ok {
p .FastCheck (id )
return p
}
}
p := tx .db .page (id )
p .FastCheck (id )
return p
}
func (tx *Tx ) forEachPage (pgidnum common .Pgid , fn func (*common .Page , int , []common .Pgid )) {
stack := make ([]common .Pgid , 10 )
stack [0 ] = pgidnum
tx .forEachPageInternal (stack [:1 ], fn )
}
func (tx *Tx ) forEachPageInternal (pgidstack []common .Pgid , fn func (*common .Page , int , []common .Pgid )) {
p := tx .page (pgidstack [len (pgidstack )-1 ])
fn (p , len (pgidstack )-1 , pgidstack )
if p .IsBranchPage () {
for i := 0 ; i < int (p .Count ()); i ++ {
elem := p .BranchPageElement (uint16 (i ))
tx .forEachPageInternal (append (pgidstack , elem .Pgid ()), fn )
}
}
}
func (tx *Tx ) Page (id int ) (*common .PageInfo , error ) {
if tx .db == nil {
return nil , berrors .ErrTxClosed
} else if common .Pgid (id ) >= tx .meta .Pgid () {
return nil , nil
}
if tx .db .freelist == nil {
return nil , berrors .ErrFreePagesNotLoaded
}
p := tx .db .page (common .Pgid (id ))
info := &common .PageInfo {
ID : id ,
Count : int (p .Count ()),
OverflowCount : int (p .Overflow ()),
}
if tx .db .freelist .Freed (common .Pgid (id )) {
info .Type = "free"
} else {
info .Type = p .Typ ()
}
return info , nil
}
type TxStats struct {
PageCount int64
PageAlloc int64
CursorCount int64
NodeCount int64
NodeDeref int64
Rebalance int64
RebalanceTime time .Duration
Split int64
Spill int64
SpillTime time .Duration
Write int64
WriteTime time .Duration
}
func (s *TxStats ) add (other *TxStats ) {
s .IncPageCount (other .GetPageCount ())
s .IncPageAlloc (other .GetPageAlloc ())
s .IncCursorCount (other .GetCursorCount ())
s .IncNodeCount (other .GetNodeCount ())
s .IncNodeDeref (other .GetNodeDeref ())
s .IncRebalance (other .GetRebalance ())
s .IncRebalanceTime (other .GetRebalanceTime ())
s .IncSplit (other .GetSplit ())
s .IncSpill (other .GetSpill ())
s .IncSpillTime (other .GetSpillTime ())
s .IncWrite (other .GetWrite ())
s .IncWriteTime (other .GetWriteTime ())
}
func (s *TxStats ) Sub (other *TxStats ) TxStats {
var diff TxStats
diff .PageCount = s .GetPageCount () - other .GetPageCount ()
diff .PageAlloc = s .GetPageAlloc () - other .GetPageAlloc ()
diff .CursorCount = s .GetCursorCount () - other .GetCursorCount ()
diff .NodeCount = s .GetNodeCount () - other .GetNodeCount ()
diff .NodeDeref = s .GetNodeDeref () - other .GetNodeDeref ()
diff .Rebalance = s .GetRebalance () - other .GetRebalance ()
diff .RebalanceTime = s .GetRebalanceTime () - other .GetRebalanceTime ()
diff .Split = s .GetSplit () - other .GetSplit ()
diff .Spill = s .GetSpill () - other .GetSpill ()
diff .SpillTime = s .GetSpillTime () - other .GetSpillTime ()
diff .Write = s .GetWrite () - other .GetWrite ()
diff .WriteTime = s .GetWriteTime () - other .GetWriteTime ()
return diff
}
func (s *TxStats ) GetPageCount () int64 {
return atomic .LoadInt64 (&s .PageCount )
}
func (s *TxStats ) IncPageCount (delta int64 ) int64 {
return atomic .AddInt64 (&s .PageCount , delta )
}
func (s *TxStats ) GetPageAlloc () int64 {
return atomic .LoadInt64 (&s .PageAlloc )
}
func (s *TxStats ) IncPageAlloc (delta int64 ) int64 {
return atomic .AddInt64 (&s .PageAlloc , delta )
}
func (s *TxStats ) GetCursorCount () int64 {
return atomic .LoadInt64 (&s .CursorCount )
}
func (s *TxStats ) IncCursorCount (delta int64 ) int64 {
return atomic .AddInt64 (&s .CursorCount , delta )
}
func (s *TxStats ) GetNodeCount () int64 {
return atomic .LoadInt64 (&s .NodeCount )
}
func (s *TxStats ) IncNodeCount (delta int64 ) int64 {
return atomic .AddInt64 (&s .NodeCount , delta )
}
func (s *TxStats ) GetNodeDeref () int64 {
return atomic .LoadInt64 (&s .NodeDeref )
}
func (s *TxStats ) IncNodeDeref (delta int64 ) int64 {
return atomic .AddInt64 (&s .NodeDeref , delta )
}
func (s *TxStats ) GetRebalance () int64 {
return atomic .LoadInt64 (&s .Rebalance )
}
func (s *TxStats ) IncRebalance (delta int64 ) int64 {
return atomic .AddInt64 (&s .Rebalance , delta )
}
func (s *TxStats ) GetRebalanceTime () time .Duration {
return atomicLoadDuration (&s .RebalanceTime )
}
func (s *TxStats ) IncRebalanceTime (delta time .Duration ) time .Duration {
return atomicAddDuration (&s .RebalanceTime , delta )
}
func (s *TxStats ) GetSplit () int64 {
return atomic .LoadInt64 (&s .Split )
}
func (s *TxStats ) IncSplit (delta int64 ) int64 {
return atomic .AddInt64 (&s .Split , delta )
}
func (s *TxStats ) GetSpill () int64 {
return atomic .LoadInt64 (&s .Spill )
}
func (s *TxStats ) IncSpill (delta int64 ) int64 {
return atomic .AddInt64 (&s .Spill , delta )
}
func (s *TxStats ) GetSpillTime () time .Duration {
return atomicLoadDuration (&s .SpillTime )
}
func (s *TxStats ) IncSpillTime (delta time .Duration ) time .Duration {
return atomicAddDuration (&s .SpillTime , delta )
}
func (s *TxStats ) GetWrite () int64 {
return atomic .LoadInt64 (&s .Write )
}
func (s *TxStats ) IncWrite (delta int64 ) int64 {
return atomic .AddInt64 (&s .Write , delta )
}
func (s *TxStats ) GetWriteTime () time .Duration {
return atomicLoadDuration (&s .WriteTime )
}
func (s *TxStats ) IncWriteTime (delta time .Duration ) time .Duration {
return atomicAddDuration (&s .WriteTime , delta )
}
func atomicAddDuration(ptr *time .Duration , du time .Duration ) time .Duration {
return time .Duration (atomic .AddInt64 ((*int64 )(unsafe .Pointer (ptr )), int64 (du )))
}
func atomicLoadDuration(ptr *time .Duration ) time .Duration {
return time .Duration (atomic .LoadInt64 ((*int64 )(unsafe .Pointer (ptr ))))
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .