blockservice.go 8.69 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
	"io"
11

12
	"github.com/ipfs/go-ipfs/thirdparty/verifcid"
Jeromy's avatar
Jeromy committed
13

Jeromy's avatar
Jeromy committed
14 15 16 17 18
	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"
19 20
)

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

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

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

	// 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.
	GetBlocks(ctx context.Context, ks []*cid.Cid) <-chan blocks.Block
}

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

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

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

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

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

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

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

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

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

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

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

110 111 112 113 114
// 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.
115
func NewSession(ctx context.Context, bs BlockService) *Session {
116 117 118
	exch := bs.Exchange()
	if sessEx, ok := exch.(exchange.SessionExchange); ok {
		ses := sessEx.NewSession(ctx)
119 120
		return &Session{
			ses: ses,
121
			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
		// TODO(#4623): really an error?
153
		return errors.New("blockservice is closed")
154
	}
Jeromy's avatar
Jeromy committed
155

156
	return nil
157 158
}

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

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

Jeromy's avatar
Jeromy committed
188
	for _, o := range toput {
189
		log.Event(context.TODO(), "BlockService.BlockAdded", o.Cid())
190
		if err := s.exchange.HasBlock(o); err != nil {
191
			// TODO(#4623): Should this really *return*?
192
			return fmt.Errorf("blockservice is closed (%s)", err)
193 194
		}
	}
195
	return nil
196 197
}

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

203 204 205 206 207
	var f exchange.Fetcher
	if s.exchange != nil {
		f = s.exchange
	}

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

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

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

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

237
	log.Debug("Blockservice GetBlock: Not found")
Jeromy's avatar
Jeromy committed
238
	if err == blockstore.ErrNotFound {
239
		return nil, ErrNotFound
240
	}
Jeromy's avatar
Jeromy committed
241 242

	return nil, err
243
}
Jeromy's avatar
Jeromy committed
244

245 246 247
// GetBlocks gets a list of blocks asynchronously and returns through
// the returned channel.
// NB: No guarantees are made about order.
248
func (s *blockService) GetBlocks(ctx context.Context, ks []*cid.Cid) <-chan blocks.Block {
Jakub Sztandera's avatar
Jakub Sztandera committed
249
	return getBlocks(ctx, ks, s.blockstore, s.exchange) // hash security
250 251 252
}

func getBlocks(ctx context.Context, ks []*cid.Cid, bs blockstore.Blockstore, f exchange.Fetcher) <-chan blocks.Block {
253
	out := make(chan blocks.Block)
254

255
	go func() {
256
		defer close(out)
257 258 259 260 261 262 263 264 265 266 267 268 269

		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]

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

284 285 286 287
		if len(misses) == 0 {
			return
		}

288
		rblocks, err := f.GetBlocks(ctx, misses)
Jeromy's avatar
Jeromy committed
289
		if err != nil {
290
			log.Debugf("Error with GetBlocks: %s", err)
Jeromy's avatar
Jeromy committed
291 292
			return
		}
293

294
		for b := range rblocks {
295
			log.Event(ctx, "BlockService.BlockFetched", b.Cid())
296 297 298 299 300
			select {
			case out <- b:
			case <-ctx.Done():
				return
			}
Jeromy's avatar
Jeromy committed
301
		}
302 303
	}()
	return out
Jeromy's avatar
Jeromy committed
304 305
}

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

315
func (s *blockService) Close() error {
316
	log.Debug("blockservice is shutting down...")
317
	return s.exchange.Close()
318
}
319

Jeromy's avatar
Jeromy committed
320
// Session is a helper type to provide higher level access to bitswap sessions
321 322 323 324 325
type Session struct {
	bs  blockstore.Blockstore
	ses exchange.Fetcher
}

Jeromy's avatar
Jeromy committed
326
// GetBlock gets a block in the context of a request session
327
func (s *Session) GetBlock(ctx context.Context, c *cid.Cid) (blocks.Block, error) {
328
	return getBlock(ctx, c, s.bs, s.ses) // hash security
329 330
}

Jeromy's avatar
Jeromy committed
331
// GetBlocks gets blocks in the context of a request session
332
func (s *Session) GetBlocks(ctx context.Context, ks []*cid.Cid) <-chan blocks.Block {
333
	return getBlocks(ctx, ks, s.bs, s.ses) // hash security
334
}
Steven Allen's avatar
Steven Allen committed
335 336

var _ BlockGetter = (*Session)(nil)