Giter VIP home page Giter VIP logo

bbolt's Introduction

bbolt

Go Report Card Go Reference Releases LICENSE

bbolt is a fork of Ben Johnson's Bolt key/value store. The purpose of this fork is to provide the Go community with an active maintenance and development target for Bolt; the goal is improved reliability and stability. bbolt includes bug fixes, performance enhancements, and features not found in Bolt while preserving backwards compatibility with the Bolt API.

Bolt is a pure Go key/value store inspired by Howard Chu's LMDB project. The goal of the project is to provide a simple, fast, and reliable database for projects that don't require a full database server such as Postgres or MySQL.

Since Bolt is meant to be used as such a low-level piece of functionality, simplicity is key. The API will be small and only focus on getting values and setting values. That's it.

Project Status

Bolt is stable, the API is fixed, and the file format is fixed. Full unit test coverage and randomized black box testing are used to ensure database consistency and thread safety. Bolt is currently used in high-load production environments serving databases as large as 1TB. Many companies such as Shopify and Heroku use Bolt-backed services every day.

Project versioning

bbolt uses semantic versioning. API should not change between patch and minor releases. New minor versions may add additional features to the API.

Table of Contents

Getting Started

Installing

To start using Bolt, install Go and run go get:

$ go get go.etcd.io/bbolt@latest

This will retrieve the library and update your go.mod and go.sum files.

To run the command line utility, execute:

$ go run go.etcd.io/bbolt/cmd/bbolt@latest

Run go install to install the bbolt command line utility into your $GOBIN path, which defaults to $GOPATH/bin or $HOME/go/bin if the GOPATH environment variable is not set.

$ go install go.etcd.io/bbolt/cmd/bbolt@latest

Importing bbolt

To use bbolt as an embedded key-value store, import as:

import bolt "go.etcd.io/bbolt"

db, err := bolt.Open(path, 0600, nil)
if err != nil {
  return err
}
defer db.Close()

Opening a database

The top-level object in Bolt is a DB. It is represented as a single file on your disk and represents a consistent snapshot of your data.

To open your database, simply use the bolt.Open() function:

package main

import (
	"log"

	bolt "go.etcd.io/bbolt"
)

func main() {
	// Open the my.db data file in your current directory.
	// It will be created if it doesn't exist.
	db, err := bolt.Open("my.db", 0600, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	...
}

Please note that Bolt obtains a file lock on the data file so multiple processes cannot open the same database at the same time. Opening an already open Bolt database will cause it to hang until the other process closes it. To prevent an indefinite wait you can pass a timeout option to the Open() function:

db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second})

Transactions

Bolt allows only one read-write transaction at a time but allows as many read-only transactions as you want at a time. Each transaction has a consistent view of the data as it existed when the transaction started.

Individual transactions and all objects created from them (e.g. buckets, keys) are not thread safe. To work with data in multiple goroutines you must start a transaction for each one or use locking to ensure only one goroutine accesses a transaction at a time. Creating transaction from the DB is thread safe.

Transactions should not depend on one another and generally shouldn't be opened simultaneously in the same goroutine. This can cause a deadlock as the read-write transaction needs to periodically re-map the data file but it cannot do so while any read-only transaction is open. Even a nested read-only transaction can cause a deadlock, as the child transaction can block the parent transaction from releasing its resources.

Read-write transactions

To start a read-write transaction, you can use the DB.Update() function:

err := db.Update(func(tx *bolt.Tx) error {
	...
	return nil
})

Inside the closure, you have a consistent view of the database. You commit the transaction by returning nil at the end. You can also rollback the transaction at any point by returning an error. All database operations are allowed inside a read-write transaction.

Always check the return error as it will report any disk failures that can cause your transaction to not complete. If you return an error within your closure it will be passed through.

Read-only transactions

To start a read-only transaction, you can use the DB.View() function:

err := db.View(func(tx *bolt.Tx) error {
	...
	return nil
})

You also get a consistent view of the database within this closure, however, no mutating operations are allowed within a read-only transaction. You can only retrieve buckets, retrieve values, and copy the database within a read-only transaction.

Batch read-write transactions

Each DB.Update() waits for disk to commit the writes. This overhead can be minimized by combining multiple updates with the DB.Batch() function:

err := db.Batch(func(tx *bolt.Tx) error {
	...
	return nil
})

Concurrent Batch calls are opportunistically combined into larger transactions. Batch is only useful when there are multiple goroutines calling it.

The trade-off is that Batch can call the given function multiple times, if parts of the transaction fail. The function must be idempotent and side effects must take effect only after a successful return from DB.Batch().

For example: don't display messages from inside the function, instead set variables in the enclosing scope:

var id uint64
err := db.Batch(func(tx *bolt.Tx) error {
	// Find last key in bucket, decode as bigendian uint64, increment
	// by one, encode back to []byte, and add new key.
	...
	id = newValue
	return nil
})
if err != nil {
	return ...
}
fmt.Println("Allocated ID %d", id)

Managing transactions manually

The DB.View() and DB.Update() functions are wrappers around the DB.Begin() function. These helper functions will start the transaction, execute a function, and then safely close your transaction if an error is returned. This is the recommended way to use Bolt transactions.

However, sometimes you may want to manually start and end your transactions. You can use the DB.Begin() function directly but please be sure to close the transaction.

// Start a writable transaction.
tx, err := db.Begin(true)
if err != nil {
    return err
}
defer tx.Rollback()

// Use the transaction...
_, err := tx.CreateBucket([]byte("MyBucket"))
if err != nil {
    return err
}

// Commit the transaction and check for error.
if err := tx.Commit(); err != nil {
    return err
}

The first argument to DB.Begin() is a boolean stating if the transaction should be writable.

Using buckets

Buckets are collections of key/value pairs within the database. All keys in a bucket must be unique. You can create a bucket using the Tx.CreateBucket() function:

db.Update(func(tx *bolt.Tx) error {
	b, err := tx.CreateBucket([]byte("MyBucket"))
	if err != nil {
		return fmt.Errorf("create bucket: %s", err)
	}
	return nil
})

You can retrieve an existing bucket using the Tx.Bucket() function:

db.Update(func(tx *bolt.Tx) error {
	b := tx.Bucket([]byte("MyBucket"))
	if b == nil {
		return errors.New("bucket does not exist")
	}
	return nil
})

You can also create a bucket only if it doesn't exist by using the Tx.CreateBucketIfNotExists() function. It's a common pattern to call this function for all your top-level buckets after you open your database so you can guarantee that they exist for future transactions.

To delete a bucket, simply call the Tx.DeleteBucket() function.

Using key/value pairs

To save a key/value pair to a bucket, use the Bucket.Put() function:

db.Update(func(tx *bolt.Tx) error {
	b := tx.Bucket([]byte("MyBucket"))
	err := b.Put([]byte("answer"), []byte("42"))
	return err
})

This will set the value of the "answer" key to "42" in the MyBucket bucket. To retrieve this value, we can use the Bucket.Get() function:

db.View(func(tx *bolt.Tx) error {
	b := tx.Bucket([]byte("MyBucket"))
	v := b.Get([]byte("answer"))
	fmt.Printf("The answer is: %s\n", v)
	return nil
})

The Get() function does not return an error because its operation is guaranteed to work (unless there is some kind of system failure). If the key exists then it will return its byte slice value. If it doesn't exist then it will return nil. It's important to note that you can have a zero-length value set to a key which is different than the key not existing.

Use the Bucket.Delete() function to delete a key from the bucket:

db.Update(func (tx *bolt.Tx) error {
    b := tx.Bucket([]byte("MyBucket"))
    err := b.Delete([]byte("answer"))
    return err
})

This will delete the key answers from the bucket MyBucket.

Please note that values returned from Get() are only valid while the transaction is open. If you need to use a value outside of the transaction then you must use copy() to copy it to another byte slice.

Autoincrementing integer for the bucket

By using the NextSequence() function, you can let Bolt determine a sequence which can be used as the unique identifier for your key/value pairs. See the example below.

// CreateUser saves u to the store. The new user ID is set on u once the data is persisted.
func (s *Store) CreateUser(u *User) error {
    return s.db.Update(func(tx *bolt.Tx) error {
        // Retrieve the users bucket.
        // This should be created when the DB is first opened.
        b := tx.Bucket([]byte("users"))

        // Generate ID for the user.
        // This returns an error only if the Tx is closed or not writeable.
        // That can't happen in an Update() call so I ignore the error check.
        id, _ := b.NextSequence()
        u.ID = int(id)

        // Marshal user data into bytes.
        buf, err := json.Marshal(u)
        if err != nil {
            return err
        }

        // Persist bytes to users bucket.
        return b.Put(itob(u.ID), buf)
    })
}

