blockstore.go 6.73 KB
Newer Older
1
// Package blockstore implements a thin wrapper over a datastore, giving a
2 3 4 5
// clean interface for Getting and Putting block objects.
package blockstore

import (
6
	"context"
7
	"errors"
Jeromy's avatar
Jeromy committed
8
	"sync"
Jeromy's avatar
Jeromy committed
9
	"sync/atomic"
10

11 12 13 14 15 16 17
	blocks "github.com/ipfs/go-block-format"
	cid "github.com/ipfs/go-cid"
	ds "github.com/ipfs/go-datastore"
	dsns "github.com/ipfs/go-datastore/namespace"
	dsq "github.com/ipfs/go-datastore/query"
	dshelp "github.com/ipfs/go-ipfs-ds-help"
	logging "github.com/ipfs/go-log"
18 19
)

Jeromy's avatar
Jeromy committed
20
var log = logging.Logger("blockstore")
21

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22
// BlockPrefix namespaces blockstore datastores
23
var BlockPrefix = ds.NewKey("blocks")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
24

25 26 27 28 29 30
// ErrValueTypeMismatch is an error returned when the item retrieved from
// the datatstore is not a block.
var ErrValueTypeMismatch = errors.New("the retrieved value is not a Block")

// ErrHashMismatch is an error returned when the hash of a block
// is different than expected.
31
var ErrHashMismatch = errors.New("block in storage has different hash than requested")
32

33
// ErrNotFound is an error returned when a block is not found.
34 35
var ErrNotFound = errors.New("blockstore: block not found")

36 37
// Blockstore wraps a Datastore block-centered methods and provides a layer
// of abstraction which allows to add different caching strategies.
38
type Blockstore interface {
39 40 41
	DeleteBlock(*cid.Cid) error
	Has(*cid.Cid) (bool, error)
	Get(*cid.Cid) (blocks.Block, error)
Jeromy's avatar
Jeromy committed
42 43

	// Put puts a given block to the underlying datastore
44
	Put(blocks.Block) error
Jeromy's avatar
Jeromy committed
45 46 47

	// PutMany puts a slice of blocks at the same time using batching
	// capabilities of the underlying datastore whenever possible.
48
	PutMany([]blocks.Block) error
Jeromy's avatar
Jeromy committed
49

50 51 52
	// AllKeysChan returns a channel from which
	// the CIDs in the Blockstore can be read. It should respect
	// the given context, closing the channel if it becomes Done.
53
	AllKeysChan(ctx context.Context) (<-chan *cid.Cid, error)
Jeromy's avatar
Jeromy committed
54

55 56 57
	// HashOnRead specifies if every read block should be
	// rehashed to make sure it matches its CID.
	HashOnRead(enabled bool)
58 59
}

60 61
// GCLocker abstract functionality to lock a blockstore when performing
// garbage-collection operations.
62
type GCLocker interface {
63 64 65
	// GCLock locks the blockstore for garbage collection. No operations
	// that expect to finish with a pin should ocurr simultaneously.
	// Reading during GC is safe, and requires no lock.
66
	GCLock() Unlocker
67 68 69 70 71

	// PinLock locks the blockstore for sequences of puts expected to finish
	// with a pin (before GC). Multiple put->pin sequences can write through
	// at the same time, but no GC should not happen simulatenously.
	// Reading during Pinning is safe, and requires no lock.
72
	PinLock() Unlocker
Jeromy's avatar
Jeromy committed
73 74 75 76

	// GcRequested returns true if GCLock has been called and is waiting to
	// take the lock
	GCRequested() bool
Jeromy's avatar
Jeromy committed
77 78
}

79 80
// GCBlockstore is a blockstore that can safely run garbage-collection
// operations.
81 82 83 84 85
type GCBlockstore interface {
	Blockstore
	GCLocker
}

86 87
// NewGCBlockstore returns a default implementation of GCBlockstore
// using the given Blockstore and GCLocker.
88 89 90 91 92 93 94 95 96
func NewGCBlockstore(bs Blockstore, gcl GCLocker) GCBlockstore {
	return gcBlockstore{bs, gcl}
}

type gcBlockstore struct {
	Blockstore
	GCLocker
}

97 98 99
// NewBlockstore returns a default Blockstore implementation
// using the provided datastore.Batching backend.
func NewBlockstore(d ds.Batching) Blockstore {
Jeromy's avatar
Jeromy committed
100
	var dsb ds.Batching
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101
	dd := dsns.Wrap(d, BlockPrefix)
Jeromy's avatar
Jeromy committed
102
	dsb = dd
103
	return &blockstore{
Jeromy's avatar
Jeromy committed
104
		datastore: dsb,
105 106 107 108
	}
}

type blockstore struct {
Jeromy's avatar
Jeromy committed
109
	datastore ds.Batching
Jeromy's avatar
Jeromy committed
110

111 112 113
	rehash bool
}

114
func (bs *blockstore) HashOnRead(enabled bool) {
115
	bs.rehash = enabled
116 117
}

