blockservice.go 9.07 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"
9
	"io"
10
	"sync"
11

Jeromy's avatar
Jeromy committed
12 13 14 15 16
	blocks "github.com/ipfs/go-block-format"
	cid "github.com/ipfs/go-cid"
	blockstore "github.com/ipfs/go-ipfs-blockstore"
	exchange "github.com/ipfs/go-ipfs-exchange-interface"
	logging "github.com/ipfs/go-log"
Jeromy's avatar
Jeromy committed
17
	"github.com/ipfs/go-verifcid"
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

Steven Allen's avatar
Steven Allen committed
24 25
// BlockGetter is the common interface shared between blockservice sessions and
// the blockservice.
26 27
type BlockGetter interface {
	// GetBlock gets the requested block.
28
	GetBlock(ctx context.Context, c cid.Cid) (blocks.Block, error)
29 30 31 32 33 34 35 36

	// GetBlocks does a batch request for the given cids, returning blocks as
	// they are found, in no particular order.
	//
	// It may not be able to find all requested blocks (or the context may
	// be canceled). In that case, it will close the channel early. It is up
	// to the consumer to detect this situation and keep track which blocks
	// it has received and which it hasn't.
37
	GetBlocks(ctx context.Context, ks []cid.Cid) <-chan blocks.Block
38 39
}

40 41
// BlockService is a hybrid block datastore. It stores data in a local
// datastore and may retrieve data from a remote Exchange.
42
// It uses an internal `datastore.Datastore` instance to store values.
43
type BlockService interface {
44 45 46
	io.Closer
	BlockGetter

Jeromy's avatar
Jeromy committed
47
	// Blockstore returns a reference to the underlying blockstore
48
	Blockstore() blockstore.Blockstore
Jeromy's avatar
Jeromy committed
49 50

	// Exchange returns a reference to the underlying exchange (usually bitswap)
51
	Exchange() exchange.Interface
Jeromy's avatar
Jeromy committed
52 53

	// AddBlock puts a given block to the underlying datastore
54
	AddBlock(o blocks.Block) error
Jeromy's avatar
Jeromy committed
55 56 57

	// AddBlocks adds a slice of blocks at the same time using batching
	// capabilities of the underlying datastore whenever possible.
58
	AddBlocks(bs []blocks.Block) error
Jeromy's avatar
Jeromy committed
59

60
	// DeleteBlock deletes the given block from the blockservice.
61
	DeleteBlock(o cid.Cid) error
62 63 64 65 66
}

type blockService struct {
	blockstore blockstore.Blockstore
	exchange   exchange.Interface
67 68 69
	// If checkFirst is true then first check that a block doesn't
	// already exist to avoid republishing the block on the exchange.
	checkFirst bool
70 71 72
}

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

78 79 80
	return &blockService{
		blockstore: bs,
		exchange:   rem,
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
		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,
96
	}
97 98
}

Steven Allen's avatar
Steven Allen committed
99 100 101
// Blockstore returns the blockstore behind this blockservice.
func (s *blockService) Blockstore() blockstore.Blockstore {
	return s.blockstore
102 103
}

Steven Allen's avatar
Steven Allen committed
104 105 106
// Exchange returns the exchange behind this blockservice.
func (s *blockService) Exchange() exchange.Interface {
	return s.exchange
107 108
}

109 110 111 112 113
// NewSession creates a new session that allows for
// controlled exchange of wantlists to decrease the bandwidth overhead.
// If the current exchange is a SessionExchange, a new exchange
// session will be created. Otherwise, the current exchange will be used
// directly.
114
func NewSession(ctx context.Context, bs BlockService) *Session {
115 116 117
	exch := bs.Exchange()
	if sessEx, ok := exch.(exchange.SessionExchange); ok {
		ses := sessEx.NewSession(ctx)
118
		return &Session{
119 120 121
			ses:    ses,
			sessEx: sessEx,
			bs:     bs.Blockstore(),
122 123 124
		}
	}
	return &Session{
125
		ses: exch,
126
		bs:  bs.Blockstore(),
127 128 129
	}
}

