bitswap.go 12.1 KB
Newer Older
Brian Tiger Chow's avatar
Brian Tiger Chow committed
1 2
// package bitswap implements the IPFS Exchange interface with the BitSwap
// bilateral exchange protocol.
3 4 5
package bitswap

import (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	"errors"
Jeromy Johnson's avatar
Jeromy Johnson committed
7
	"fmt"
8
	"math"
9
	"sync"
Jeromy's avatar
Jeromy committed
10 11
	"time"

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
	process "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess"
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	blocks "github.com/ipfs/go-ipfs/blocks"
	blockstore "github.com/ipfs/go-ipfs/blocks/blockstore"
	exchange "github.com/ipfs/go-ipfs/exchange"
	decision "github.com/ipfs/go-ipfs/exchange/bitswap/decision"
	bsmsg "github.com/ipfs/go-ipfs/exchange/bitswap/message"
	bsnet "github.com/ipfs/go-ipfs/exchange/bitswap/network"
	notifications "github.com/ipfs/go-ipfs/exchange/bitswap/notifications"
	wantlist "github.com/ipfs/go-ipfs/exchange/bitswap/wantlist"
	peer "github.com/ipfs/go-ipfs/p2p/peer"
	"github.com/ipfs/go-ipfs/thirdparty/delay"
	eventlog "github.com/ipfs/go-ipfs/thirdparty/eventlog"
	u "github.com/ipfs/go-ipfs/util"
	pset "github.com/ipfs/go-ipfs/util/peerset" // TODO move this to peerstore
27 28
)

29
var log = eventlog.Logger("bitswap")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30

Brian Tiger Chow's avatar
Brian Tiger Chow committed
31
const (
Brian Tiger Chow's avatar
Brian Tiger Chow committed
32 33 34
	// maxProvidersPerRequest specifies the maximum number of providers desired
	// from the network. This value is specified because the network streams
	// results.
Brian Tiger Chow's avatar
Brian Tiger Chow committed
35 36 37 38
	// TODO: if a 'non-nice' strategy is implemented, consider increasing this value
	maxProvidersPerRequest = 3
	providerRequestTimeout = time.Second * 10
	hasBlockTimeout        = time.Second * 15
39
	provideTimeout         = time.Second * 15
Brian Tiger Chow's avatar
Brian Tiger Chow committed
40
	sizeBatchRequestChan   = 32
41 42
	// kMaxPriority is the max priority as defined by the bitswap protocol
	kMaxPriority = math.MaxInt32
43

Jeromy's avatar
Jeromy committed
44
	HasBlockBufferSize = 256
45
	provideWorkers     = 4
Brian Tiger Chow's avatar
Brian Tiger Chow committed
46
)
Jeromy's avatar
Jeromy committed
47

Brian Tiger Chow's avatar
Brian Tiger Chow committed
48
var (
Brian Tiger Chow's avatar
Brian Tiger Chow committed
49
	rebroadcastDelay = delay.Fixed(time.Second * 10)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
50
)
51