// itob returns an 8-byte big endian representation of v.
func itob(v int) []byte {
    b := make([]byte, 8)
    binary.BigEndian.PutUint64(b, uint64(v))
    return b
}

type User struct {
    ID int
    ...
}

Iterating over keys

Bolt stores its keys in byte-sorted order within a bucket. This makes sequential iteration over these keys extremely fast. To iterate over keys we'll use a Cursor:

db.View(func(tx *bolt.Tx) error {
	// Assume bucket exists and has keys
	b := tx.Bucket([]byte("MyBucket"))

	c := b.Cursor()

	for k, v := c.First(); k != nil; k, v = c.Next() {
		fmt.Printf("key=%s, value=%s\n", k, v)
	}

	return nil
})

The cursor allows you to move to a specific point in the list of keys and move forward or backward through the keys one at a time.

The following functions are available on the cursor:

First()  Move to the first key.
Last()   Move to the last key.
Seek()   Move to a specific key.
Next()   Move to the next key.
Prev()   Move to the previous key.

Each of those functions has a return signature of (key []byte, value []byte). You must seek to a position using First(), Last(), or Seek() before calling Next() or Prev(). If you do not seek to a position then these functions will return a nil key.

When you have iterated to the end of the cursor, then Next() will return a nil key and the cursor still points to the last element if present. When you have iterated to the beginning of the cursor, then Prev() will return a nil key and the cursor still points to the first element if present.

If you remove key/value pairs during iteration, the cursor may automatically move to the next position if present in current node each time removing a key. When you call c.Next() after removing a key, it may skip one key/value pair.
Refer to pull/611 to get more detailed info.

During iteration, if the key is non-nil but the value is nil, that means the key refers to a bucket rather than a value. Use Bucket.Bucket() to access the sub-bucket.

Prefix scans

To iterate over a key prefix, you can combine Seek() and bytes.HasPrefix():

db.View(func(tx *bolt.Tx) error {
	// Assume bucket exists and has keys
	c := tx.Bucket([]byte("MyBucket")).Cursor()

	prefix := []byte("1234")
	for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {
		fmt.Printf("key=%s, value=%s\n", k, v)
	}

	return nil
})

Range scans

Another common use case is scanning over a range such as a time range. If you use a sortable time encoding such as RFC3339 then you can query a specific date range like this:

db.View(func(tx *bolt.Tx) error {
	// Assume our events bucket exists and has RFC3339 encoded time keys.
	c := tx.Bucket([]byte("Events")).Cursor()

	// Our time range spans the 90's decade.
	min := []byte("1990-01-01T00:00:00Z")
	max := []byte("2000-01-01T00:00:00Z")

	// Iterate over the 90's.
	for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() {
		fmt.Printf("%s: %s\n", k, v)
	}

	return nil
})

Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable.

ForEach()

You can also use the function ForEach() if you know you'll be iterating over all the keys in a bucket:

db.View(func(tx *bolt.Tx) error {
	// Assume bucket exists and has keys
	b := tx.Bucket([]byte("MyBucket"))

	b.ForEach(func(k, v []byte) error {
		fmt.Printf("key=%s, value=%s\n", k, v)
		return nil
	})
	return nil
})

Please note that keys and values in ForEach() are only valid while the transaction is open. If you need to use a key or value outside of the transaction, you must use copy() to copy it to another byte slice.

Nested buckets

You can also store a bucket in a key to create nested buckets. The API is the same as the bucket management API on the DB object:

func (*Bucket) CreateBucket(key []byte) (*Bucket, error)
func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error)
func (*Bucket) DeleteBucket(key []byte) error

Say you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings.

// createUser creates a new user in the given account.
func createUser(accountID int, u *User) error {
    // Start the transaction.
    tx, err := db.Begin(true)
    if err != nil {
        return err
    }
    defer tx.Rollback()

    // Retrieve the root bucket for the account.
    // Assume this has already been created when the account was set up.
    root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10)))

    // Setup the users bucket.
    bkt, err := root.CreateBucketIfNotExists([]byte("USERS"))
    if err != nil {
        return err
    }

    // Generate an ID for the new user.
    userID, err := bkt.NextSequence()
    if err != nil {
        return err
    }
    u.ID = userID

    // Marshal and save the encoded user.
    if buf, err := json.Marshal(u); err != nil {
        return err
    } else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil {
        return err
    }

    // Commit the transaction.
    if err := tx.Commit(); err != nil {
        return err
    }

    return nil
}

Database backups

Bolt is a single file so it's easy to backup. You can use the Tx.WriteTo() function to write a consistent view of the database to a writer. If you call this from a read-only transaction, it will perform a hot backup and not block your other database reads and writes.

By default, it will use a regular file handle which will utilize the operating system's page cache. See the Tx documentation for information about optimizing for larger-than-RAM datasets.

One common use case is to backup over HTTP so you can use tools like cURL to do database backups:

func BackupHandleFunc(w http.ResponseWriter, req *http.Request) {
	err := db.View(func(tx *bolt.Tx) error {
		w.Header().Set("Content-Type", "application/octet-stream")
		w.Header().Set("Content-Disposition", `attachment; filename="my.db"`)
		w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size())))
		_, err := tx.WriteTo(w)
		return err
	})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

Then you can backup using this command:

$ curl http://localhost/backup > my.db

Or you can open your browser to http://localhost/backup and it will download automatically.

If you want to backup to another file you can use the Tx.CopyFile() helper function.

Statistics

The database keeps a running count of many of the internal operations it performs so you can better understand what's going on. By grabbing a snapshot of these stats at two points in time we can see what operations were performed in that time range.

For example, we could start a goroutine to log stats every 10 seconds:

go func() {
	// Grab the initial stats.
	prev := db.Stats()

	for {
		// Wait for 10s.
		time.Sleep(10 * time.Second)

		// Grab the current stats and diff them.
		stats := db.Stats()
		diff := stats.Sub(&prev)

		// Encode stats to JSON and print to STDERR.
		json.NewEncoder(os.Stderr).Encode(diff)

		// Save stats for the next loop.
		prev = stats
	}
}()

It's also useful to pipe these stats to a service such as statsd for monitoring or to provide an HTTP endpoint that will perform a fixed-length sample.

Read-Only Mode

Sometimes it is useful to create a shared, read-only Bolt database. To this, set the Options.ReadOnly flag when opening your database. Read-only mode uses a shared lock to allow multiple processes to read from the database but it will block any processes from opening the database in read-write mode.

db, err := bolt.Open("my.db", 0600, &bolt.Options{ReadOnly: true})
if err != nil {
	log.Fatal(err)
}

Mobile Use (iOS/Android)

Bolt is able to run on mobile devices by leveraging the binding feature of the gomobile tool. Create a struct that will contain your database logic and a reference to a *bolt.DB with a initializing constructor that takes in a filepath where the database file will be stored. Neither Android nor iOS require extra permissions or cleanup from using this method.

func NewBoltDB(filepath string) *BoltDB {
	db, err := bolt.Open(filepath+"/demo.db", 0600, nil)
	if err != nil {
		log.Fatal(err)
	}

	return &BoltDB{db}
}

type BoltDB struct {
	db *bolt.DB
	...
}

func (b *BoltDB) Path() string {
	return b.db.Path()
}

func (b *BoltDB) Close() {
	b.db.Close()
}

Database logic should be defined as methods on this wrapper struct.

To initialize this struct from the native language (both platforms now sync their local storage to the cloud. These snippets disable that functionality for the database file):

Android

String path;
if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){
    path = getNoBackupFilesDir().getAbsolutePath();
} else{
    path = getFilesDir().getAbsolutePath();
}
Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path)

iOS

- (void)demo {
    NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
                                                          NSUserDomainMask,
                                                          YES) objectAtIndex:0];
	GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path);
	[self addSkipBackupAttributeToItemAtPath:demo.path];
	//Some DB Logic would go here
	[demo close];
}

- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
{
    NSURL* URL= [NSURL fileURLWithPath: filePathString];
    assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);

    NSError *error = nil;
    BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
                                  forKey: NSURLIsExcludedFromBackupKey error: &error];
    if(!success){
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
    }
    return success;
}

Resources

For more information on getting started with Bolt, check out the following articles:

Comparison with other databases

