Skip to content
This repository has been archived by the owner on Oct 31, 2023. It is now read-only.

Commit

Permalink
initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
raulk committed Nov 25, 2020
0 parents commit 071fd4c
Show file tree
Hide file tree
Showing 7 changed files with 491 additions and 0 deletions.
5 changes: 5 additions & 0 deletions LICENSE-APACHE
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
19 changes: 19 additions & 0 deletions LICENSE-MIT
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# go-bs-lmdb

An LMDB-backed [IPFS Blockstore](https://github.com/ipfs/go-ipfs-blockstore/).

## License

Dual-licensed: [MIT](./LICENSE-MIT), [Apache Software License v2](./LICENSE-APACHE), by way of the
[Permissive License Stack](https://protocol.ai/blog/announcing-the-permissive-license-stack/).
218 changes: 218 additions & 0 deletions blockstore.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
package lmdbbs

import (
"context"
"fmt"
"os"
"sync/atomic"

"github.com/bmatsuo/lmdb-go/lmdb"
blocks "github.com/ipfs/go-block-format"
"github.com/ipfs/go-cid"
blockstore "github.com/ipfs/go-ipfs-blockstore"
)

const (
MaxDBs = 1 // needs to be configurable.
MapSize = 1 << 38 // 256GiB, this will need to be configurable.
MaxReaders = 128
FreelistReuse = uint(1000) // pages, in case we decide to use https://github.com/ledgerwatch/lmdb-go (non-viral license).
)

type Blockstore struct {
env *lmdb.Env
db lmdb.DBI

closed int32
}

var (
_ blockstore.Blockstore = (*Blockstore)(nil)
_ blockstore.Viewer = (*Blockstore)(nil)
)

func Open(path string) (*Blockstore, error) {
env, err := lmdb.NewEnv()
if err != nil {
return nil, fmt.Errorf("failed to initialize LMDB env: %w", err)
}
if err = env.SetMapSize(MapSize); err != nil {
return nil, fmt.Errorf("failed to set LMDB map size: %w", err)
}
if err = env.SetMaxDBs(MaxDBs); err != nil {
return nil, fmt.Errorf("failed to set LMDB max dbs: %w", err)
}
if err = env.SetMaxReaders(MaxReaders); err != nil {
return nil, fmt.Errorf("failed to set LMDB max readers: %w", err)
}

if st, err := os.Stat(path); os.IsNotExist(err) {
if err := os.MkdirAll(path, 0777); err != nil {
return nil, fmt.Errorf("failed to create lmdb data directory at %s: %w", path, err)
}
} else if err != nil {
return nil, fmt.Errorf("failed to check if lmdb data dir exists: %w", err)
} else if !st.IsDir() {
return nil, fmt.Errorf("lmdb path is not a directory %s", path)
}

err = env.Open(path, lmdb.NoSync|lmdb.WriteMap|lmdb.MapAsync|lmdb.NoReadahead, 0777)
if err != nil {
return nil, fmt.Errorf("failed to open lmdb database: %w", err)
}

bs := new(Blockstore)
bs.env = env
err = env.Update(func(txn *lmdb.Txn) (err error) {
bs.db, err = txn.CreateDBI("blocks")
return err
})
return bs, err
}

func (b *Blockstore) Close() error {
// lmdb doesn't do close idempotency, so we only process a single
// call to Close.
if atomic.CompareAndSwapInt32(&b.closed, 0, 1) {
b.env.CloseDBI(b.db)
return b.env.Close()
}
return nil
}

func (b *Blockstore) Has(cid cid.Cid) (bool, error) {
var exists bool
err := b.env.View(func(txn *lmdb.Txn) error {
txn.RawRead = true
_, err := txn.Get(b.db, cid.Hash())
if err == nil {
exists = true
}
return err
})
if lmdb.IsNotFound(err) {
return exists, nil
}
return exists, err
}

func (b *Blockstore) Get(cid cid.Cid) (blocks.Block, error) {
var val []byte
err := b.env.View(func(txn *lmdb.Txn) error {
txn.RawRead = true
v, err := txn.Get(b.db, cid.Hash())
if err == nil {
val = make([]byte, len(v))
copy(val, v)
}
return err
})
if err == nil {
return blocks.NewBlockWithCid(val, cid)
}
// lmdb returns badvalsize with nil keys.
if lmdb.IsNotFound(err) || lmdb.IsErrno(err, lmdb.BadValSize) {
return nil, blockstore.ErrNotFound
}
return nil, err
}

func (b *Blockstore) View(cid cid.Cid, callback func([]byte) error) error {
err := b.env.View(func(txn *lmdb.Txn) error {
txn.RawRead = true
v, err := txn.Get(b.db, cid.Hash())
if err == nil {
return callback(v)
}
return err
})
// lmdb returns badvalsize with nil keys.
if lmdb.IsNotFound(err) || lmdb.IsErrno(err, lmdb.BadValSize) {
return blockstore.ErrNotFound
}
return err
}

func (b *Blockstore) GetSize(cid cid.Cid) (int, error) {
size := -1
err := b.env.View(func(txn *lmdb.Txn) error {
txn.RawRead = true
v, err := txn.Get(b.db, cid.Hash())
if err == nil {
size = len(v)
}
return err
})
if lmdb.IsNotFound(err) {
err = blockstore.ErrNotFound
}
return size, err
}

func (b *Blockstore) Put(block blocks.Block) error {
return b.env.Update(func(txn *lmdb.Txn) error {
err := txn.Put(b.db, block.Cid().Hash(), block.RawData(), lmdb.NoOverwrite)
if err != nil && !lmdb.IsErrno(err, lmdb.KeyExist) {
return err
}
return err
})
}

func (b *Blockstore) PutMany(blocks []blocks.Block) error {
return b.env.Update(func(txn *lmdb.Txn) error {
for _, block := range blocks {
err := txn.Put(b.db, block.Cid().Hash(), block.RawData(), lmdb.NoOverwrite)
if err != nil && !lmdb.IsErrno(err, lmdb.KeyExist) {
return err
}
}
return nil
})
}

func (b *Blockstore) DeleteBlock(cid cid.Cid) error {
err := b.env.Update(func(txn *lmdb.Txn) error {
return txn.Del(b.db, cid.Hash(), nil)
})
if lmdb.IsNotFound(err) {
err = nil
}
return err
}

func (b *Blockstore) AllKeysChan(ctx context.Context) (<-chan cid.Cid, error) {
ch := make(chan cid.Cid)
go func() {
_ = b.env.View(func(txn *lmdb.Txn) error {
defer close(ch)

txn.RawRead = true
cur, err := txn.OpenCursor(b.db)
if err != nil {
return err
}
defer cur.Close()

for {
if ctx.Err() != nil {
return nil // context has fired.
}
k, _, err := cur.Get(nil, nil, lmdb.Next)
if lmdb.IsNotFound(err) {
return nil
}
if err != nil {
return err
}
ch <- cid.NewCidV1(cid.Raw, k)
}
})
}()

return ch, nil
}

func (b *Blockstore) HashOnRead(_ bool) {
// not supported
}
41 changes: 41 additions & 0 deletions blockstore_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package lmdbbs

import (
"io/ioutil"
"os"
"testing"

bstest "github.com/raulk/go-bs-tests"
)

func TestLMDBBlockstore(t *testing.T) {
s := &bstest.Suite{
NewBlockstore: newBlockstore,
OpenBlockstore: openBlockstore,
}
s.RunTests(t, "")
}

func newBlockstore(tb testing.TB) (bstest.Blockstore, string) {
tb.Helper()

path, err := ioutil.TempDir("", "")
if err != nil {
tb.Fatal(err)
}

db, err := Open(path)
if err != nil {
tb.Fatal(err)
}

tb.Cleanup(func() {
_ = os.RemoveAll(path)
})

return db, path
}

func openBlockstore(tb testing.TB, path string) (bstest.Blockstore, error) {
return Open(path)
}
28 changes: 28 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
module github.com/raulk/go-bs-lmdb

go 1.15

require (
github.com/bmatsuo/lmdb-go v1.8.0
github.com/google/uuid v1.1.2 // indirect
github.com/ipfs/go-block-format v0.0.2
github.com/ipfs/go-cid v0.0.7
github.com/ipfs/go-datastore v0.4.5 // indirect
github.com/ipfs/go-ipfs-blockstore v1.0.3
github.com/ipfs/go-log v1.0.4 // indirect
github.com/ipfs/go-log/v2 v2.1.2-0.20200626104915-0016c0b4b3e4 // indirect
github.com/minio/sha256-simd v0.1.1 // indirect
github.com/mr-tron/base58 v1.2.0 // indirect
github.com/multiformats/go-multihash v0.0.14 // indirect
github.com/multiformats/go-varint v0.0.6 // indirect
github.com/opentracing/opentracing-go v1.2.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/raulk/go-bs-tests v0.0.3
go.uber.org/zap v1.16.0 // indirect
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a // indirect
golang.org/x/lint v0.0.0-20200130185559-910be7a94367 // indirect
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 // indirect
golang.org/x/tools v0.0.0-20200827010519-17fd2f27a9e3 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
gopkg.in/yaml.v2 v2.3.0 // indirect
)
Loading

0 comments on commit 071fd4c

Please sign in to comment.