Brian Tiger Chow's avatar
Brian Tiger Chow committed
52 53 54 55
// New initializes a BitSwap instance that communicates over the provided
// BitSwapNetwork. This function registers the returned instance as the network
// delegate.
// Runs until context is cancelled.
56
func New(parent context.Context, p peer.ID, network bsnet.BitSwapNetwork,
57
	bstore blockstore.Blockstore, nice bool) exchange.Interface {
58

59 60 61 62 63 64 65
	// important to use provided parent context (since it may include important
	// loggable data). It's probably not a good idea to allow bitswap to be
	// coupled to the concerns of the IPFS daemon in this way.
	//
	// FIXME(btc) Now that bitswap manages itself using a process, it probably
	// shouldn't accept a context anymore. Clients should probably use Close()
	// exclusively. We should probably find another way to share logging data
66 67
	ctx, cancelFunc := context.WithCancel(parent)

68
	notif := notifications.New()
69 70 71 72 73
	px := process.WithTeardown(func() error {
		notif.Shutdown()
		return nil
	})

74
	go func() {
75
		<-px.Closing() // process closes first
Jeromy's avatar
Jeromy committed
76
		cancelFunc()
77 78 79 80
	}()
	go func() {
		<-ctx.Done() // parent cancelled first
		px.Close()
81 82
	}()

83
	bs := &Bitswap{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84
		self:          p,
85
		blockstore:    bstore,
86
		notifications: notif,
87
		engine:        decision.NewEngine(ctx, bstore), // TODO close the engine with Close() method
88
		network:       network,
89
		wantlist:      wantlist.NewThreadSafe(),
90
		batchRequests: make(chan *blockRequest, sizeBatchRequestChan),
91
		process:       px,
Jeromy's avatar
Jeromy committed
92
		newBlocks:     make(chan *blocks.Block, HasBlockBufferSize),
93
		provideKeys:   make(chan u.Key),
94
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
95
	network.SetDelegate(bs)
96

97 98
	// Start up bitswaps async worker routines
	bs.startWorkers(px, ctx)
99 100 101
	return bs
}

102 103
// Bitswap instances implement the bitswap protocol.
type Bitswap struct {
104

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
105 106 107
	// the ID of the peer to act on behalf of
	self peer.ID

108 109
	// network delivers messages on behalf of the session
	network bsnet.BitSwapNetwork
110 111 112 113 114 115 116

	// blockstore is the local database
	// NB: ensure threadsafety
	blockstore blockstore.Blockstore

	notifications notifications.PubSub

117 118 119
	// Requests for a set of related blocks
	// the assumption is made that the same peer is likely to
	// have more than a single block in the set
120
	batchRequests chan *blockRequest
Jeromy's avatar
Jeromy committed
121

122
	engine *decision.Engine
123

124
	wantlist *wantlist.ThreadSafe
125

126
	process process.Process
127 128

	newBlocks chan *blocks.Block
129 130

	provideKeys chan u.Key
131 132 133

	blocksRecvd    int
	dupBlocksRecvd int
134 135
}

136 137 138 139 140
type blockRequest struct {
	keys []u.Key
	ctx  context.Context
}

141
// GetBlock attempts to retrieve a particular block from peers within the
142
// deadline enforced by the context.
143
func (bs *Bitswap) GetBlock(parent context.Context, k u.Key) (*blocks.Block, error) {
144

145 146 147 148
	// Any async work initiated by this function must end when this function
	// returns. To ensure this, derive a new context. Note that it is okay to
	// listen on parent in this scope, but NOT okay to pass |parent| to
	// functions called by this one. Otherwise those functions won't return
149 150
	// when this context's cancel func is executed. This is difficult to
	// enforce. May this comment keep you safe.
151

152
	ctx, cancelFunc := context.WithCancel(parent)
153

Jeromy's avatar
Jeromy committed
154
	ctx = eventlog.ContextWithLoggable(ctx, eventlog.Uuid("GetBlockRequest"))
Jeromy's avatar
Jeromy committed
155
	defer log.EventBegin(ctx, "GetBlockRequest", &k).Done()
156 157 158 159

	defer func() {
		cancelFunc()
	}()
160

161
	promise, err := bs.GetBlocks(ctx, []u.Key{k})
162 163
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
164
	}
165 166

	select {
167 168 169 170 171 172 173 174 175
	case block, ok := <-promise:
		if !ok {
			select {
			case <-ctx.Done():
				return nil, ctx.Err()
			default:
				return nil, errors.New("promise channel was closed")
			}
		}
Jeromy's avatar
Jeromy committed
176
		return block, nil
177 178
	case <-parent.Done():
		return nil, parent.Err()
179 180 181
	}
}

182 183 184 185 186 187 188 189
func (bs *Bitswap) WantlistForPeer(p peer.ID) []u.Key {
	var out []u.Key
	for _, e := range bs.engine.WantlistForPeer(p) {
		out = append(out, e.Key)
	}
	return out
}

190 191 192 193 194 195 196
// GetBlocks returns a channel where the caller may receive blocks that
// correspond to the provided |keys|. Returns an error if BitSwap is unable to
// begin this request within the deadline enforced by the context.
//
// NB: Your request remains open until the context expires. To conserve
// resources, provide a context with a reasonably short deadline (ie. not one
// that lasts throughout the lifetime of the server)
197
func (bs *Bitswap) GetBlocks(ctx context.Context, keys []u.Key) (<-chan *blocks.Block, error) {
198 199 200 201 202
	select {
	case <-bs.process.Closing():
		return nil, errors.New("bitswap is closed")
	default:
	}
203
	promise := bs.notifications.Subscribe(ctx, keys...)
204 205 206 207 208

	req := &blockRequest{
		keys: keys,
		ctx:  ctx,
	}
209
	select {
210
	case bs.batchRequests <- req:
211
		return promise, nil
212 213 214
	case <-ctx.Done():
		return nil, ctx.Err()
	}
Jeromy's avatar
Jeromy committed
215 216
}