Postgres, MySQL, & other relational databases

Relational databases structure data into rows and are only accessible through the use of SQL. This approach provides flexibility in how you store and query your data but also incurs overhead in parsing and planning SQL statements. Bolt accesses all data by a byte slice key. This makes Bolt fast to read and write data by key but provides no built-in support for joining values together.

Most relational databases (with the exception of SQLite) are standalone servers that run separately from your application. This gives your systems flexibility to connect multiple application servers to a single database server but also adds overhead in serializing and transporting data over the network. Bolt runs as a library included in your application so all data access has to go through your application's process. This brings data closer to your application but limits multi-process access to the data.

LevelDB, RocksDB

LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that they are libraries bundled into the application, however, their underlying structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes random writes by using a write ahead log and multi-tiered, sorted files called SSTables. Bolt uses a B+tree internally and only a single file. Both approaches have trade-offs.

If you require a high random write throughput (>10,000 w/sec) or you need to use spinning disks then LevelDB could be a good choice. If your application is read-heavy or does a lot of range scans then Bolt could be a good choice.

One other important consideration is that LevelDB does not have transactions. It supports batch writing of key/values pairs and it supports read snapshots but it will not give you the ability to do a compare-and-swap operation safely. Bolt supports fully serializable ACID transactions.

LMDB

Bolt was originally a port of LMDB so it is architecturally similar. Both use a B+tree, have ACID semantics with fully serializable transactions, and support lock-free MVCC using a single writer and multiple readers.

The two projects have somewhat diverged. LMDB heavily focuses on raw performance while Bolt has focused on simplicity and ease of use. For example, LMDB allows several unsafe actions such as direct writes for the sake of performance. Bolt opts to disallow actions which can leave the database in a corrupted state. The only exception to this in Bolt is DB.NoSync.

There are also a few differences in API. LMDB requires a maximum mmap size when opening an mdb_env whereas Bolt will handle incremental mmap resizing automatically. LMDB overloads the getter and setter functions with multiple flags whereas Bolt splits these specialized cases into their own functions.

Caveats & Limitations

It's important to pick the right tool for the job and Bolt is no exception. Here are a few things to note when evaluating and using Bolt:

  • Bolt is good for read intensive workloads. Sequential write performance is also fast but random writes can be slow. You can use DB.Batch() or add a write-ahead log to help mitigate this issue.

  • Bolt uses a B+tree internally so there can be a lot of random page access. SSDs provide a significant performance boost over spinning disks.

  • Try to avoid long running read transactions. Bolt uses copy-on-write so old pages cannot be reclaimed while an old transaction is using them.

  • Byte slices returned from Bolt are only valid during a transaction. Once the transaction has been committed or rolled back then the memory they point to can be reused by a new page or can be unmapped from virtual memory and you'll see an unexpected fault address panic when accessing it.

  • Bolt uses an exclusive write lock on the database file so it cannot be shared by multiple processes.

  • Be careful when using Bucket.FillPercent. Setting a high fill percent for buckets that have random inserts will cause your database to have very poor page utilization.

  • Use larger buckets in general. Smaller buckets causes poor page utilization once they become larger than the page size (typically 4KB).

  • Bulk loading a lot of random writes into a new bucket can be slow as the page will not split until the transaction is committed. Randomly inserting more than 100,000 key/value pairs into a single new bucket in a single transaction is not advised.

  • Bolt uses a memory-mapped file so the underlying operating system handles the caching of the data. Typically, the OS will cache as much of the file as it can in memory and will release memory as needed to other processes. This means that Bolt can show very high memory usage when working with large databases. However, this is expected and the OS will release memory as needed. Bolt can handle databases much larger than the available physical RAM, provided its memory-map fits in the process virtual address space. It may be problematic on 32-bits systems.

  • The data structures in the Bolt database are memory mapped so the data file will be endian specific. This means that you cannot copy a Bolt file from a little endian machine to a big endian machine and have it work. For most users this is not a concern since most modern CPUs are little endian.

  • Because of the way pages are laid out on disk, Bolt cannot truncate data files and return free pages back to the disk. Instead, Bolt maintains a free list of unused pages within its data file. These free pages can be reused by later transactions. This works well for many use cases as databases generally tend to grow. However, it's important to note that deleting large chunks of data will not allow you to reclaim that space on disk.

  • Removing key/values pairs in a bucket during iteration on the bucket using cursor may not work properly. Each time when removing a key/value pair, the cursor may automatically move to the next position if present. When users call c.Next() after removing a key, it may skip one key/value pair. Refer to #611 for more detailed info.

    For more information on page allocation, see this comment.

Reading the Source

Bolt is a relatively small code base (<5KLOC) for an embedded, serializable, transactional key/value database so it can be a good starting point for people interested in how databases work.

The best places to start are the main entry points into Bolt:

  • Open() - Initializes the reference to the database. It's responsible for creating the database if it doesn't exist, obtaining an exclusive lock on the file, reading the meta pages, & memory-mapping the file.

  • DB.Begin() - Starts a read-only or read-write transaction depending on the value of the writable argument. This requires briefly obtaining the "meta" lock to keep track of open transactions. Only one read-write transaction can exist at a time so the "rwlock" is acquired during the life of a read-write transaction.

  • Bucket.Put() - Writes a key/value pair into a bucket. After validating the arguments, a cursor is used to traverse the B+tree to the page and position where the key & value will be written. Once the position is found, the bucket materializes the underlying page and the page's parent pages into memory as "nodes". These nodes are where mutations occur during read-write transactions. These changes get flushed to disk during commit.

  • Bucket.Get() - Retrieves a key/value pair from a bucket. This uses a cursor to move to the page & position of a key/value pair. During a read-only transaction, the key and value data is returned as a direct reference to the underlying mmap file so there's no allocation overhead. For read-write transactions, this data may reference the mmap file or one of the in-memory node values.

  • Cursor - This object is simply for traversing the B+tree of on-disk pages or in-memory nodes. It can seek to a specific key, move to the first or last value, or it can move forward or backward. The cursor handles the movement up and down the B+tree transparently to the end user.

  • Tx.Commit() - Converts the in-memory dirty nodes and the list of free pages into pages to be written to disk. Writing to disk then occurs in two phases. First, the dirty pages are written to disk and an fsync() occurs. Second, a new meta page with an incremented transaction ID is written and another fsync() occurs. This two phase write ensures that partially written data pages are ignored in the event of a crash since the meta page pointing to them is never written. Partially written meta pages are invalidated because they are written with a checksum.

If you have additional notes that could be helpful for others, please submit them via pull request.

Known Issues

Other Projects Using Bolt

