blockstore.go 7.12 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 44 45
	// GetSize returns the CIDs mapped BlockSize
	GetSize(*cid.Cid) (int, error)

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

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

53 54 55
	// 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.
56
	AllKeysChan(ctx context.Context) (<-chan *cid.Cid, error)
Jeromy's avatar
Jeromy committed
57

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

63 64
// GCLocker abstract functionality to lock a blockstore when performing
// garbage-collection operations.
65
type GCLocker interface {
66 67 68
	// 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.
69
	GCLock() Unlocker
70 71 72 73 74

	// 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.
75
	PinLock() Unlocker
Jeromy's avatar
Jeromy committed
76 77 78 79

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

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

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

type gcBlockstore struct {
	Blockstore
	GCLocker
}

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

type blockstore struct {
Jeromy's avatar
Jeromy committed
112
	datastore ds.Batching
Jeromy's avatar
Jeromy committed
113

114 115 116
	rehash bool
}

117
func (bs *blockstore) HashOnRead(enabled bool) {
118
	bs.rehash = enabled
119 120
}

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

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

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

		if !rbcid.Equals(k) {
146 147
			return nil, ErrHashMismatch
		}
148 149

		return blocks.NewBlockWithCid(bdata, rbcid)
150
	}
151
	return blocks.NewBlockWithCid(bdata, k)
152 153
}

154
func (bs *blockstore) Put(block blocks.Block) error {
155
	k := dshelp.CidToDsKey(block.Cid())
156 157

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

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

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

185
func (bs *blockstore) Has(k *cid.Cid) (bool, error) {
186
	return bs.datastore.Has(dshelp.CidToDsKey(k))
187 188
}

189 190
func (bs *blockstore) GetSize(k *cid.Cid) (int, error) {
	maybeData, err := bs.datastore.Get(dshelp.CidToDsKey(k))
191 192 193
	if err == ds.ErrNotFound {
		return -1, ErrNotFound
	}
194 195 196 197 198 199 200 201 202 203
	if err != nil {
		return -1, err
	}
	bdata, ok := maybeData.([]byte)
	if !ok {
		return -1, ErrValueTypeMismatch
	}
	return len(bdata), nil
}

204 205
func (bs *blockstore) DeleteBlock(k *cid.Cid) error {
	err := bs.datastore.Delete(dshelp.CidToDsKey(k))
206 207 208 209
	if err == ds.ErrNotFound {
		return ErrNotFound
	}
	return err
210
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
211

212
// AllKeysChan runs a query for keys from the blockstore.
213 214
// this is very simplistic, in the future, take dsq.Query as a param?
//
215
// AllKeysChan respects context.
216
func (bs *blockstore) AllKeysChan(ctx context.Context) (<-chan *cid.Cid, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
217 218

	// KeysOnly, because that would be _a lot_ of data.
219
	q := dsq.Query{KeysOnly: true}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
220 221 222 223 224
	res, err := bs.datastore.Query(q)
	if err != nil {
		return nil, err
	}

225
	output := make(chan *cid.Cid, dsq.KeysOnlyBufSize)
226 227
	go func() {
		defer func() {
228
			res.Close() // ensure exit (signals early exit, too)
229 230 231 232
			close(output)
		}()

		for {
233
			e, ok := res.NextSync()
234 235 236
			if !ok {
				return
			}
237
			if e.Error != nil {
Jakub Sztandera's avatar
Jakub Sztandera committed
238
				log.Errorf("blockstore.AllKeysChan got err: %s", e.Error)
239
				return
240 241 242 243 244
			}

			// 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
245
				log.Warningf("error parsing key from DsKey: %s", err)
246 247
				continue
			}
248 249 250 251 252 253 254 255 256 257

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

	return output, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
258
}
Jeromy's avatar
Jeromy committed
259

260 261 262
// NewGCLocker returns a default implementation of
// GCLocker using standard [RW] mutexes.
func NewGCLocker() GCLocker {
263 264 265 266
	return &gclocker{}
}

type gclocker struct {
267 268
	lk    sync.RWMutex
	gcreq int32
269 270
}

271 272
// Unlocker represents an object which can Unlock
// something.
273 274 275 276 277 278 279 280 281 282 283 284 285
type Unlocker interface {
	Unlock()
}

type unlocker struct {
	unlock func()
}

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

286
func (bs *gclocker) GCLock() Unlocker {
Jeromy's avatar
Jeromy committed
287
	atomic.AddInt32(&bs.gcreq, 1)
Jeromy's avatar
Jeromy committed
288
	bs.lk.Lock()
Jeromy's avatar
Jeromy committed
289
	atomic.AddInt32(&bs.gcreq, -1)
290
	return &unlocker{bs.lk.Unlock}
Jeromy's avatar
Jeromy committed
291 292
}

293
func (bs *gclocker) PinLock() Unlocker {
Jeromy's avatar
Jeromy committed
294
	bs.lk.RLock()
295
	return &unlocker{bs.lk.RUnlock}
Jeromy's avatar
Jeromy committed
296
}
Jeromy's avatar
Jeromy committed
297

298
func (bs *gclocker) GCRequested() bool {
Jeromy's avatar
Jeromy committed
299 300
	return atomic.LoadInt32(&bs.gcreq) > 0
}