blockstore.go 5.68 KB
Newer Older
1 2 3 4 5
// package blockstore implements a thin wrapper over a datastore, giving a
// 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
	blocks "github.com/ipfs/go-ipfs/blocks"
12 13
	dshelp "github.com/ipfs/go-ipfs/thirdparty/ds-help"

Jeromy's avatar
Jeromy committed
14
	logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
15
	cid "gx/ipfs/QmXUuRadqDq5BuFWzVU6VuKaSjTcNm1gNCtLvvP1TJCW4z/go-cid"
George Antoniadis's avatar
George Antoniadis committed
16 17 18
	ds "gx/ipfs/QmbzuUusHqaLLoNTDEVLcSF6vZDHZDLPC7p4bztRvvkXxU/go-datastore"
	dsns "gx/ipfs/QmbzuUusHqaLLoNTDEVLcSF6vZDHZDLPC7p4bztRvvkXxU/go-datastore/namespace"
	dsq "gx/ipfs/QmbzuUusHqaLLoNTDEVLcSF6vZDHZDLPC7p4bztRvvkXxU/go-datastore/query"
19 20
)

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

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

26 27
var ValueTypeMismatch = errors.New("the retrieved value is not a Block")
var ErrHashMismatch = errors.New("block in storage has different hash than requested")
28

29 30
var ErrNotFound = errors.New("blockstore: block not found")

Jeromy's avatar
Jeromy committed
31
// Blockstore wraps a Datastore
32
type Blockstore interface {
33 34 35
	DeleteBlock(*cid.Cid) error
	Has(*cid.Cid) (bool, error)
	Get(*cid.Cid) (blocks.Block, error)
36 37
	Put(blocks.Block) error
	PutMany([]blocks.Block) error
38

39
	AllKeysChan(ctx context.Context) (<-chan *cid.Cid, error)
40 41
}

