blockstore.go 5.25 KB
Newer Older
1 2 3 4 5 6
// package blockstore implements a thin wrapper over a datastore, giving a
// clean interface for Getting and Putting block objects.
package blockstore

import (
	"errors"
Jeromy's avatar
Jeromy committed
7
	"sync"
Jeromy's avatar
Jeromy committed
8
	"sync/atomic"
9

Jeromy's avatar
Jeromy committed
10 11 12
	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/ipfs/go-datastore"
	dsns "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/ipfs/go-datastore/namespace"
	dsq "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/ipfs/go-datastore/query"
13
	blocks "github.com/ipfs/go-ipfs/blocks"
14
	key "github.com/ipfs/go-ipfs/blocks/key"
15
	mh "gx/ipfs/QmYf7ng2hG5XBtJA3tN34DQ2GUN5HNksEw1rLDkmr6vGku/go-multihash"
Jakub Sztandera's avatar
Jakub Sztandera committed
16
	logging "gx/ipfs/QmYtB7Qge8cJpXc4irsEp8zRqfnZMBeB7aTrMEkPk67DRv/go-log"
Jeromy's avatar
Jeromy committed
17
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
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
var ValueTypeMismatch = errors.New("The retrieved value is not a Block")

27 28
var ErrNotFound = errors.New("blockstore: block not found")

Jeromy's avatar
Jeromy committed
29
// Blockstore wraps a Datastore
30
type Blockstore interface {
31 32
	DeleteBlock(key.Key) error
	Has(key.Key) (bool, error)
33 34 35
	Get(key.Key) (blocks.Block, error)
	Put(blocks.Block) error
	PutMany([]blocks.Block) error
36

37
	AllKeysChan(ctx context.Context) (<-chan key.Key, error)
38 39
}

Jeromy's avatar
Jeromy committed
40 41 42
type GCBlockstore interface {
	Blockstore

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

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

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

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

type blockstore struct {
Jeromy's avatar
Jeromy committed
69
	datastore ds.Batching
Jeromy's avatar
Jeromy committed
70

Jeromy's avatar
Jeromy committed
71 72 73
	lk      sync.RWMutex
	gcreq   int32
	gcreqlk sync.Mutex
74 75
}

76
func (bs *blockstore) Get(k key.Key) (blocks.Block, error) {
jbenet's avatar
jbenet committed
77 78 79 80
	if k == "" {
		return nil, ErrNotFound
	}

81
	maybeData, err := bs.datastore.Get(k.DsKey())
82 83 84
	if err == ds.ErrNotFound {
		return nil, ErrNotFound
	}
85 86 87 88 89 90 91 92 93 94 95
	if err != nil {
		return nil, err
	}
	bdata, ok := maybeData.([]byte)
	if !ok {
		return nil, ValueTypeMismatch
	}

	return blocks.NewBlockWithHash(bdata, mh.Multihash(k))
}

96
func (bs *blockstore) Put(block blocks.Block) error {
97
	k := block.Key().DsKey()
98 99

	// Has is cheaper than Put, so see if we already have it
100
	exists, err := bs.datastore.Has(k)
101
	if err == nil && exists {
102 103
		return nil // already stored.
	}
104
	return bs.datastore.Put(k, block.Data())
105
}
106

107
func (bs *blockstore) PutMany(blocks []blocks.Block) error {
108 109 110 111 112 113 114 115 116 117 118
	t, err := bs.datastore.Batch()
	if err != nil {
		return err
	}
	for _, b := range blocks {
		k := b.Key().DsKey()
		exists, err := bs.datastore.Has(k)
		if err == nil && exists {
			continue
		}

119
		err = t.Put(k, b.Data())
120 121 122 123 124 125 126
		if err != nil {
			return err
		}
	}
	return t.Commit()
}

127
func (bs *blockstore) Has(k key.Key) (bool, error) {
128 129 130
	return bs.datastore.Has(k.DsKey())
}

131
func (s *blockstore) DeleteBlock(k key.Key) error {
132 133
	return s.datastore.Delete(k.DsKey())
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134

135
// AllKeysChan runs a query for keys from the blockstore.
136 137
// this is very simplistic, in the future, take dsq.Query as a param?
//
138
// AllKeysChan respects context
139
func (bs *blockstore) AllKeysChan(ctx context.Context) (<-chan key.Key, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140 141

	// KeysOnly, because that would be _a lot_ of data.
142
	q := dsq.Query{KeysOnly: true}
143 144
	// datastore/namespace does *NOT* fix up Query.Prefix
	q.Prefix = BlockPrefix.String()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
145 146 147 148 149
	res, err := bs.datastore.Query(q)
	if err != nil {
		return nil, err
	}

150
	// this function is here to compartmentalize
151
	get := func() (k key.Key, ok bool) {
152 153 154 155 156 157 158 159 160 161 162 163
		select {
		case <-ctx.Done():
			return k, false
		case e, more := <-res.Next():
			if !more {
				return k, false
			}
			if e.Error != nil {
				log.Debug("blockstore.AllKeysChan got err:", e.Error)
				return k, false
			}

164 165
			// need to convert to key.Key using key.KeyFromDsKey.
			k = key.KeyFromDsKey(ds.NewKey(e.Key))
166
			log.Debug("blockstore: query got key", k)
167 168 169 170 171 172 173

			// key must be a multihash. else ignore it.
			_, err := mh.Cast([]byte(k))
			if err != nil {
				return "", true
			}

174 175
			return k, true
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
176
	}
177

178
	output := make(chan key.Key)
179 180 181 182 183 184 185 186 187 188 189
	go func() {
		defer func() {
			res.Process().Close() // ensure exit (signals early exit, too)
			close(output)
		}()

		for {
			k, ok := get()
			if !ok {
				return
			}
190 191 192
			if k == "" {
				continue
			}
193 194 195 196 197 198 199 200 201 202

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

	return output, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
203
}
Jeromy's avatar
Jeromy committed
204

205 206 207 208 209 210 211 212 213 214 215 216 217 218
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
219
	atomic.AddInt32(&bs.gcreq, 1)
Jeromy's avatar
Jeromy committed
220
	bs.lk.Lock()
Jeromy's avatar
Jeromy committed
221
	atomic.AddInt32(&bs.gcreq, -1)
222
	return &unlocker{bs.lk.Unlock}
Jeromy's avatar
Jeromy committed
223 224
}

225
func (bs *blockstore) PinLock() Unlocker {
Jeromy's avatar
Jeromy committed
226
	bs.lk.RLock()
227
	return &unlocker{bs.lk.RUnlock}
Jeromy's avatar
Jeromy committed
228
}
Jeromy's avatar
Jeromy committed
229 230 231 232

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