Below is a list of public, open source projects that use Bolt:

  • Algernon - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend.
  • Bazil - A file system that lets your data reside where it is most convenient for it to reside.
  • bolter - Command-line app for viewing BoltDB file in your terminal.
  • boltcli - the redis-cli for boltdb with Lua script support.
  • BoltHold - An embeddable NoSQL store for Go types built on BoltDB
  • BoltStore - Session store using Bolt.
  • Boltdb Boilerplate - Boilerplate wrapper around bolt aiming to make simple calls one-liners.
  • BoltDbWeb - A web based GUI for BoltDB files.
  • BoltDB Viewer - A BoltDB Viewer Can run on Windowsใ€Linuxใ€Android system.
  • bleve - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend.
  • bstore - Database library storing Go values, with referential/unique/nonzero constraints, indices, automatic schema management with struct tags, and a query API.
  • btcwallet - A bitcoin wallet.
  • buckets - a bolt wrapper streamlining simple tx and key scans.
  • Buildkit - concurrent, cache-efficient, and Dockerfile-agnostic builder toolkit
  • cayley - Cayley is an open-source graph database using Bolt as optional backend.
  • ChainStore - Simple key-value interface to a variety of storage engines organized as a chain of operations.
  • ๐ŸŒฐ Chestnut - Chestnut is encrypted storage for Go.
  • Consul - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware.
  • Containerd - An open and reliable container runtime
  • DVID - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb.
  • dcrwallet - A wallet for the Decred cryptocurrency.
  • drive - drive is an unofficial Google Drive command line client for *NIX operating systems.
  • event-shuttle - A Unix system service to collect and reliably deliver messages to Kafka.
  • Freehold - An open, secure, and lightweight platform for your files and data.
  • Go Report Card - Go code quality report cards as a (free and open source) service.
  • GoWebApp - A basic MVC web application in Go using BoltDB.
  • GoShort - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter.
  • gopherpit - A web service to manage Go remote import paths with custom domains
  • gokv - Simple key-value store abstraction and implementations for Go (Redis, Consul, etcd, bbolt, BadgerDB, LevelDB, Memcached, DynamoDB, S3, PostgreSQL, MongoDB, CockroachDB and many more)
  • Gitchain - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin".
  • InfluxDB - Scalable datastore for metrics, events, and real-time analytics.
  • ipLocator - A fast ip-geo-location-server using bolt with bloom filters.
  • ipxed - Web interface and api for ipxed.
  • Ironsmith - A simple, script-driven continuous integration (build - > test -> release) tool, with no external dependencies
  • Kala - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs.
  • Key Value Access Language (KVAL) - A proposed grammar for key-value datastores offering a bbolt binding.
  • LedisDB - A high performance NoSQL, using Bolt as optional storage.
  • lru - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores.
  • mbuckets - A Bolt wrapper that allows easy operations on multi level (nested) buckets.
  • MetricBase - Single-binary version of Graphite.
  • MuLiFS - Music Library Filesystem creates a filesystem to organise your music files.
  • NATS - NATS Streaming uses bbolt for message and metadata storage.
  • Portainer - A lightweight service delivery platform for containerized applications that can be used to manage Docker, Swarm, Kubernetes and ACI environments.
  • Prometheus Annotation Server - Annotation server for PromDash & Prometheus service monitoring system.
  • Rain - BitTorrent client and library.
  • reef-pi - reef-pi is an award winning, modular, DIY reef tank controller using easy to learn electronics based on a Raspberry Pi.
  • Request Baskets - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to RequestBin service
  • Seaweed File System - Highly scalable distributed key~file system with O(1) disk read.
  • stow - a persistence manager for objects backed by boltdb.
  • Storm - Simple and powerful ORM for BoltDB.
  • SimpleBolt - A simple way to use BoltDB. Deals mainly with strings.
  • Skybox Analytics - A standalone funnel analysis tool for web analytics.
  • Scuttlebutt - Uses Bolt to store and process all Twitter mentions of GitHub projects.
  • tentacool - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server.
  • torrent - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development.
  • Wiki - A tiny wiki using Goji, BoltDB and Blackfriday.

If you are using Bolt in a project please send a pull request to add it to the list.

bbolt's People

Contributors

ahrtr avatar asdine avatar benbjohnson avatar caojiamingalan avatar cenkalti avatar dependabot[bot] avatar elbehery avatar fuweid avatar gyuho avatar henrybear327 avatar ishan16696 avatar ivanvc avatar jmhbnz avatar josharian avatar jpbetz avatar jrick avatar lorneli avatar mkobetic avatar mrueg avatar pmezard avatar ptabor avatar rhcarvalho avatar serathius avatar snormore avatar tjungblu avatar trevorsstone avatar tv42 avatar wizard-cxy avatar wpedrak avatar xiang90 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bbolt's Issues

can't build with go get

am i doing something wrong here?

$ go get github.com/coreos/bbolt
$ echo $?
0
$ bolt
bolt: command not found

i go into the $GOPATH/src/github.com/coreos/bbolt directory, and i can't go build (does nothing, but returns 0). make returns an error (make: *** No rule to make target 'build', needed by 'default'. Stop.)

Secondary Indexes

It would be very helpful if it was possible to use secondary indexes in bolt.

This is a sample implementation. But having it built-in, makes things easier and cleaner.

(Usage Example)

Maybe a misleading comment in tx:init method

https://github.com/coreos/bbolt/blob/b44cfbde695bad1a19cc09cf00ffb217ce98f038/tx.go#L48-L50

this is a piece of code in tx.go init method, and init will be called in both beginTx and beginRWTx

as db never has two RWTx run concurrently, so actually copy cost can be saving in RWTx

tx.go init method can it be updated to save this cost ? for example

func (tx *Tx) init(db *DB) {
        ...
    	if tx.writable {
		tx.meta = db.meta()
	} else {
                db.meta().copy(tx.meta)
        }
        ...
}

and the comment about Copy the meta page since it can be changed by the writer, makes me thought of there can be more than one writer at the same time ......

Rollback when freelist == pgidNoFreelist causes panic (index out of range)

I am getting an error using bbolt, where meta has a valid page number, but sometimes, has the sentinal value 0xFFFFFFFFFFFFFFFF. Sample debugging output:

bolt: db: meta: meta0: *bolt.meta,&{3977042669 2 4096 0 {3 0} 4 5 10 8200348871670262819}, meta1: *bolt.meta,&{3977042669 2 4096 0 {3 0} 2 5 11 110609177022752452}, db.meta0.txid: bolt.txid,10, db.meta1.txid: bolt.txid,11

bolt: db: meta: meta0: *bolt.meta,&{3977042669 2 4096 0 {4 0} 18446744073709551615 5 12 15793416151478272846}, meta1: *bolt.meta,&{3977042669 2 4096 0 {3 0} 2 5 11 110609177022752452}, db.meta0.txid: bolt.txid,12, db.meta1.txid: bolt.txid,11

end-case logic needs to be added, in case the freelist pageid is the sentinal value.

Curious about rosdmap

The fork has been announced on Reddit.

Are you at a point where you can put any meat on the bones for where bbolt is heading ?

Am excited about this as I use boltdb for almost all projects

Close only waits for write transactions to finish

Hi,

This is a followup on: #80

I have been testing with closing BoltDB and ran into panic's in view transactions after calling Close(). After looking at the Close() code I think I can conclude that it waits for write transactions to finish by locking on db.rwlock but it does not wait for read transactions.

The only read lock a view transaction keeps open is the db.mmaplock, but the Close() function also only requires a read lock on that. So it does not wait for them. Am I correct in this conclusion?

If true, I think the documentation should be amended to reflect that it does not wait for read transactions, or the Close() function should acquire a full lock on db.mmaplock so that it also waits for read transactions. That said, I am not familiar enough with BoltDB's code to know what other consequences that might have.

I'm willing to submit a PR if you tell me which option you prefer :)

Add log in error handling path

Current implementation ignores whether error handling succeeds or not. If error handling itself fails, maybe record this failure to log. Otherwise, it's hard to detect it.

For example, in DB.Update function, t.Rollback may fail. https://github.com/coreos/bbolt/blob/master/db.go#L651-L657

// If an error is returned from the function then rollback and return error.
err = fn(t)
t.managed = false
if err != nil {
       // Write rollback failure to log?
	_ = t.Rollback()
	return err
}

blob: can bolt support read/write blob data

Current data access API assume all data is in memory
func (b *Bucket) Put(key []byte, value []byte) error
func (b *Bucket) Get(key []byte) []byte

Compare with other embeded db (like sqlite, berkerlydb),
read/write blob( maybe larger than 4GB) is a common demand.
I hope bolt can add APIs to open blob tx.

rework file locking

has a bunch of time.Sleep retry logic; should be closer to etcd's locking

Such keys, much RAM!

Good morning!

Why this code allocates so much memory?
(Insert 10M records with keys "10000000"..."1999999" and empty values โ†’ย 2G+ allocated RAM, output below in gist.)

I decided to migrate 10M+ rows table from MySQL to BoltDB using UUID for keys. But when I tried, I ran out of memory, because process allocated 26G+ RAM during migration.

Then I found that it's about key length: 4 bytes are fine, but 8 bytes and more cause pain. Maybe, hashing, caching, paging, duplication in memory, I don't really know how it works.

Is this normal behaviour for Bolt (and other similar storages)? Can it be tuned? Or, maybe, it's not the way I should use Bolt?

macOS 10.13.4, go version go1.10.2 darwin/amd64

more aggressive free page reclamation

Free page reclamation uses the alloc txid to reason about when to free a page. If no alloc txn id is known, it falls back to deallocating based on a tx watermark, freeing when all outstanding txs are closed (e.g., waiting until some laggy snapshot completes).

The fallback code is here:
https://github.com/coreos/bbolt/blob/12923fe56c105bca6efbbcc258cd762b4258333d/freelist.go#L132-L138

Ideally there'd always be a txid associated with the page being freed. Right now the code is doing some allocations that aren't being tracked.

TestSimulateNoFreeListSync_1op_1p fails

=== RUN   TestSimulateNoFreeListSync_1op_1p


consistency check failed (1 errors)
page 2: unreachable unfreed

db saved to:
/tmp/bolt-474295987


FAIL	github.com/coreos/bbolt	66.403s

Give proper credit to Ben Johnson