Jeromy's avatar
Jeromy committed
42 43 44
type GCBlockstore interface {
	Blockstore

45 46 47
	// 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.
48
	GCLock() Unlocker
49 50 51 52 53

	// 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.
54
	PinLock() Unlocker
Jeromy's avatar
Jeromy committed
55 56 57 58

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

Jeromy's avatar
Jeromy committed
61
func NewBlockstore(d ds.Batching) *blockstore {
Jeromy's avatar
Jeromy committed
62
	var dsb ds.Batching
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63
	dd := dsns.Wrap(d, BlockPrefix)
Jeromy's avatar
Jeromy committed
64
	dsb = dd
65
	return &blockstore{
Jeromy's avatar
Jeromy committed
66
		datastore: dsb,
67 68 69 70
	}
}

type blockstore struct {
Jeromy's avatar
Jeromy committed
71
	datastore ds.Batching
Jeromy's avatar
Jeromy committed
72

Jeromy's avatar
Jeromy committed
73 74 75
	lk      sync.RWMutex
	gcreq   int32
	gcreqlk sync.Mutex
76 77 78 79

	rehash bool
}

80
func (bs *blockstore) HashOnRead(enabled bool) {
81
	bs.rehash = enabled
82 83
}

84 85 86
func (bs *blockstore) Get(k *cid.Cid) (blocks.Block, error) {
	if k == nil {
		log.Error("nil cid in blockstore")
jbenet's avatar
jbenet committed
87 88 89
		return nil, ErrNotFound
	}

90
	maybeData, err := bs.datastore.Get(dshelp.CidToDsKey(k))
91 92 93
	if err == ds.ErrNotFound {
		return nil, ErrNotFound
	}
94 95 96 97 98 99 100 101
	if err != nil {
		return nil, err
	}
	bdata, ok := maybeData.([]byte)
	if !ok {
		return nil, ValueTypeMismatch
	}

102
	if bs.rehash {
103 104 105 106 107 108
		rbcid, err := k.Prefix().Sum(bdata)
		if err != nil {
			return nil, err
		}

		if !rbcid.Equals(k) {
109 110
			return nil, ErrHashMismatch
		}
111 112

		return blocks.NewBlockWithCid(bdata, rbcid)
113
	} else {
114
		return blocks.NewBlockWithCid(bdata, k)
115
	}
116 117
}

118
func (bs *blockstore) Put(block blocks.Block) error {
119
	k := dshelp.CidToDsKey(block.Cid())
120 121

	// Has is cheaper than Put, so see if we already have it
122
	exists, err := bs.datastore.Has(k)
123
	if err == nil && exists {
124 125
		return nil // already stored.
	}
Jeromy's avatar
Jeromy committed
126
	return bs.datastore.Put(k, block.RawData())
127
}
128

129
func (bs *blockstore) PutMany(blocks []blocks.Block) error {
130 131 132 133 134
	t, err := bs.datastore.Batch()
	if err != nil {
		return err
	}
	for _, b := range blocks {
135
		k := dshelp.CidToDsKey(b.Cid())
136 137 138 139 140
		exists, err := bs.datastore.Has(k)
		if err == nil && exists {
			continue
		}

Jeromy's avatar
Jeromy committed
141
		err = t.Put(k, b.RawData())
142 143 144 145 146 147 148
		if err != nil {
			return err
		}
	}
	return t.Commit()
}

149
func (bs *blockstore) Has(k *cid.Cid) (bool, error) {
150
	return bs.datastore.Has(dshelp.CidToDsKey(k))
151 152
}

153
func (s *blockstore) DeleteBlock(k *cid.Cid) error {
154
	return s.datastore.Delete(dshelp.CidToDsKey(k))
155
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156

157
// AllKeysChan runs a query for keys from the blockstore.
158 159
// this is very simplistic, in the future, take dsq.Query as a param?
//
160
// AllKeysChan respects context
161
func (bs *blockstore) AllKeysChan(ctx context.Context) (<-chan *cid.Cid, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162 163

	// KeysOnly, because that would be _a lot_ of data.
164
	q := dsq.Query{KeysOnly: true}
165 166
	// datastore/namespace does *NOT* fix up Query.Prefix
	q.Prefix = BlockPrefix.String()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
167 168 169 170 171
	res, err := bs.datastore.Query(q)
	if err != nil {
		return nil, err
	}

172
	// this function is here to compartmentalize
173
	get := func() (*cid.Cid, bool) {
174 175
		select {
		case <-ctx.Done():
176
			return nil, false
177 178
		case e, more := <-res.Next():
			if !more {
179
				return nil, false
180 181 182
			}
			if e.Error != nil {
				log.Debug("blockstore.AllKeysChan got err:", e.Error)
183
				return nil, false
184 185
			}

186
			// need to convert to key.Key using key.KeyFromDsKey.
187
			c, err := dshelp.DsKeyToCid(ds.NewKey(e.Key)) // TODO: calling NewKey isnt free
188 189
			if err != nil {
				log.Warningf("error parsing key from DsKey: ", err)
190
				return nil, true
191
			}
192

193
			log.Debug("blockstore: query got key", c)
194

195
			return c, true
196
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197
	}
198

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

		for {
			k, ok := get()
			if !ok {
				return
			}
211
			if k == nil {
212 213
				continue
			}
214 215 216 217 218 219 220 221 222 223

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

	return output, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224
}
Jeromy's avatar
Jeromy committed
225

226 227 228 229 230 231 232 233 234 235 236 237 238 239
type Unlocker interface {
	Unlock()
}

type unlocker struct {
	unlock func()
}

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

func (bs *blockstore) GCLock() Unlocker {
Jeromy's avatar
Jeromy committed
240
	atomic.AddInt32(&bs.gcreq, 1)
Jeromy's avatar
Jeromy committed
241
	bs.lk.Lock()
Jeromy's avatar
Jeromy committed
242
	atomic.AddInt32(&bs.gcreq, -1)
243
	return &unlocker{bs.lk.Unlock}
Jeromy's avatar
Jeromy committed
244 245
}

246
func (bs *blockstore) PinLock() Unlocker {
Jeromy's avatar
Jeromy committed
247
	bs.lk.RLock()
248
	return &unlocker{bs.lk.RUnlock}
Jeromy's avatar
Jeromy committed
249
}
Jeromy's avatar
Jeromy committed
250 251 252 253

func (bs *blockstore) GCRequested() bool {
	return atomic.LoadInt32(&bs.gcreq) > 0
}