130
// AddBlock adds a particular block to the service, Putting it into the datastore.
131
// TODO pass a context into this if the remote.HasBlock is going to remain here.
132
func (s *blockService) AddBlock(o blocks.Block) error {
Jeromy's avatar
Jeromy committed
133
	c := o.Cid()
134 135 136 137 138
	// hash security
	err := verifcid.ValidateCid(c)
	if err != nil {
		return err
	}
139
	if s.checkFirst {
140 141
		if has, err := s.blockstore.Has(c); has || err != nil {
			return err
142
		}
143 144
	}

145 146
	if err := s.blockstore.Put(o); err != nil {
		return err
Jeromy's avatar
Jeromy committed
147
	}
Jeromy's avatar
Jeromy committed
148

149 150
	log.Event(context.TODO(), "BlockService.BlockAdded", c)

151
	if err := s.exchange.HasBlock(o); err != nil {
152
		log.Errorf("HasBlock: %s", err.Error())
153
	}
Jeromy's avatar
Jeromy committed
154

155
	return nil
156 157
}

158
func (s *blockService) AddBlocks(bs []blocks.Block) error {
Jakub Sztandera's avatar
Jakub Sztandera committed
159
	// hash security
160 161 162 163 164 165
	for _, b := range bs {
		err := verifcid.ValidateCid(b.Cid())
		if err != nil {
			return err
		}
	}
166
	var toput []blocks.Block
167
	if s.checkFirst {
168
		toput = make([]blocks.Block, 0, len(bs))
169 170 171
		for _, b := range bs {
			has, err := s.blockstore.Has(b.Cid())
			if err != nil {
172
				return err
173
			}
174 175
			if !has {
				toput = append(toput, b)
176
			}
177
		}
178
	} else {
Jeromy's avatar
Jeromy committed
179
		toput = bs
180 181
	}

182
	err := s.blockstore.PutMany(toput)
183
	if err != nil {
184
		return err
185 186
	}

Jeromy's avatar
Jeromy committed
187
	for _, o := range toput {
188
		log.Event(context.TODO(), "BlockService.BlockAdded", o.Cid())
189
		if err := s.exchange.HasBlock(o); err != nil {
190
			log.Errorf("HasBlock: %s", err.Error())
191 192
		}
	}
193
	return nil
194 195
}

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

201
	var f func() exchange.Fetcher
202
	if s.exchange != nil {
203
		f = s.getExchange
204 205
	}

Jakub Sztandera's avatar
Jakub Sztandera committed
206
	return getBlock(ctx, c, s.blockstore, f) // hash security
207 208
}

209 210 211 212 213
func (s *blockService) getExchange() exchange.Fetcher {
	return s.exchange
}

func getBlock(ctx context.Context, c cid.Cid, bs blockstore.Blockstore, fget func() exchange.Fetcher) (blocks.Block, error) {
Jakub Sztandera's avatar
Jakub Sztandera committed
214
	err := verifcid.ValidateCid(c) // hash security
215 216 217 218
	if err != nil {
		return nil, err
	}

219
	block, err := bs.Get(c)
Jeromy's avatar
Jeromy committed
220
	if err == nil {
221
		return block, nil
Jeromy's avatar
Jeromy committed
222 223
	}

224 225 226
	if err == blockstore.ErrNotFound && fget != nil {
		f := fget() // Don't load the exchange until we have to

227 228
		// TODO be careful checking ErrNotFound. If the underlying
		// implementation changes, this will break.
229
		log.Debug("Blockservice: Searching bitswap")
230
		blk, err := f.GetBlock(ctx, c)
Jeromy's avatar
Jeromy committed
231
		if err != nil {
232 233 234
			if err == blockstore.ErrNotFound {
				return nil, ErrNotFound
			}
Jeromy's avatar
Jeromy committed
235 236
			return nil, err
		}
237
		log.Event(ctx, "BlockService.BlockFetched", c)
Jeromy's avatar
Jeromy committed
238
		return blk, nil
Jeromy's avatar
Jeromy committed
239 240
	}

241
	log.Debug("Blockservice GetBlock: Not found")
Jeromy's avatar
Jeromy committed
242
	if err == blockstore.ErrNotFound {
243
		return nil, ErrNotFound
244
	}
Jeromy's avatar
Jeromy committed
245 246

	return nil, err
247
}
Jeromy's avatar
Jeromy committed
248

