blockstore.go 6.77 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
// ErrHashMismatch is an error returned when the hash of a block
// is different than expected.
27
var ErrHashMismatch = errors.New("block in storage has different hash than requested")
28

29
// ErrNotFound is an error returned when a block is not found.
30 31
var ErrNotFound = errors.New("blockstore: block not found")

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

39 40 41
	// GetSize returns the CIDs mapped BlockSize
	GetSize(*cid.Cid) (int, error)

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

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

49 50 51
	// 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.
52
	AllKeysChan(ctx context.Context) (<-chan *cid.Cid, error)
Jeromy's avatar
Jeromy committed
53

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

59 60
// GCLocker abstract functionality to lock a blockstore when performing
// garbage-collection operations.
61
type GCLocker interface {
62 63 64
	// 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.
65
	GCLock() Unlocker
66 67 68

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

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

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

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

type gcBlockstore struct {
	Blockstore
	GCLocker
}

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

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

110 111 112
	rehash bool
}

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

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

123
	bdata, err := bs.datastore.Get(dshelp.CidToDsKey(k))
124 125 126
	if err == ds.ErrNotFound {
		return nil, ErrNotFound
	}
127 128 129
	if err != nil {
		return nil, err
	}
130
	if bs.rehash {
131 132 133 134 135 136
		rbcid, err := k.Prefix().Sum(bdata)
		if err != nil {
			return nil, err
		}

		if !rbcid.Equals(k) {
137 138
			return nil, ErrHashMismatch
		}
139 140

		return blocks.NewBlockWithCid(bdata, rbcid)
141
	}
142
	return blocks.NewBlockWithCid(bdata, k)
143 144
}

145
func (bs *blockstore) Put(block blocks.Block) error {
146
	k := dshelp.CidToDsKey(block.Cid())
147 148

	// Has is cheaper than Put, so see if we already have it
149
	exists, err := bs.datastore.Has(k)
150
	if err == nil && exists {
151 152
		return nil // already stored.
	}
Jeromy's avatar
Jeromy committed
153
	return bs.datastore.Put(k, block.RawData())
154
}
155

156
func (bs *blockstore) PutMany(blocks []blocks.Block) error {
157 158 159 160 161
	t, err := bs.datastore.Batch()
	if err != nil {
		return err
	}
	for _, b := range blocks {
162
		k := dshelp.CidToDsKey(b.Cid())
163 164 165 166 167
		exists, err := bs.datastore.Has(k)
		if err == nil && exists {
			continue
		}

Jeromy's avatar
Jeromy committed
168
		err = t.Put(k, b.RawData())
169 170 171 172 173 174 175
		if err != nil {
			return err
		}
	}
	return t.Commit()
}

176
func (bs *blockstore) Has(k *cid.Cid) (bool, error) {
177
	return bs.datastore.Has(dshelp.CidToDsKey(k))
178 179
}

180
func (bs *blockstore) GetSize(k *cid.Cid) (int, error) {
181
	bdata, err := bs.datastore.Get(dshelp.CidToDsKey(k))
182 183 184
	if err == ds.ErrNotFound {
		return -1, ErrNotFound
	}
185 186 187 188 189 190
	if err != nil {
		return -1, err
	}
	return len(bdata), nil
}

191 192
func (bs *blockstore) DeleteBlock(k *cid.Cid) error {
	err := bs.datastore.Delete(dshelp.CidToDsKey(k))
193 194 195 196
	if err == ds.ErrNotFound {
		return ErrNotFound
	}
	return err
197
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
198

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

	// KeysOnly, because that would be _a lot_ of data.
206
	q := dsq.Query{KeysOnly: true}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
207 208 209 210 211
	res, err := bs.datastore.Query(q)
	if err != nil {
		return nil, err
	}

212
	output := make(chan *cid.Cid, dsq.KeysOnlyBufSize)
213 214
	go func() {
		defer func() {
215
			res.Close() // ensure exit (signals early exit, too)
216 217 218 219
			close(output)
		}()

		for {
220
			e, ok := res.NextSync()
221 222 223
			if !ok {
				return
			}
224
			if e.Error != nil {
Jakub Sztandera's avatar
Jakub Sztandera committed
225
				log.Errorf("blockstore.AllKeysChan got err: %s", e.Error)
226
				return
227 228 229 230 231
			}

			// 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
232
				log.Warningf("error parsing key from DsKey: %s", err)
233 234
				continue
			}
235 236 237 238 239 240 241 242 243 244

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

	return output, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245
}
Jeromy's avatar
Jeromy committed
246

247 248 249
// NewGCLocker returns a default implementation of
// GCLocker using standard [RW] mutexes.
func NewGCLocker() GCLocker {
250 251 252 253
	return &gclocker{}
}

type gclocker struct {
254 255
	lk    sync.RWMutex
	gcreq int32
256 257
}

258 259
// Unlocker represents an object which can Unlock
// something.
260 261 262 263 264 265 266 267 268 269 270 271 272
type Unlocker interface {
	Unlock()
}

type unlocker struct {
	unlock func()
}

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

273
func (bs *gclocker) GCLock() Unlocker {
Jeromy's avatar
Jeromy committed
274
	atomic.AddInt32(&bs.gcreq, 1)
Jeromy's avatar
Jeromy committed
275
	bs.lk.Lock()
Jeromy's avatar
Jeromy committed
276
	atomic.AddInt32(&bs.gcreq, -1)
277
	return &unlocker{bs.lk.Unlock}
Jeromy's avatar
Jeromy committed
278 279
}

280
func (bs *gclocker) PinLock() Unlocker {
Jeromy's avatar
Jeromy committed
281
	bs.lk.RLock()
282
	return &unlocker{bs.lk.RUnlock}
Jeromy's avatar
Jeromy committed
283
}
Jeromy's avatar
Jeromy committed
284

285
func (bs *gclocker) GCRequested() bool {
Jeromy's avatar
Jeromy committed
286 287
	return atomic.LoadInt32(&bs.gcreq) > 0
}