blockstore.go 5.62 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 103
	if bs.rehash {
		rb := blocks.NewBlock(bdata)
104
		if !rb.Cid().Equals(k) {
105 106 107 108 109
			return nil, ErrHashMismatch
		} else {
			return rb, nil
		}
	} else {
110
		return blocks.NewBlockWithCid(bdata, k)
111
	}
112 113
}

114
func (bs *blockstore) Put(block blocks.Block) error {
115
	k := dshelp.CidToDsKey(block.Cid())
116 117

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

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

Jeromy's avatar
Jeromy committed
137
		err = t.Put(k, b.RawData())
138 139 140 141 142 143 144
		if err != nil {
			return err
		}
	}
	return t.Commit()
}

145
func (bs *blockstore) Has(k *cid.Cid) (bool, error) {
146
	return bs.datastore.Has(dshelp.CidToDsKey(k))
147 148
}

149
func (s *blockstore) DeleteBlock(k *cid.Cid) error {
150
	return s.datastore.Delete(dshelp.CidToDsKey(k))
151
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
152

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

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

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

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

189
			log.Debug("blockstore: query got key", c)
190

191
			return c, true
192
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
193
	}
194

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

		for {
			k, ok := get()
			if !ok {
				return
			}
207
			if k == nil {
208 209
				continue
			}
210 211 212 213 214 215 216 217 218 219

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

	return output, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
220
}
Jeromy's avatar
Jeromy committed
221

222 223 224 225 226 227 228 229 230 231 232 233 234 235
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
236
	atomic.AddInt32(&bs.gcreq, 1)
Jeromy's avatar
Jeromy committed
237
	bs.lk.Lock()
Jeromy's avatar
Jeromy committed
238
	atomic.AddInt32(&bs.gcreq, -1)
239
	return &unlocker{bs.lk.Unlock}
Jeromy's avatar
Jeromy committed
240 241
}

242
func (bs *blockstore) PinLock() Unlocker {
Jeromy's avatar
Jeromy committed
243
	bs.lk.RLock()
244
	return &unlocker{bs.lk.RUnlock}
Jeromy's avatar
Jeromy committed
245
}
Jeromy's avatar
Jeromy committed
246 247 248 249

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