Hello folks,

Can we please be more kind to Ben Johnson on the front page of the project? I've been playing with BoltDB and every time I pass through this text I feel bad about it. The relationship with the person that created the project and in fact did a great job doing so, gifting us with good code, good license, good APIs, should really be one of gratitude, but the very first paragraph of the page reads as if we're blaming Ben for not actively changing the project anymore. We're all in that same boat, and it just rubs the wrong way.

Here is a seed idea, but feel free to tune obviously:

"This is a continuation of Ben Jonhsons' great work on the design and implementation of the original BoltDB package. As the project stabilized, Ben stopped investing as much time on it and we'd like to continue the development preserving the original principles and APIs but improving on some areas such as performance, reliability, and bug fixes when required."

By the same token, thank you very much for pushing this project forward in those terms and spending your own time on it, openly. I'll most likely be using this on real projects at some point.

tx.Check() crashes in read-only database

When the database db is opened in read-only mode (options = bolt.Options{ReadOnly: true}),
and the transaction tx is created in read-only mode (tx, ... = db.Begin(false))

Then calls to tx.Check() will systematically crash the process (stack traces at bottom of this message).
It seems the freelist management code is not entirely aware of limitations of the read-only mode - more particularly nil instances.


panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x8 pc=0x10c21c2]

goroutine 18 [running]:
github.com/coreos/bbolt.(*freelist).free_count(...)
xxx/src/github.com/coreos/bbolt/freelist.go:52
github.com/coreos/bbolt.(*freelist).count(0x0, 0x0)
xxx/src/github.com/coreos/bbolt/freelist.go:47 +0x22
github.com/coreos/bbolt.(*Tx).check(0xc4200ca000, 0xc4200ce000)
xxx/src/github.com/coreos/bbolt/tx.go:396 +0xdb
created by github.com/coreos/bbolt.(*Tx).Check
xxx/src/github.com/coreos/bbolt/tx.go:389 +0x67

Request documentation for checking if bucket exists

None of the example code in the README shows how to properly check if a bucket exists. All sample code says "assume bucket exists."

Please add at least one code example to demonstrate checking if a bucket exists.

Open 2nd write tx: fatal error: all goroutines are asleep - deadlock!

package main

import (
        "os"
        "fmt"
        bolt "github.com/coreos/bbolt"
)

func main() {
        var err error
        err = doWork()
        if err != nil {
                fmt.Fprintf(os.Stderr, "%s\n", err.Error())
                os.Exit(1)
        }
        os.Exit(0)
}

func pe(err error) string {
        if err != nil {
                return err.Error()
        }
        return "nil"
}

func doWork() error {
        db, err := bolt.Open("test.db", 0600, nil)
        fmt.Fprintf( os.Stderr, "open db: %s\n", pe(err))
        defer db.Close()

        tx1, err := db.Begin(true)
        fmt.Fprintf( os.Stderr, "01: tx 1: start rw: %s\n", pe(err))
        tx2, err := db.Begin(true)
        fmt.Fprintf( os.Stderr, "02: tx 2: start rw: %s\n", pe(err))
}
[jkayser@oel7latest cryptstore]$ bin/bolttest1
open db: nil
01: tx 1: start rw: nil
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [semacquire]:
sync.runtime_SemacquireMutex(0xc42006618c, 0x48e400)
        /usr/local/go1.9.2/src/runtime/sema.go:71 +0x3d
sync.(*Mutex).Lock(0xc420066188)
        /usr/local/go1.9.2/src/sync/mutex.go:134 +0xee
github.com/coreos/bbolt.(*DB).beginRWTx(0xc420066000, 0x0, 0x0, 0x0)
        /home/jkayser/projects/jkayser/experiment/cryptstore/src/github.com/coreos/bbolt/db.go:566 +0x65
github.com/coreos/bbolt.(*DB).Begin(0xc420066000, 0xc42000c001, 0x4e9518, 0x17, 0xc420041ed0)
        /home/jkayser/projects/jkayser/experiment/cryptstore/src/github.com/coreos/bbolt/db.go:515 +0x38
main.doWork(0x0, 0x0)
        /home/jkayser/projects/jibe/general/cryptstore/src/cmd/bolttest1/bolttest1.go:37 +0x271
main.main()
        /home/jkayser/projects/jibe/general/cryptstore/src/cmd/bolttest1/bolttest1.go:14 +0x26
[jkayser@oel7latest cryptstore]$

check command should be read-only

I tried taking a backup of a DB file, and I made it permissions 0400 so that it could not be accidentally modified later. I wanted to run "bolt check" on it to be certain it was a good backup. I couldn't because of the permissions. I changed it to u+w and then check worked.

https://github.com/coreos/bbolt/blob/af9db2027c98c61ecd8e17caa5bd265792b9b9a2/cmd/bolt/main.go#L202

The check command should give Open a bbolt.Options with ReadOnly == true, then checking read-only files would work.

update readme file to clarify the goal of the fork

This is not a blind fork. etcd relies on boltdb pretty heavily, and cares a lot about its reliability and stability. The upstream bolt works well enough for a lot of use cases and is not actively being developed or accepting PRs. Thus, we fork it for a faster development cycle and maintaining it towards the goal of better reliability and stability, at least for etcd use case.

incremental backup possible?

The WriteTo is the whole db, is anyone thinking/working on having one that is able to start from an existing backup?
Would be useful so a readonly backup could be used to read and not block updates to another in the case where delayed reads are acceptable.

Corrupted db file when the vm got turned off because of an overload

OS: MacOS with RHEL VM

The db file got corrupted when the MAC OS decided to restart by itself and my program was running in RHEL VM. Following is the check output.

$ bolt check tmp.db
page 0: multiple references
page 0: invalid type: unknown<00>
panic: invalid page type: 0: 0

goroutine 5 [running]:
panic(0x4e4120, 0xc420010610)
        /usr/lib/golang/src/runtime/panic.go:500 +0x1a1
github.com/boltdb/bolt.(*Cursor).search(0xc42003eba8, 0x7f50350f20f0, 0xa, 0xa, 0x1bb69)
        /opt/pindrop/include/go/src/github.com/boltdb/bolt/cursor.go:256 +0x429
github.com/boltdb/bolt.(*Cursor).seek(0xc42003eba8, 0x7f50350f20f0, 0xa, 0xa, 0x0, 0x0, 0x4f77a0, 0xc42000a3f0, 0x2, 0x2, ...)
        /opt/pindrop/include/go/src/github.com/boltdb/bolt/cursor.go:159 +0xb1
github.com/boltdb/bolt.(*Bucket).Bucket(0xc420078018, 0x7f50350f20f0, 0xa, 0xa, 0x0)
        /opt/pindrop/include/go/src/github.com/boltdb/bolt/bucket.go:112 +0x108
github.com/boltdb/bolt.(*Tx).checkBucket.func2(0x7f50350f20f0, 0xa, 0xa, 0x7f50350f20fa, 0x66, 0x66, 0x66, 0x0)
        /opt/pindrop/include/go/src/github.com/boltdb/bolt/tx.go:449 +0x70
github.com/boltdb/bolt.(*Bucket).ForEach(0xc420078018, 0xc42003ecc0, 0x0, 0xc42003ecf0)
        /opt/pindrop/include/go/src/github.com/boltdb/bolt/bucket.go:390 +0xff
github.com/boltdb/bolt.(*Tx).checkBucket(0xc420078000, 0xc420078018, 0xc42003eea0, 0xc42003eed0, 0xc4200540c0)
        /opt/pindrop/include/go/src/github.com/boltdb/bolt/tx.go:453 +0x135
github.com/boltdb/bolt.(*Tx).check(0xc420078000, 0xc4200540c0)
        /opt/pindrop/include/go/src/github.com/boltdb/bolt/tx.go:404 +0x5f7
created by github.com/boltdb/bolt.(*Tx).Check
        /opt/pindrop/include/go/src/github.com/boltdb/bolt/tx.go:379 +0x67

Is there a way to fix the db file by any means? I check boltdb/bolt#348 and my version (ee30b748bcfbd74ec1d8439ae8fd4f9123a5c94e) is greater than that .

Note that it didn't happen again when i tried to reproduce again by powering off the virtual machine manually from MAC OS.

Panic == crashes

I see several panic() calls in the code, but absolutely no recover() stuff. As you can not recover another module's code, you're prone to you process dying if 1) you have a faulty database or 2) there are errors in the boltdb/bbolt code somewhere.