118 119 120
func (bs *blockstore) Get(k *cid.Cid) (blocks.Block, error) {
	if k == nil {
		log.Error("nil cid in blockstore")
jbenet's avatar
jbenet committed
121 122 123
		return nil, ErrNotFound
	}

124
	maybeData, err := bs.datastore.Get(dshelp.CidToDsKey(k))
125 126 127
	if err == ds.ErrNotFound {
		return nil, ErrNotFound
	}
128 129 130 131 132
	if err != nil {
		return nil, err
	}
	bdata, ok := maybeData.([]byte)
	if !ok {
133
		return nil, ErrValueTypeMismatch
134 135
	}

136
	if bs.rehash {
137 138 139 140 141 142
		rbcid, err := k.Prefix().Sum(bdata)
		if err != nil {
			return nil, err
		}

		if !rbcid.Equals(k) {
143 144
			return nil, ErrHashMismatch
		}
145 146

		return blocks.NewBlockWithCid(bdata, rbcid)
147
	}
148
	return blocks.NewBlockWithCid(bdata, k)
149 150
}

151
func (bs *blockstore) Put(block blocks.Block) error {
152
	k := dshelp.CidToDsKey(block.Cid())
153 154

	// Has is cheaper than Put, so see if we already have it
155
	exists, err := bs.datastore.Has(k)
156
	if err == nil && exists {
157 158
		return nil // already stored.
	}
Jeromy's avatar
Jeromy committed
159
	return bs.datastore.Put(k, block.RawData())
160
}
161

162
func (bs *blockstore) PutMany(blocks []blocks.Block) error {
163 164 165 166 167
	t, err := bs.datastore.Batch()
	if err != nil {
		return err
	}
	for _, b := range blocks {
168
		k := dshelp.CidToDsKey(b.Cid())
169 170 171 172 173
		exists, err := bs.datastore.Has(k)
		if err == nil && exists {
			continue
		}

Jeromy's avatar
Jeromy committed
174
		err = t.Put(k, b.RawData())
175 176 177 178 179 180 181
		if err != nil {
			return err
		}
	}
	return t.Commit()
}

182
func (bs *blockstore) Has(k *cid.Cid) (bool, error) {
183
	return bs.datastore.Has(dshelp.CidToDsKey(k))
184 185
}

186 187
func (bs *blockstore) DeleteBlock(k *cid.Cid) error {
	err := bs.datastore.Delete(dshelp.CidToDsKey(k))
188 189 190 191
	if err == ds.ErrNotFound {
		return ErrNotFound
	}
	return err
192
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
193

194
// AllKeysChan runs a query for keys from the blockstore.
195 196
// this is very simplistic, in the future, take dsq.Query as a param?
//
197
// AllKeysChan respects context.
198
func (bs *blockstore) AllKeysChan(ctx context.Context) (<-chan *cid.Cid, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
199 200

	// KeysOnly, because that would be _a lot_ of data.
201
	q := dsq.Query{KeysOnly: true}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202 203 204 205 206
	res, err := bs.datastore.Query(q)
	if err != nil {
		return nil, err
	}

207
	output := make(chan *cid.Cid, dsq.KeysOnlyBufSize)
208 209
	go func() {
		defer func() {
210
			res.Close() // ensure exit (signals early exit, too)
211 212 213 214
			close(output)
		}()

		for {
215
			e, ok := res.NextSync()
216 217 218
			if !ok {
				return
			}
219
			if e.Error != nil {
Jakub Sztandera's avatar
Jakub Sztandera committed
220
				log.Errorf("blockstore.AllKeysChan got err: %s", e.Error)
221
				return
222 223 224 225 226
			}

			// need to convert to key.Key using key.KeyFromDsKey.
			k, err := dshelp.DsKeyToCid(ds.RawKey(e.Key))
			if err != nil {
Jakub Sztandera's avatar
Jakub Sztandera committed
227
				log.Warningf("error parsing key from DsKey: %s", err)
228 229
				continue
			}
230 231 232 233 234 235 236 237 238 239

			select {
			case <-ctx.Done():
				return
			case output <- k:
			}
		}
	}()

	return output, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
240
}
Jeromy's avatar
Jeromy committed
241

242 243 244
// NewGCLocker returns a default implementation of
// GCLocker using standard [RW] mutexes.
func NewGCLocker() GCLocker {
245 246 247 248
	return &gclocker{}
}

type gclocker struct {
249 250
	lk    sync.RWMutex
	gcreq int32
251 252
}

253 254
// Unlocker represents an object which can Unlock
// something.
255 256 257 258 259 260 261 262 263 264 265 266 267
type Unlocker interface {
	Unlock()
}

type unlocker struct {
	unlock func()
}

func (u *unlocker) Unlock() {
	u.unlock()
	u.unlock = nil // ensure its not called twice
}

268
func (bs *gclocker) GCLock() Unlocker {
Jeromy's avatar
Jeromy committed
269
	atomic.AddInt32(&bs.gcreq, 1)
Jeromy's avatar
Jeromy committed
270
	bs.lk.Lock()
Jeromy's avatar
Jeromy committed
271
	atomic.AddInt32(&bs.gcreq, -1)
272
	return &unlocker{bs.lk.Unlock}
Jeromy's avatar
Jeromy committed
273 274
}

275
func (bs *gclocker) PinLock() Unlocker {
Jeromy's avatar
Jeromy committed
276
	bs.lk.RLock()
277
	return &unlocker{bs.lk.RUnlock}
Jeromy's avatar
Jeromy committed
278
}
Jeromy's avatar
Jeromy committed
279

280
func (bs *gclocker) GCRequested() bool {
Jeromy's avatar
Jeromy committed
281 282
	return atomic.LoadInt32(&bs.gcreq) > 0
}