249 250 251
// GetBlocks gets a list of blocks asynchronously and returns through
// the returned channel.
// NB: No guarantees are made about order.
252
func (s *blockService) GetBlocks(ctx context.Context, ks []cid.Cid) <-chan blocks.Block {
253
	return getBlocks(ctx, ks, s.blockstore, s.getExchange) // hash security
254 255
}

256
func getBlocks(ctx context.Context, ks []cid.Cid, bs blockstore.Blockstore, fget func() exchange.Fetcher) <-chan blocks.Block {
257
	out := make(chan blocks.Block)
258

259
	go func() {
260
		defer close(out)
261 262 263 264 265 266 267 268 269 270 271 272 273

		k := 0
		for _, c := range ks {
			// hash security
			if err := verifcid.ValidateCid(c); err == nil {
				ks[k] = c
				k++
			} else {
				log.Errorf("unsafe CID (%s) passed to blockService.GetBlocks: %s", c, err)
			}
		}
		ks = ks[:k]

274
		var misses []cid.Cid
Jeromy's avatar
Jeromy committed
275
		for _, c := range ks {
276
			hit, err := bs.Get(c)
277
			if err != nil {
278
				misses = append(misses, c)
279
				continue
280
			}
281 282 283 284 285
			select {
			case out <- hit:
			case <-ctx.Done():
				return
			}
286
		}
Jeromy's avatar
Jeromy committed
287

288 289 290 291
		if len(misses) == 0 {
			return
		}

292
		f := fget() // don't load exchange unless we have to
293
		rblocks, err := f.GetBlocks(ctx, misses)
Jeromy's avatar
Jeromy committed
294
		if err != nil {
295
			log.Debugf("Error with GetBlocks: %s", err)
Jeromy's avatar
Jeromy committed
296 297
			return
		}
298

299
		for b := range rblocks {
300
			log.Event(ctx, "BlockService.BlockFetched", b.Cid())
301 302 303 304 305
			select {
			case out <- b:
			case <-ctx.Done():
				return
			}
Jeromy's avatar
Jeromy committed
306
		}
307 308
	}()
	return out
Jeromy's avatar
Jeromy committed
309 310
}

Jeromy's avatar
Jeromy committed
311
// DeleteBlock deletes a block in the blockservice from the datastore
312
func (s *blockService) DeleteBlock(c cid.Cid) error {
313 314 315 316 317
	err := s.blockstore.DeleteBlock(c)
	if err == nil {
		log.Event(context.TODO(), "BlockService.BlockDeleted", c)
	}
	return err
Jeromy's avatar
Jeromy committed
318
}
319

320
func (s *blockService) Close() error {
321
	log.Debug("blockservice is shutting down...")
322
	return s.exchange.Close()
323
}
324

Jeromy's avatar
Jeromy committed
325
// Session is a helper type to provide higher level access to bitswap sessions
326
type Session struct {
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
	bs      blockstore.Blockstore
	ses     exchange.Fetcher
	sessEx  exchange.SessionExchange
	sessCtx context.Context
	lk      sync.Mutex
}

func (s *Session) getSession() exchange.Fetcher {
	s.lk.Lock()
	defer s.lk.Unlock()
	if s.ses == nil {
		s.ses = s.sessEx.NewSession(s.sessCtx)
	}

	return s.ses
342 343
}

Jeromy's avatar
Jeromy committed
344
// GetBlock gets a block in the context of a request session
345
func (s *Session) GetBlock(ctx context.Context, c cid.Cid) (blocks.Block, error) {
346
	return getBlock(ctx, c, s.bs, s.getSession) // hash security
347 348
}

Jeromy's avatar
Jeromy committed
349
// GetBlocks gets blocks in the context of a request session
350
func (s *Session) GetBlocks(ctx context.Context, ks []cid.Cid) <-chan blocks.Block {
351
	return getBlocks(ctx, ks, s.bs, s.getSession) // hash security
352
}
Steven Allen's avatar
Steven Allen committed
353 354

var _ BlockGetter = (*Session)(nil)