We're using boltdb in our software, and it runs on a large number of machines - pretty reliably. But sometimes, bad stuff does happen, and the application crashes in the boltdb code somewhere.

Shouldn't everything be so reliable that it doesn't bring your entire application down with it?

Best Practice for Multiple Puts

What's the best practice for doing multiple put operations, say, on a slice of a struct? Is it better to range the slice inside db.Update(), or do multiple db.Update() inside the range?

func saveInfo(infos []myInfoStruct) error {
  return db.Update(func(tx *bolt.Tx) error {
    for _, o := range infos {
      buf, _ := json.Marshal(o)
      if err := tx.Put(o.key, buf); err != nil {
        return err
      }
    }
    return nil
  })
}

or

func saveInfo(infos []myInfoStruct) error {
  for _, o := range infos {
    buf, _ := json.Marshal(o)
    err := db.Update(func(tx *bolt.Tx) error {
      if err := tx.Put(o.key, buf); err != nil {
        return err
      }
      return nil
    })

    if err != nil {
      return err  // breaks for-loop on any failure
    }
  }
  return nil
}

In re-reading my code above, the 2nd option appears to be less "atomic" if you are considering Put()'ing the entire slice as a single transaction. In the 1st option, if any Put() fails, they will all fail because the Update() would return non-nill. In the 2nd option, several Put-Update's may succeed but the N-th could fail resulting in that element plus all subsequent slice elements to not be added.

Interest for allocation-free reads

Is there community interest for allocation-free reads? This was a suggestion for future work from @benbjohnson.

After zooming into the existing code, it may be feasible.

It could be reached in 2 steps:

1 - Provide an allocation-free Get within an already allocated Tx transaction - i.e., a Tx.Get(keys ...[]byte) with variadic keys argument - note it doesn't rely on any Bucket allocation
That first step gives us allocation-free batched reads

2 - Wrap it further into an allocation-free read outside of any Tx transaction (but still properly read-locking the db, etc...) through a DB.Get(keys ...[)byte)
That second step offers us allocation-free atomic reads

If interest is sufficient, I may contribute some pieces

page already freed

Openig same issue as boltdb/bolt#731, because coreos/bbolt also crashes in same way:

package main

import (
	"log"
	"math/rand"

	"github.com/coreos/bbolt"
	// "github.com/boltdb/bolt"
)

var BC = make(chan []byte)

func main() {

	go Add(BC, "/opt/test.db")

	s := make([]byte, 30)
	for i := 0; i < 100000000; i++ {
		rand.Read(s)
		BC <- s
	}

	close(BC)

}

func Add(c chan []byte, bfile string) {
	const bname = `bc41`

	db, err := bolt.Open(bfile, 0600, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	err = db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists([]byte(bname))
		if err != nil {
			return err //fmt.Errorf("create bucket: %s", err)
		}
		return nil
	})
	if err != nil {
		log.Fatal(err)
		panic(err)
	}

	more := true
	for more {
		err := db.Update(func(tx *bolt.Tx) error {
			b := tx.Bucket([]byte(bname))
			for i := 0; i < 100000; i++ {
				v := <-c
				if v == nil {
					more = false
					return nil
				}
				err = b.Put(v, []byte("0"))
				if err != nil {
					return err
				}
			}
			return nil
		})
		if err != nil {
			log.Fatal(err)
			panic(err)
		}
	}
}
panic: page 3955 already freed

goroutine 5 [running]:
github.com/coreos/bbolt.(*freelist).free(0xc420074210, 0x7, 0x7fbb550ef000)
	/home/jambo/golang/src/github.com/coreos/bbolt/freelist.go:143 +0x4ad
github.com/coreos/bbolt.(*node).spill(0xc42163d810, 0xc4209c7800, 0x55f920)
	/home/jambo/golang/src/github.com/coreos/bbolt/node.go:363 +0x210
github.com/coreos/bbolt.(*node).spill(0xc42163d7a0, 0x0, 0x0)
	/home/jambo/golang/src/github.com/coreos/bbolt/node.go:350 +0xbf
github.com/coreos/bbolt.(*node).spill(0xc42163d490, 0xc4229c36e0, 0xc420045ab0)
	/home/jambo/golang/src/github.com/coreos/bbolt/node.go:350 +0xbf
github.com/coreos/bbolt.(*Bucket).spill(0xc420052580, 0xc4229c3600, 0xc420045d28)
	/home/jambo/golang/src/github.com/coreos/bbolt/bucket.go:568 +0x4d3
github.com/coreos/bbolt.(*Bucket).spill(0xc4200900f8, 0x2116cdd17, 0x5721a0)
	/home/jambo/golang/src/github.com/coreos/bbolt/bucket.go:535 +0x417
github.com/coreos/bbolt.(*Tx).Commit(0xc4200900e0, 0x0, 0x0)
	/home/jambo/golang/src/github.com/coreos/bbolt/tx.go:160 +0x129
github.com/coreos/bbolt.(*DB).Update(0xc420088000, 0xc42006bf98, 0x0, 0x0)
	/home/jambo/golang/src/github.com/coreos/bbolt/db.go:674 +0xf2
main.Add(0xc420072060, 0x4ea01b, 0x12)
	/home/jambo/go/src/jambo/tests/error1/error1.go:50 +0x1ac
created by main.main
	/home/jambo/go/src/jambo/tests/error1/error1.go:15 +0x5a
go version 
go version go1.9.1 linux/amd64

uname -a
Linux bee 4.9.0-0.bpo.4-amd64 #1 SMP Debian 4.9.51-1~bpo8+1 (2017-10-17) x86_64 GNU/Linux

'invalid argument' error while opening database on qemu/9p_virtio shared file system

I tried to store a db on a 9p_virtio shared file system but it throw me a 'invalid argument' error.
The db file gets created but seems it don't like something related to the file system.
Running on a regular file system works just fine.

Running on debian 9 a qemu/kvm virtual machine, sharing file system with host trough 9p_virtio module, in 'mapped' mode.

Here is my fstab :

# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/vda2 during installation
UUID=f3905f5b-7c6f-4093-b4c5-2f5c31037113 /               ext4    errors=remount-ro 0       1
# swap was on /dev/vda1 during installation
UUID=9cd015f1-ce56-41c6-9f41-bc0048f9f053 none            swap    sw              0       0
# Host share (data-stk-oo)
data-stk-oo /mnt/storkshare 9p rw,sync,dirsync,relatime,trans=virtio,version=9p2000.L 0 0

The only logs I get from go is invalid argument :

2018/06/11 10:19:09 Info:  Starting the server ...
2018/06/11 10:19:09 Info:  Checking data folders
2018/06/11 10:19:09 Info:  Loading database
2018/06/11 10:19:09 Info:  No database found, creating new one
2018/06/11 10:19:09 Fatal: invalid argument

Large database created under Windows is not the same as created under Linux or Mac

I created bolt databases under Windows/Linux/Mac and insert 100000 and 1000 records into the database. Then I got the result below:

file records created under file size md5sum
win_1000.db 1000 Windows 262144 05d62c9653360e15d35625759947e8ea
linux_1000.db 1000 Linux 262144 05d62c9653360e15d35625759947e8ea
mac_1000.db 1000 Mac 262144 05d62c9653360e15d35625759947e8ea
win_100000.db 100000 Windows 33554432 aa11783743dc42f44778ffbcbc4b0ba9
linux_100000.db 100000 Linux 34795520 b7cc6445179f70911d27f682903632d9
mac_100000.db 100000 Mac 34795520 b7cc6445179f70911d27f682903632d9

Things I found:

  1. If the number of the data is small, no matter which OS you use to create the database, the database files are all the same (same size and same content).
  2. If insert a large number of date into the database, the one created under Windows is different with the one created under Linux or Mac. See win_100000.db above.
  3. All database files can be recognized under Linux or Mac no matter which OS the database is created from.
  4. A database with a large number of data created under Linux or Mac can not be recognized under Windows. There will be an error when opening the database: CreateFileMapping: Not enough storage is available to process this command.

Could the 2nd and 4th point above be fixed?

Below is the code for test:

// file: test-bolt.go
package main

import (
    "crypto/sha512"
    "flag"
    "fmt"
    "io"
    "os"
    "github.com/coreos/bbolt"
)


func fileExist(filename string) bool {
    _, err := os.Stat(filename)
    if err == nil {
        return true
    }
    if os.IsNotExist(err) {
        return false
    }
    return true
}