217 218
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
219
func (bs *Bitswap) HasBlock(ctx context.Context, blk *blocks.Block) error {
220
	log.Event(ctx, "hasBlock", blk)
221 222 223 224 225
	select {
	case <-bs.process.Closing():
		return errors.New("bitswap is closed")
	default:
	}
226

227 228 229 230 231
	if err := bs.blockstore.Put(blk); err != nil {
		return err
	}
	bs.wantlist.Remove(blk.Key())
	bs.notifications.Publish(blk)
232 233 234 235 236 237
	select {
	case bs.newBlocks <- blk:
	case <-ctx.Done():
		return ctx.Err()
	}
	return nil
238 239
}

240
func (bs *Bitswap) sendWantlistMsgToPeers(ctx context.Context, m bsmsg.BitSwapMessage, peers <-chan peer.ID) error {
241
	set := pset.New()
242
	wg := sync.WaitGroup{}
243

244 245 246 247 248 249 250
loop:
	for {
		select {
		case peerToQuery, ok := <-peers:
			if !ok {
				break loop
			}
251

252 253
			if !set.TryAdd(peerToQuery) { //Do once per peer
				continue
254
			}
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

			wg.Add(1)
			go func(p peer.ID) {
				defer wg.Done()
				if err := bs.send(ctx, p, m); err != nil {
					log.Debug(err) // TODO remove if too verbose
				}
			}(peerToQuery)
		case <-ctx.Done():
			return nil
		}
	}
	done := make(chan struct{})
	go func() {
		wg.Wait()
		close(done)
	}()

	select {
	case <-done:
	case <-ctx.Done():
276 277 278
		// NB: we may be abandoning goroutines here before they complete
		// this shouldnt be an issue because they will complete soon anyways
		// we just don't want their being slow to impact bitswap transfer speeds
Jeromy's avatar
Jeromy committed
279 280 281 282
	}
	return nil
}

283
func (bs *Bitswap) sendWantlistToPeers(ctx context.Context, peers <-chan peer.ID) error {
Jeromy's avatar
Jeromy committed
284 285
	message := bsmsg.New()
	message.SetFull(true)
286 287
	for _, wanted := range bs.wantlist.Entries() {
		message.AddEntry(wanted.Key, wanted.Priority)
Jeromy's avatar
Jeromy committed
288
	}
289 290
	return bs.sendWantlistMsgToPeers(ctx, message, peers)
}
Jeromy's avatar
Jeromy committed
291

292
func (bs *Bitswap) sendWantlistToProviders(ctx context.Context, entries []wantlist.Entry) {
Jeromy's avatar
Jeromy committed
293

294 295 296 297 298
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	// prepare a channel to hand off to sendWantlistToPeers
	sendToPeers := make(chan peer.ID)
Jeromy's avatar
Jeromy committed
299

300
	// Get providers for all entries in wantlist (could take a while)
Jeromy's avatar
Jeromy committed
301
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
302
	for _, e := range entries {
303
		wg.Add(1)
Jeromy's avatar
Jeromy committed
304
		go func(k u.Key) {
Jeromy's avatar
Jeromy committed
305
			defer wg.Done()
306

307 308
			child, cancel := context.WithTimeout(ctx, providerRequestTimeout)
			defer cancel()
309
			providers := bs.network.FindProvidersAsync(child, k, maxProvidersPerRequest)
310
			for prov := range providers {
311
				sendToPeers <- prov
Jeromy's avatar
Jeromy committed
312
			}
313
		}(e.Key)
Jeromy's avatar
Jeromy committed
314
	}
315 316 317 318 319 320 321 322

	go func() {
		wg.Wait() // make sure all our children do finish.
		close(sendToPeers)
	}()

	err := bs.sendWantlistToPeers(ctx, sendToPeers)
	if err != nil {
323
		log.Debugf("sendWantlistToPeers error: %s", err)
324
	}
Jeromy's avatar
Jeromy committed
325 326
}

327
// TODO(brian): handle errors
Jeromy Johnson's avatar
Jeromy Johnson committed
328
func (bs *Bitswap) ReceiveMessage(ctx context.Context, p peer.ID, incoming bsmsg.BitSwapMessage) error {
329
	defer log.EventBegin(ctx, "receiveMessage", p, incoming).Done()
330

Jeromy's avatar
Jeromy committed
331 332
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
333
	bs.engine.MessageReceived(p, incoming)
Jeromy's avatar
Jeromy committed
334 335
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
336

Jeromy Johnson's avatar
Jeromy Johnson committed
337
	var keys []u.Key
Brian Tiger Chow's avatar
Brian Tiger Chow committed
338
	for _, block := range incoming.Blocks() {
339 340 341 342
		bs.blocksRecvd++
		if has, err := bs.blockstore.Has(block.Key()); err == nil && has {
			bs.dupBlocksRecvd++
		}
Jeromy Johnson's avatar
Jeromy Johnson committed
343
		log.Debugf("got block %s from %s", block, p)
344
		hasBlockCtx, cancel := context.WithTimeout(ctx, hasBlockTimeout)
345
		if err := bs.HasBlock(hasBlockCtx, block); err != nil {
Jeromy Johnson's avatar
Jeromy Johnson committed
346
			return fmt.Errorf("ReceiveMessage HasBlock error: %s", err)
Jeromy's avatar
Jeromy committed
347
		}
348
		cancel()
349
		keys = append(keys, block.Key())
350
	}
351

Jeromy's avatar
Jeromy committed
352 353
	bs.cancelBlocks(ctx, keys)
	return nil
354 355
}

