blockstore.go 6.78 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
	// GetSize returns the CIDs mapped BlockSize
40
	GetSize(cid.Cid) (int, error)
41

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.Defined() {
		log.Error("undefined cid in blockstore")
jbenet's avatar
jbenet committed
120 121
		return nil, ErrNotFound
	}
122
	bdata, err := bs.datastore.Get(dshelp.MultihashToDsKey(k.Hash()))
123 124 125
	if err == ds.ErrNotFound {
		return nil, ErrNotFound
	}
126 127 128
	if err != nil {
		return nil, err
	}
129
	if bs.rehash {
130 131 132 133 134 135
		rbcid, err := k.Prefix().Sum(bdata)
		if err != nil {
			return nil, err
		}

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

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

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

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

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

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

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

179
func (bs *blockstore) GetSize(k cid.Cid) (int, error) {
180
	size, err := bs.datastore.GetSize(dshelp.MultihashToDsKey(k.Hash()))
181 182 183
	if err == ds.ErrNotFound {
		return -1, ErrNotFound
	}
Steven Allen's avatar
Steven Allen committed
184
	return size, err
185 186
}

187
func (bs *blockstore) DeleteBlock(k cid.Cid) error {
188
	return bs.datastore.Delete(dshelp.MultihashToDsKey(k.Hash()))
189
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190

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

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

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

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

			// need to convert to key.Key using key.KeyFromDsKey.
222
			bk, err := dshelp.BinaryFromDsKey(ds.RawKey(e.Key))
223
			if err != nil {
Alex Trottier's avatar
Alex Trottier committed
224
				log.Warningf("error parsing key from binary: %s", err)
225 226
				continue
			}
227
			k := cid.NewCidV1(cid.Raw, bk)
228 229 230 231 232 233 234 235 236
			select {
			case <-ctx.Done():
				return
			case output <- k:
			}
		}
	}()

	return output, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
237
}
Jeromy's avatar
Jeromy committed
238

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

type gclocker struct {
246 247
	lk    sync.RWMutex
	gcreq int32
248 249
}

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

type unlocker struct {
	unlock func()
}

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

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

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

277
func (bs *gclocker) GCRequested() bool {
Jeromy's avatar
Jeromy committed
278 279
	return atomic.LoadInt32(&bs.gcreq) > 0
}