func genData(n int) []byte {
    h := sha512.New()
    io.WriteString(h, fmt.Sprintf("%d", n))
    return h.Sum(nil)
}


func create(filename string, n int) (err error) {
    if fileExist(filename) {
        err = fmt.Errorf("%s already exist, please use another file name", filename)
        return
    }

    db, err := bolt.Open(filename, 0600, nil)
    if err != nil {
        return
    }
    defer db.Close()

    fmt.Fprintf(os.Stderr, "add %d records to %s:\n", n, filename)

    err = db.Update(func(tx *bolt.Tx) error {
        b, err := tx.CreateBucket([]byte("data"))
        if err != nil {
            return err
        }

        var i int
        for i = 1; i <= n; i++ {
            err = b.Put([]byte(fmt.Sprintf("%d", i)), genData(i))
            if err != nil {
                return err
            }

            if i % 2000 == 0 {
                fmt.Printf("%d records added\n", i)
            }
        }
        i--

        if i % 2000 != 0 {
            fmt.Printf("%d records added\n", i)
        }

        return nil
    })

    if err == nil {
        fmt.Println("done")
    }

    return
}


func check(filename string) (err error) {
    if !fileExist(filename) {
        err = fmt.Errorf("%s not exist", filename)
        return
    }

    db, err := bolt.Open(filename, 0600, &bolt.Options{ReadOnly:true})
    if err != nil {
        return
    }
    defer db.Close()

    err = db.View(func(tx *bolt.Tx) error {
        b := tx.Bucket([]byte("data"))
        if b == nil {
            return fmt.Errorf(`bucket "data" not found`)
        }
        fmt.Printf("%s has %d records.\n", filename, b.Stats().KeyN)
        return nil
    })

    return
}


const usage = `test-bolt

Usage:
    test-bolt -m create -n <integer> <filename>
    test-bolt -m check <filename>

Options:
    -m <create|check>   create or check bolt database
    -n <integer>        number of records to insert into the database
    -h                  help message`


func main() {
    var method, filename string
    var n int
    var help bool
    flag.StringVar(&method, "m", "", "create or check bolt database")
    flag.IntVar(&n, "n", 0, "number of records to insert into the database")
    flag.BoolVar(&help, "h", false, "help message")
    flag.Parse()

    if help {
        fmt.Println(usage)
        os.Exit(0)
    }

    if method != "create" && method != "check" {
        fmt.Fprintln(os.Stderr, `value of -m must be "create" or "check"`)
        os.Exit(1)
    }

    if method == "create" && n <= 0 {
        fmt.Fprintln(os.Stderr, "value of -n must > 0")
        os.Exit(1)
    }

    args := flag.Args()
    if len(args) == 0 {
        fmt.Fprintln(os.Stderr, "please input database filename")
        os.Exit(1)
    }

    filename = args[0]

    if method == "create" {
        err := create(filename, n)
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
            os.Exit(1)
        }
    } else {
        err := check(filename)
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
            os.Exit(1)
        }
    }
}

Test command:

Create database with 1000 records under Windows:

go run test-bolt.go -m create -n 1000 win_1000.db

Create database with 100000 records under Windows:

go run test-bolt.go -m create -n 100000 win_100000.db

Create database with 1000 records under Linux:

go run test-bolt.go -m create -n 1000 linux_1000.db

Create database with 100000 records under Linux:

go run test-bolt.go -m create -n 100000 linux_100000.db

Create database with 1000 records under Mac:

go run test-bolt.go -m create -n 1000 mac_1000.db

Create database with 100000 records under Mac:

go run test-bolt.go -m create -n 100000 mac_100000.db

Check database under Windows, Linux and Mac:

go run test-bolt.go -m check win_1000.db
go run test-bolt.go -m check win_100000.db
go run test-bolt.go -m check linux_1000.db
go run test-bolt.go -m check linux_100000.db
go run test-bolt.go -m check mac_1000.db
go run test-bolt.go -m check mac_100000.db

Open a not-exist file as read-only mode will cause create file.

If I open a database file which is not exist, bolt will return an error and create the file even if Options.ReadOnly == true. Why bolt still create file under read-only mode?

Here is the code:

// test-open-file.go
package main

import (
    "fmt"
    "flag"
    "os"
    bolt "github.com/coreos/bbolt"
)

func check(filename string) (err error) {
    db, err := bolt.Open(filename, 0600, &bolt.Options{ReadOnly:true})
    if err != nil {
        return
    }
    defer db.Close()
    return
}

func main() {
    flag.Parse()
    args := flag.Args()
    if len(args) == 0 {
        fmt.Fprintln(os.Stderr, "Please input filename")
        os.Exit(1)
    }

    fmt.Printf("Open \"%s\"\n", args[0])
    if err := check(args[0]); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    fmt.Println("ok")
}

Run the code:

go run test-open-file.go a-not-exist-file.db

Under Windows, it will create two files: a-not-exist-file.db and a-not-exist-file.db.lock. The error message is:

CreateFileMapping: Not enough storage is available to process this command.

Under Linux, it will create one file: a-not-exist-file.db. The error message is:

write a-not-exist-file.db: bad file descriptor

The error messages above are not friendly, why not just return "file not exist"?

panic: page 2 already freed

Triggered by starting/restarting etcd

panic: page 2 already freed

goroutine 98 [running]:
github.com/coreos/etcd/cmd/vendor/github.com/coreos/bbolt.(*freelist).free(0xc42022cb70, 0x46, 0x7fe98f92a000)
        /home/anthony/go/src/github.com/coreos/etcd/gopath/src/github.com/coreos/etcd/cmd/vendor/github.com/coreos/bbolt/freelist.go:143 +0x3c8
github.com/coreos/etcd/cmd/vendor/github.com/coreos/bbolt.(*node).spill(0xc4201d8000, 0xc420048b18, 0x7)
        /home/anthony/go/src/github.com/coreos/etcd/gopath/src/github.com/coreos/etcd/cmd/vendor/github.com/coreos/bbolt/node.go:363 +0x1e0
github.com/coreos/etcd/cmd/vendor/github.com/coreos/bbolt.(*Bucket).spill(0xc42038c398, 0x1acf1e9b, 0x1518800)
        /home/anthony/go/src/github.com/coreos/etcd/gopath/src/github.com/coreos/etcd/cmd/vendor/github.com/coreos/bbolt/bucket.go:570 +0x17b
github.com/coreos/etcd/cmd/vendor/github.com/coreos/bbolt.(*Tx).Commit(0xc42038c380, 0x1acf0d1c, 0x1518800)
        /home/anthony/go/src/github.com/coreos/etcd/gopath/src/github.com/coreos/etcd/cmd/vendor/github.com/coreos/bbolt/tx.go:163 +0x11f
github.com/coreos/etcd/cmd/vendor/github.com/coreos/etcd/mvcc/backend.(*batchTx).commit(0xc42022cc60, 0x0)
        /home/anthony/go/src/github.com/coreos/etcd/gopath/src/github.com/coreos/etcd/cmd/vendor/github.com/coreos/etcd/mvcc/backend/batch_tx.go:192 +0x82
github.com/coreos/etcd/cmd/vendor/github.com/coreos/etcd/mvcc/backend.(*batchTxBuffered).unsafeCommit(0xc42022cc60, 0xfc7900)
        /home/anthony/go/src/github.com/coreos/etcd/gopath/src/github.com/coreos/etcd/cmd/vendor/github.com/coreos/etcd/mvcc/backend/batch_tx.go:264 +0x49
github.com/coreos/etcd/cmd/vendor/github.com/coreos/etcd/mvcc/backend.(*batchTxBuffered).commit(0xc42022cc60, 0xfc4900)
        /home/anthony/go/src/github.com/coreos/etcd/gopath/src/github.com/coreos/etcd/cmd/vendor/github.com/coreos/etcd/mvcc/backend/batch_tx.go:252 +0x80
github.com/coreos/etcd/cmd/vendor/github.com/coreos/etcd/mvcc/backend.(*batchTxBuffered).Commit(0xc42022cc60)
        /home/anthony/go/src/github.com/coreos/etcd/gopath/src/github.com/coreos/etcd/cmd/vendor/github.com/coreos/etcd/mvcc/backend/batch_tx.go:239 +0x66
github.com/coreos/etcd/cmd/vendor/github.com/coreos/etcd/mvcc/backend.(*backend).run(0xc420210ae0)
        /home/anthony/go/src/github.com/coreos/etcd/gopath/src/github.com/coreos/etcd/cmd/vendor/github.com/coreos/etcd/mvcc/backend/backend.go:258 +0x13b