356
// Connected/Disconnected warns bitswap about peer connections
357
func (bs *Bitswap) PeerConnected(p peer.ID) {
358
	// TODO: add to clientWorker??
359 360 361 362 363
	peers := make(chan peer.ID, 1)
	peers <- p
	close(peers)
	err := bs.sendWantlistToPeers(context.TODO(), peers)
	if err != nil {
364
		log.Debugf("error sending wantlist: %s", err)
365
	}
366 367 368
}

// Connected/Disconnected warns bitswap about peer connections
369
func (bs *Bitswap) PeerDisconnected(p peer.ID) {
370
	bs.engine.PeerDisconnected(p)
371 372
}

Jeromy's avatar
Jeromy committed
373
func (bs *Bitswap) cancelBlocks(ctx context.Context, bkeys []u.Key) {
374
	if len(bkeys) < 1 {
Jeromy's avatar
Jeromy committed
375
		return
376
	}
Jeromy's avatar
Jeromy committed
377 378 379
	message := bsmsg.New()
	message.SetFull(false)
	for _, k := range bkeys {
Jeromy Johnson's avatar
Jeromy Johnson committed
380
		log.Debug("cancel block: %s", k)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
381
		message.Cancel(k)
Jeromy's avatar
Jeromy committed
382
	}
Jeromy's avatar
Jeromy committed
383 384

	wg := sync.WaitGroup{}
385
	for _, p := range bs.engine.Peers() {
Jeromy's avatar
Jeromy committed
386 387 388 389 390 391 392 393 394
		wg.Add(1)
		go func(p peer.ID) {
			defer wg.Done()
			err := bs.send(ctx, p, message)
			if err != nil {
				log.Warningf("Error sending message: %s", err)
				return
			}
		}(p)
Jeromy's avatar
Jeromy committed
395
	}
Jeromy's avatar
Jeromy committed
396 397
	wg.Wait()
	return
Jeromy's avatar
Jeromy committed
398 399
}

400
func (bs *Bitswap) wantNewBlocks(ctx context.Context, bkeys []u.Key) {
401 402 403 404 405 406 407 408 409
	if len(bkeys) < 1 {
		return
	}

	message := bsmsg.New()
	message.SetFull(false)
	for i, k := range bkeys {
		message.AddEntry(k, kMaxPriority-i)
	}
410 411

	wg := sync.WaitGroup{}
412
	for _, p := range bs.engine.Peers() {
413
		wg.Add(1)
414
		go func(p peer.ID) {
415
			defer wg.Done()
416 417 418 419 420
			err := bs.send(ctx, p, message)
			if err != nil {
				log.Debugf("Error sending message: %s", err)
			}
		}(p)
421
	}
422 423 424 425 426 427 428 429
	done := make(chan struct{})
	go func() {
		wg.Wait()
		close(done)
	}()
	select {
	case <-done:
	case <-ctx.Done():
430 431 432
		// NB: we may be abandoning goroutines here before they complete
		// this shouldnt be an issue because they will complete soon anyways
		// we just don't want their being slow to impact bitswap transfer speeds
433
	}
434 435
}

436
func (bs *Bitswap) ReceiveError(err error) {
437
	log.Debugf("Bitswap ReceiveError: %s", err)
438 439
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
440 441
}

442 443
// send strives to ensure that accounting is always performed when a message is
// sent
444
func (bs *Bitswap) send(ctx context.Context, p peer.ID, m bsmsg.BitSwapMessage) error {
445
	defer log.EventBegin(ctx, "sendMessage", p, m).Done()
446
	if err := bs.network.SendMessage(ctx, p, m); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
447
		return err
448
	}
449
	return bs.engine.MessageSent(p, m)
450
}
451

452
func (bs *Bitswap) Close() error {
453
	return bs.process.Close()
454
}
455

456
func (bs *Bitswap) GetWantlist() []u.Key {
457 458 459 460 461 462
	var out []u.Key
	for _, e := range bs.wantlist.Entries() {
		out = append(out, e.Key)
	}
	return out
}