blockstore.go 4.74 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"
8

9 10 11 12 13 14
	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
	dsns "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/namespace"
	dsq "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/query"
	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"
15
	key "github.com/ipfs/go-ipfs/blocks/key"
Jeromy's avatar
Jeromy committed
16
	logging "github.com/ipfs/go-ipfs/vendor/QmQg1J6vikuXF9oDvm4wpdeAUvvkVEKW1EYDw9HhTMnP2b/go-log"
17 18
)

Jeromy's avatar
Jeromy committed
19
var log = logging.Logger("blockstore")
20

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

24 25
var ValueTypeMismatch = errors.New("The retrieved value is not a Block")

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

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

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

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

42 43 44 45 46 47 48 49 50 51
	// 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
52 53
}

Jeromy's avatar
Jeromy committed
54
func NewBlockstore(d ds.Batching) *blockstore {
Jeromy's avatar
Jeromy committed
55
	var dsb ds.Batching
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56
	dd := dsns.Wrap(d, BlockPrefix)
Jeromy's avatar
Jeromy committed
57
	dsb = dd
58
	return &blockstore{
Jeromy's avatar
Jeromy committed
59
		datastore: dsb,
60 61 62 63
	}
}

type blockstore struct {
Jeromy's avatar
Jeromy committed
64
	datastore ds.Batching
Jeromy's avatar
Jeromy committed
65 66

	lk sync.RWMutex
67 68
}

69
func (bs *blockstore) Get(k key.Key) (*blocks.Block, error) {
70
	maybeData, err := bs.datastore.Get(k.DsKey())
71 72 73
	if err == ds.ErrNotFound {
		return nil, ErrNotFound
	}
74 75 76 77 78 79 80 81 82 83 84 85
	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 {
86
	k := block.Key().DsKey()
87 88

	// Has is cheaper than Put, so see if we already have it
89
	exists, err := bs.datastore.Has(k)
90
	if err == nil && exists {
91 92 93
		return nil // already stored.
	}
	return bs.datastore.Put(k, block.Data)
94
}
95

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
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()
}

116
func (bs *blockstore) Has(k key.Key) (bool, error) {
117 118 119
	return bs.datastore.Has(k.DsKey())
}

120
func (s *blockstore) DeleteBlock(k key.Key) error {
121 122
	return s.datastore.Delete(k.DsKey())
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123

124
// AllKeysChan runs a query for keys from the blockstore.
125 126
// this is very simplistic, in the future, take dsq.Query as a param?
//
127
// AllKeysChan respects context
128
func (bs *blockstore) AllKeysChan(ctx context.Context) (<-chan key.Key, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129 130

	// KeysOnly, because that would be _a lot_ of data.
131
	q := dsq.Query{KeysOnly: true}
132 133
	// datastore/namespace does *NOT* fix up Query.Prefix
	q.Prefix = BlockPrefix.String()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134 135 136 137 138
	res, err := bs.datastore.Query(q)
	if err != nil {
		return nil, err
	}

139
	// this function is here to compartmentalize
140
	get := func() (k key.Key, ok bool) {
141 142 143 144 145 146 147 148 149 150 151 152
		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
			}

153 154
			// need to convert to key.Key using key.KeyFromDsKey.
			k = key.KeyFromDsKey(ds.NewKey(e.Key))
155
			log.Debug("blockstore: query got key", k)
156 157 158 159 160 161 162

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

163 164
			return k, true
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
165
	}
166

167
	output := make(chan key.Key)
168 169 170 171 172 173 174 175 176 177 178
	go func() {
		defer func() {
			res.Process().Close() // ensure exit (signals early exit, too)
			close(output)
		}()

		for {
			k, ok := get()
			if !ok {
				return
			}
179 180 181
			if k == "" {
				continue
			}
182 183 184 185 186 187 188 189 190 191

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

	return output, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192
}
Jeromy's avatar
Jeromy committed
193

194
func (bs *blockstore) GCLock() func() {
Jeromy's avatar
Jeromy committed
195 196 197 198
	bs.lk.Lock()
	return bs.lk.Unlock
}

199
func (bs *blockstore) PinLock() func() {
Jeromy's avatar
Jeromy committed
200 201 202
	bs.lk.RLock()
	return bs.lk.RUnlock
}