blockservice.go 6.64 KB
Newer Older
1 2 3
// package blockservice implements a BlockService interface that provides
// a single GetBlock/AddBlock interface that seamlessly retrieves data either
// locally or from a remote peer through the exchange.
4 5 6
package blockservice

import (
7
	"context"
8
	"errors"
Jeromy's avatar
Jeromy committed
9
	"fmt"
10

11 12
	"github.com/ipfs/go-ipfs/blocks/blockstore"
	exchange "github.com/ipfs/go-ipfs/exchange"
13
	bitswap "github.com/ipfs/go-ipfs/exchange/bitswap"
Jeromy's avatar
Jeromy committed
14

Jeromy's avatar
Jeromy committed
15
	logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
16
	blocks "gx/ipfs/QmXxGS5QsUxpR3iqL5DjmsYPHR1Yz74siRQ4ChJqWFosMh/go-block-format"
17
	cid "gx/ipfs/Qma4RJSuh7mMeJQYCqMbKzekn6EwBo7HEs5AQYjVRMQATB/go-cid"
18 19
)

Jeromy's avatar
Jeromy committed
20
var log = logging.Logger("blockservice")
21

22
var ErrNotFound = errors.New("blockservice: key not found")
Jeromy's avatar
Jeromy committed
23

24 25
// BlockService is a hybrid block datastore. It stores data in a local
// datastore and may retrieve data from a remote Exchange.
26
// It uses an internal `datastore.Datastore` instance to store values.
27 28 29 30 31 32 33 34
type BlockService interface {
	Blockstore() blockstore.Blockstore
	Exchange() exchange.Interface
	AddBlock(o blocks.Block) (*cid.Cid, error)
	AddBlocks(bs []blocks.Block) ([]*cid.Cid, error)
	GetBlock(ctx context.Context, c *cid.Cid) (blocks.Block, error)
	GetBlocks(ctx context.Context, ks []*cid.Cid) <-chan blocks.Block
	DeleteBlock(o blocks.Block) error
35
	NewSession(context.Context) *Session
36 37 38 39 40 41
	Close() error
}

type blockService struct {
	blockstore blockstore.Blockstore
	exchange   exchange.Interface
42 43 44
	// If checkFirst is true then first check that a block doesn't
	// already exist to avoid republishing the block on the exchange.
	checkFirst bool
45 46 47
}

// NewBlockService creates a BlockService with given datastore instance.
48
func New(bs blockstore.Blockstore, rem exchange.Interface) BlockService {
Jeromy's avatar
Jeromy committed
49
	if rem == nil {
Jeromy's avatar
Jeromy committed
50
		log.Warning("blockservice running in local (offline) mode.")
Jeromy's avatar
Jeromy committed
51
	}
52

53 54 55
	return &blockService{
		blockstore: bs,
		exchange:   rem,
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
		checkFirst: true,
	}
}

// NewWriteThrough ceates a BlockService that guarantees writes will go
// through to the blockstore and are not skipped by cache checks.
func NewWriteThrough(bs blockstore.Blockstore, rem exchange.Interface) BlockService {
	if rem == nil {
		log.Warning("blockservice running in local (offline) mode.")
	}

	return &blockService{
		blockstore: bs,
		exchange:   rem,
		checkFirst: false,
71
	}
72 73
}

74 75 76 77 78 79 80 81
func (bs *blockService) Blockstore() blockstore.Blockstore {
	return bs.blockstore
}

func (bs *blockService) Exchange() exchange.Interface {
	return bs.exchange
}

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
func (bs *blockService) NewSession(ctx context.Context) *Session {
	bswap, ok := bs.Exchange().(*bitswap.Bitswap)
	if ok {
		ses := bswap.NewSession(ctx)
		return &Session{
			ses: ses,
			bs:  bs.blockstore,
		}
	}
	return &Session{
		ses: bs.exchange,
		bs:  bs.blockstore,
	}
}

97
// AddBlock adds a particular block to the service, Putting it into the datastore.
98
// TODO pass a context into this if the remote.HasBlock is going to remain here.
99
func (s *blockService) AddBlock(o blocks.Block) (*cid.Cid, error) {
Jeromy's avatar
Jeromy committed
100
	c := o.Cid()
101 102 103 104 105
	if s.checkFirst {
		has, err := s.blockstore.Has(c)
		if err != nil {
			return nil, err
		}
Jeromy's avatar
Jeromy committed
106

107 108 109
		if has {
			return c, nil
		}
110 111
	}

112
	err := s.blockstore.Put(o)
Jeromy's avatar
Jeromy committed
113
	if err != nil {
Jeromy's avatar
Jeromy committed
114
		return nil, err
Jeromy's avatar
Jeromy committed
115
	}
Jeromy's avatar
Jeromy committed
116

117
	if err := s.exchange.HasBlock(o); err != nil {
Jeromy's avatar
Jeromy committed
118
		return nil, errors.New("blockservice is closed")
119
	}
Jeromy's avatar
Jeromy committed
120 121

	return c, nil
122 123
}

