blockstore.go 5.04 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 14 15
	mh "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash"
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	blocks "github.com/ipfs/go-ipfs/blocks"
16
	key "github.com/ipfs/go-ipfs/blocks/key"
Jeromy's avatar
Jeromy committed
17
	logging "github.com/ipfs/go-ipfs/vendor/QmQg1J6vikuXF9oDvm4wpdeAUvvkVEKW1EYDw9HhTMnP2b/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
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 33
	DeleteBlock(key.Key) error
	Has(key.Key) (bool, error)
	Get(key.Key) (*blocks.Block, error)
34
	Put(*blocks.Block) error
35
	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 46 47 48 49 50 51 52
	// 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.
	GCLock() func()

	// 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.
	PinLock() func()
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) {
77
	maybeData, err := bs.datastore.Get(k.DsKey())
78 79 80
	if err == ds.ErrNotFound {
		return nil, ErrNotFound
	}
81 82 83 84 85 86 87 88 89 90 91 92
	if err != nil {
		return nil, err
	}
	bdata, ok := maybeData.([]byte)
	if !ok {
		return nil, ValueTypeMismatch
	}

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

func (bs *blockstore) Put(block *blocks.Block) error {
93
	k := block.Key().DsKey()
94 95

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

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
func (bs *blockstore) PutMany(blocks []*blocks.Block) error {
	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
		}

		err = t.Put(k, b.Data)
		if err != nil {
			return err
		}
	}
	return t.Commit()
}

123
func (bs *blockstore) Has(k key.Key) (bool, error) {
124 125 126
	return bs.datastore.Has(k.DsKey())
}

127
func (s *blockstore) DeleteBlock(k key.Key) error {
128 129
	return s.datastore.Delete(k.DsKey())
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130

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

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

146
	// this function is here to compartmentalize
147
	get := func() (k key.Key, ok bool) {
148 149 150 151 152 153 154 155 156 157 158 159
		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
			}

160 161
			// need to convert to key.Key using key.KeyFromDsKey.
			k = key.KeyFromDsKey(ds.NewKey(e.Key))
162
			log.Debug("blockstore: query got key", k)
163 164 165 166 167 168 169

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

170 171
			return k, true
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172
	}
173

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

		for {
			k, ok := get()
			if !ok {
				return
			}
186 187 188
			if k == "" {
				continue
			}
189 190 191 192 193 194 195 196 197 198

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

	return output, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
199
}
Jeromy's avatar
Jeromy committed
200

201
func (bs *blockstore) GCLock() func() {
Jeromy's avatar
Jeromy committed
202
	atomic.AddInt32(&bs.gcreq, 1)
Jeromy's avatar
Jeromy committed
203
	bs.lk.Lock()
Jeromy's avatar
Jeromy committed
204
	atomic.AddInt32(&bs.gcreq, -1)
Jeromy's avatar
Jeromy committed
205 206 207
	return bs.lk.Unlock
}

208
func (bs *blockstore) PinLock() func() {
Jeromy's avatar
Jeromy committed
209 210 211
	bs.lk.RLock()
	return bs.lk.RUnlock
}
Jeromy's avatar
Jeromy committed
212 213 214 215

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