created by github.com/coreos/etcd/cmd/vendor/github.com/coreos/etcd/mvcc/backend.newBackend
        /home/anthony/go/src/github.com/coreos/etcd/gopath/src/github.com/coreos/etcd/cmd/vendor/github.com/coreos/etcd/mvcc/backend/backend.go:150 +0x344

Increase the waiting time when TestDB_Open_InitialMmapSize

Origin from https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=832834

Since boltdb/bolt is not active, I think reporting this issue here is more appropriate.
We have the following issue,

--- FAIL: TestDB_Open_InitialMmapSize (5.21s)
        db_test.go:416: unexpected that the reader blocks writer

I think it's caused by waiting only 5s for writing 134M data. Maybe waiting more time?
At lease I didn't meet such issue if I change the time to 180s.

And someone on the origin issue complains about the test shouldn't test the hardware...

compaction, for > 1MB values

Its great to see coreos/bbolt take up the boltdb project.

I wonder if you have already added compaction, e.g. to allow values over 1MB and not consume infinite disk space due to fragmentation? Some time back I made a fork that did this, so the code is already available--

https://github.com/bigboltdb/bolt

Bigboltdb is a fork of boltdb that supports database compaction and thus can store big values (over 1MB).

Writing big values causes fragmententation of the backing file, requiring regular compaction to avoid infinite file growth. Bigboltdb provides a Compact() api call to do this, and a mechanism to establish regular, automatic compaction by setting the db.CompactAfterCommitCount field.

Other than this one change, bigboltdb is simple, friendly fork of boltdb.

Document mmap error handling

Bolt is backed by an mmap'd file, but there is no documentation regarding the implications of this for disk read/write errors.

If the user's disk is faulty, standard IO operations can return an error, but when using mmap, there are no function calls to return errors. Instead, the OS sends a signal (SIGSEGV or SIGBUS) to the process. If the signal is not caught, the program crashes. Users of https://github.com/NebulousLabs/Sia have reported this behavior.

Bolt should document this drawback. Specifically:

  • It should describe what can happen in the event of an IO error
  • It should explain why Bolt doesn't catch the signal for you (there are many good reasons)
  • It should recommend an error-handling strategy, ideally with example code

Which sortable time encodings work?

The documentation says:

if you use a sortable time encoding such as RFC3339...

What other time encodings are acceptable? The documentation also states not to use RFC3339Nano because of the truncation issue, so I created my own fixed-length nano format:

RFC3339_FIXEDNANO = "2006-01-02T15:04:05.0000Z00:00"
.Put([]byte(o.Date.UTC().Format(RFC3339_FIXEDNANO)), buf)

While the insert happens, it is not inserted in timestamp order. Thus, when I fetch using a cursor, the print out (ie: fetch order) is insert-order, not timestamp order.

What restrictions are there for creating a "sortable time encoding" that will work correctly?

DB.Close(): funlock error

windows 10 x64
golang 1.9.1 and 1.8.4
bbolt v1.3.1-coreos.2(no problem with v1.3.1-coreos.1)

error when calling bolt.DB.Close()๏ผš
2017/10/10 11:05:57 bolt.Close(): funlock error: The segment is already unlocked.

#35(Support no timeout locks on db files) lead to this issue

Restart and remap are too slow

prolems

We use bolt options like etcd

const initialMmapSize = 10 * 1024 * 1024 * 1024 // 10G
db, err := bolt.Open("my.db", 0600, &bolt.Options{
		MmapFlags:       syscall.MAP_POPULATE,
		InitialMmapSize: initialMmapSize,
})

Restart boltdb is very slow.From the system metrics there are lots of disk reads duration db restart. When open returns, all the db file will be in the page cache. From this, I guess all bytes of the db file may be read into memory.

When the memory cannot hold all the db file and some pages of the file has been swapped out, boltdb's remap will be also very slow.

Is there some methods to speed up boltdb's restart and remap

system

  • System memory : 96G
  • Disk: SATA HDD
  • DB File Size: >= 10G

Cursor.Last() returns nil for non-empty bucket

Ubuntu amd-64 go 1.9.2

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/coreos/bbolt"
)

var (
	testBucket = []byte("test")
)

func initDB(path string) (*bolt.DB, error) {
	db, err := bolt.Open(path, 0600, &bolt.Options{Timeout: 1 * time.Second})
	if err != nil {
		return nil, err
	}
	err = db.Update(func(tx *bolt.Tx) error {
		err := tx.DeleteBucket(testBucket)
		_, err = tx.CreateBucketIfNotExists(testBucket)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		db.Close()
		return nil, err
	}

	return db, nil
}

func formatHeight(a int) []byte {
	return []byte(fmt.Sprintf("%08d", a))
}

func delBackwards(cb *bolt.Bucket, index int) error {
	err := cb.Delete(formatHeight(index))
	if err != nil {
		return fmt.Errorf("delete failed: %v", err)
	}
	cc := cb.Cursor()
	k, _ := cc.Last()
	k2, _ := cc.First()
	if k == nil && k2 != nil {
		return fmt.Errorf("last and first are inconsistent at %d for %#v %#v", index, k, k2)
	}
	return nil
}

func test(n int, value string) {
	db, err := initDB("bad_bolt.db")
	if err != nil {
		log.Fatalf("failed to initialize database: %v", err)
	}
	defer db.Close()
	err = db.Update(func(tx *bolt.Tx) error {
		cb := tx.Bucket(testBucket)
		for i := 0; i < n; i += 1 {
			err := cb.Put(formatHeight(i), []byte(value))
			if err != nil {
				return fmt.Errorf("put failed failed: %v", err)
			}
		}
		return nil
	})
	if err != nil {
		log.Fatalf("first tx failed: %v", err)
	}
	err = db.Update(func(tx *bolt.Tx) error {
		cb := tx.Bucket(testBucket)
		for i := n - 1; i >= 0; i -= 1 {
			err := delBackwards(cb, i)
			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		log.Printf("second tx failed: %v", err)
	} else {
		log.Printf("%d %v OK", n, value)
	}
}

func main() {
	test(100, "0000000000000000")
	test(100, "00000000000000000")
}

Crash when trying to open corrupted database

I have an app that takes regular backups of boltdb databases. Sometimes, for unknown reasons, the backups are corrupted.

I also have a restore UI that lets me browse and read from backups. Trying to open and read from these corrupted databases crashes my process. I'm using 4f5275f

unexpected fault address 0x8a6b008
fatal error: fault
[signal SIGSEGV: segmentation violation code=0x1 addr=0x8a6b008 pc=0x42e0e2f]

goroutine 12 [running]:
runtime.throw(0x4a487e4, 0x5)
	/usr/local/Cellar/go/1.10.2/libexec/src/runtime/panic.go:616 +0x81 fp=0xc4206eee00 sp=0xc4206eede0 pc=0x402d5b1
runtime.sigpanic()
	/usr/local/Cellar/go/1.10.2/libexec/src/runtime/signal_unix.go:395 +0x211 fp=0xc4206eee50 sp=0xc4206eee00 pc=0x4042de1
github.com/coreos/bbolt.(*Cursor).search(0xc4206eefe0, 0xc4206ef118, 0x6, 0x20, 0x63)
	.go/src/github.com/coreos/bbolt/cursor.go:255 +0x5f fp=0xc4206eef08 sp=0xc4206eee50 pc=0x42e0e2f
github.com/coreos/bbolt.(*Cursor).seek(0xc4206eefe0, 0xc4206ef118, 0x6, 0x20, 0x0, 0x0, 0x4063d84, 0x614e000, 0x0, 0x48d8300, ...)
	.go/src/github.com/coreos/bbolt/cursor.go:159 +0xa5 fp=0xc4206eef58 sp=0xc4206eef08 pc=0x42e0725
github.com/coreos/bbolt.(*Bucket).Bucket(0xc4204976d8, 0xc4206ef118, 0x6, 0x20, 0xc4206ef118)
	.go/src/github.com/coreos/bbolt/bucket.go:105 +0xde fp=0xc4206ef010 sp=0xc4206eef58 pc=0x42dc66e
github.com/coreos/bbolt.(*Tx).Bucket(0xc4204976c0, 0xc4206ef118, 0x6, 0x20, 0x6)
	.go/src/github.com/coreos/bbolt/tx.go:101 +0x4f fp=0xc4206ef048 sp=0xc4206ef010 pc=0x42ebbef

test.db.gz

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.