124
func (s *blockService) AddBlocks(bs []blocks.Block) ([]*cid.Cid, error) {
125
	var toput []blocks.Block
126 127 128 129 130 131
	if s.checkFirst {
		for _, b := range bs {
			has, err := s.blockstore.Has(b.Cid())
			if err != nil {
				return nil, err
			}
132 133
			if !has {
				toput = append(toput, b)
134
			}
135
		}
136
	} else {
Jeromy's avatar
Jeromy committed
137
		toput = bs
138 139
	}

140
	err := s.blockstore.PutMany(toput)
141 142 143 144
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
145 146
	var ks []*cid.Cid
	for _, o := range toput {
147
		if err := s.exchange.HasBlock(o); err != nil {
Jeromy's avatar
Jeromy committed
148
			return nil, fmt.Errorf("blockservice is closed (%s)", err)
149
		}
Jeromy's avatar
Jeromy committed
150

151
		ks = append(ks, o.Cid())
152 153 154 155
	}
	return ks, nil
}

156 157
// GetBlock retrieves a particular block from the service,
// Getting it from the datastore using the key (hash).
158
func (s *blockService) GetBlock(ctx context.Context, c *cid.Cid) (blocks.Block, error) {
Jeromy's avatar
Jeromy committed
159
	log.Debugf("BlockService GetBlock: '%s'", c)
jbenet's avatar
jbenet committed
160

161 162 163 164 165 166 167 168 169 170
	var f exchange.Fetcher
	if s.exchange != nil {
		f = s.exchange
	}

	return getBlock(ctx, c, s.blockstore, f)
}

func getBlock(ctx context.Context, c *cid.Cid, bs blockstore.Blockstore, f exchange.Fetcher) (blocks.Block, error) {
	block, err := bs.Get(c)
Jeromy's avatar
Jeromy committed
171
	if err == nil {
172
		return block, nil
Jeromy's avatar
Jeromy committed
173 174
	}

175
	if err == blockstore.ErrNotFound && f != nil {
176 177
		// TODO be careful checking ErrNotFound. If the underlying
		// implementation changes, this will break.
178
		log.Debug("Blockservice: Searching bitswap")
179
		blk, err := f.GetBlock(ctx, c)
Jeromy's avatar
Jeromy committed
180
		if err != nil {
181 182 183
			if err == blockstore.ErrNotFound {
				return nil, ErrNotFound
			}
Jeromy's avatar
Jeromy committed
184 185 186
			return nil, err
		}
		return blk, nil
Jeromy's avatar
Jeromy committed
187 188
	}

189
	log.Debug("Blockservice GetBlock: Not found")
Jeromy's avatar
Jeromy committed
190
	if err == blockstore.ErrNotFound {
191
		return nil, ErrNotFound
192
	}
Jeromy's avatar
Jeromy committed
193 194

	return nil, err
195
}
Jeromy's avatar
Jeromy committed
196

197 198 199
// GetBlocks gets a list of blocks asynchronously and returns through
// the returned channel.
// NB: No guarantees are made about order.
200
func (s *blockService) GetBlocks(ctx context.Context, ks []*cid.Cid) <-chan blocks.Block {
201 202 203 204
	return getBlocks(ctx, ks, s.blockstore, s.exchange)
}

func getBlocks(ctx context.Context, ks []*cid.Cid, bs blockstore.Blockstore, f exchange.Fetcher) <-chan blocks.Block {
205
	out := make(chan blocks.Block)
206
	go func() {
207
		defer close(out)
208
		var misses []*cid.Cid
Jeromy's avatar
Jeromy committed
209
		for _, c := range ks {
210
			hit, err := bs.Get(c)
211
			if err != nil {
212
				misses = append(misses, c)
213
				continue
214
			}
215
			log.Debug("Blockservice: Got data in datastore")
216 217 218 219 220
			select {
			case out <- hit:
			case <-ctx.Done():
				return
			}
221
		}
Jeromy's avatar
Jeromy committed
222

223 224 225 226
		if len(misses) == 0 {
			return
		}

227
		rblocks, err := f.GetBlocks(ctx, misses)
Jeromy's avatar
Jeromy committed
228
		if err != nil {
229
			log.Debugf("Error with GetBlocks: %s", err)
Jeromy's avatar
Jeromy committed
230 231
			return
		}
232

233 234 235 236 237 238
		for b := range rblocks {
			select {
			case out <- b:
			case <-ctx.Done():
				return
			}
Jeromy's avatar
Jeromy committed
239
		}
240 241
	}()
	return out
Jeromy's avatar
Jeromy committed
242 243
}

Jeromy's avatar
Jeromy committed
244
// DeleteBlock deletes a block in the blockservice from the datastore
245 246
func (s *blockService) DeleteBlock(o blocks.Block) error {
	return s.blockstore.DeleteBlock(o.Cid())
Jeromy's avatar
Jeromy committed
247
}
248

249
func (s *blockService) Close() error {
250
	log.Debug("blockservice is shutting down...")
251
	return s.exchange.Close()
252
}
253

Jeromy's avatar
Jeromy committed
254
// Session is a helper type to provide higher level access to bitswap sessions
255 256 257 258 259
type Session struct {
	bs  blockstore.Blockstore
	ses exchange.Fetcher
}

Jeromy's avatar
Jeromy committed
260
// GetBlock gets a block in the context of a request session
261 262 263 264
func (s *Session) GetBlock(ctx context.Context, c *cid.Cid) (blocks.Block, error) {
	return getBlock(ctx, c, s.bs, s.ses)
}

Jeromy's avatar
Jeromy committed
265
// GetBlocks gets blocks in the context of a request session
266 267 268
func (s *Session) GetBlocks(ctx context.Context, ks []*cid.Cid) <-chan blocks.Block {
	return getBlocks(ctx, ks, s.bs, s.ses)
}