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"
7
	"math"
8
	"sync"
Jeromy's avatar
Jeromy committed
9 10
	"time"

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
	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
26 27
)

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
30
const (
Brian Tiger Chow's avatar
Brian Tiger Chow committed
31 32 33
	// 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
34 35 36 37
	// TODO: if a 'non-nice' strategy is implemented, consider increasing this value
	maxProvidersPerRequest = 3
	providerRequestTimeout = time.Second * 10
	hasBlockTimeout        = time.Second * 15
38
	provideTimeout         = time.Second * 15
Brian Tiger Chow's avatar
Brian Tiger Chow committed
39
	sizeBatchRequestChan   = 32
40 41
	// kMaxPriority is the max priority as defined by the bitswap protocol
	kMaxPriority = math.MaxInt32
42

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

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
51 52 53 54
// 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.
55
func New(parent context.Context, p peer.ID, network bsnet.BitSwapNetwork,
56
	bstore blockstore.Blockstore, nice bool) exchange.Interface {
57

58 59 60 61 62 63 64
	// 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
65 66
	ctx, cancelFunc := context.WithCancel(parent)

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

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

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

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

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

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

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

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

	notifications notifications.PubSub

116 117 118
	// 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
119
	batchRequests chan *blockRequest
Jeromy's avatar
Jeromy committed
120

121
	engine *decision.Engine
122

123
	wantlist *wantlist.ThreadSafe
124

125
	process process.Process
126 127

	newBlocks chan *blocks.Block
128 129

	provideKeys chan u.Key
130 131
}

132 133 134 135 136
type blockRequest struct {
	keys []u.Key
	ctx  context.Context
}

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

141 142 143 144
	// 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
145 146
	// when this context's cancel func is executed. This is difficult to
	// enforce. May this comment keep you safe.
147

148
	ctx, cancelFunc := context.WithCancel(parent)
149

Jeromy's avatar
Jeromy committed
150
	ctx = eventlog.ContextWithLoggable(ctx, eventlog.Uuid("GetBlockRequest"))
Jeromy's avatar
Jeromy committed
151
	defer log.EventBegin(ctx, "GetBlockRequest", &k).Done()
152 153 154 155

	defer func() {
		cancelFunc()
	}()
156

157
	promise, err := bs.GetBlocks(ctx, []u.Key{k})
158 159
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
160
	}
161 162

	select {
163 164 165 166 167 168 169 170 171
	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
172
		return block, nil
173 174
	case <-parent.Done():
		return nil, parent.Err()
175 176 177
	}
}

178 179 180 181 182 183 184 185
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
}

186 187 188 189 190 191 192
// 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)
193
func (bs *Bitswap) GetBlocks(ctx context.Context, keys []u.Key) (<-chan *blocks.Block, error) {
194 195 196 197 198
	select {
	case <-bs.process.Closing():
		return nil, errors.New("bitswap is closed")
	default:
	}
199
	promise := bs.notifications.Subscribe(ctx, keys...)
200 201 202 203 204

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

213 214
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
215
func (bs *Bitswap) HasBlock(ctx context.Context, blk *blocks.Block) error {
216
	log.Event(ctx, "hasBlock", blk)
217 218 219 220 221
	select {
	case <-bs.process.Closing():
		return errors.New("bitswap is closed")
	default:
	}
222 223 224 225 226
	if err := bs.blockstore.Put(blk); err != nil {
		return err
	}
	bs.wantlist.Remove(blk.Key())
	bs.notifications.Publish(blk)
227 228 229 230 231 232
	select {
	case bs.newBlocks <- blk:
	case <-ctx.Done():
		return ctx.Err()
	}
	return nil
233 234
}

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

239 240 241 242 243 244 245
loop:
	for {
		select {
		case peerToQuery, ok := <-peers:
			if !ok {
				break loop
			}
246

247 248
			if !set.TryAdd(peerToQuery) { //Do once per peer
				continue
249
			}
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

			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():
271 272 273
		// 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
274 275 276 277
	}
	return nil
}

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

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

289 290 291 292 293
	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
294

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

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

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

	err := bs.sendWantlistToPeers(ctx, sendToPeers)
	if err != nil {
318
		log.Debugf("sendWantlistToPeers error: %s", err)
319
	}
Jeromy's avatar
Jeromy committed
320 321
}

322
// TODO(brian): handle errors
323
func (bs *Bitswap) ReceiveMessage(ctx context.Context, p peer.ID, incoming bsmsg.BitSwapMessage) (
324
	peer.ID, bsmsg.BitSwapMessage) {
325
	defer log.EventBegin(ctx, "receiveMessage", p, incoming).Done()
326

327
	if p == "" {
328
		log.Debug("Received message from nil peer!")
329
		// TODO propagate the error upward
330
		return "", nil
331 332
	}
	if incoming == nil {
333
		log.Debug("Got nil bitswap message!")
334
		// TODO propagate the error upward
335
		return "", nil
336
	}
337

Jeromy's avatar
Jeromy committed
338 339
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
340
	bs.engine.MessageReceived(p, incoming)
Jeromy's avatar
Jeromy committed
341 342
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
343

Brian Tiger Chow's avatar
Brian Tiger Chow committed
344
	for _, block := range incoming.Blocks() {
345
		hasBlockCtx, cancel := context.WithTimeout(ctx, hasBlockTimeout)
346
		if err := bs.HasBlock(hasBlockCtx, block); err != nil {
347
			log.Debug(err)
Jeromy's avatar
Jeromy committed
348
		}
349
		cancel()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
350
	}
351

352
	var keys []u.Key
Brian Tiger Chow's avatar
Brian Tiger Chow committed
353
	for _, block := range incoming.Blocks() {
354
		keys = append(keys, block.Key())
355
	}
356
	bs.cancelBlocks(ctx, keys)
357

Jeromy's avatar
Jeromy committed
358
	// TODO: consider changing this function to not return anything
359
	return "", nil
360 361
}

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

// Connected/Disconnected warns bitswap about peer connections
375
func (bs *Bitswap) PeerDisconnected(p peer.ID) {
376
	bs.engine.PeerDisconnected(p)
377 378
}

379
func (bs *Bitswap) cancelBlocks(ctx context.Context, bkeys []u.Key) {
380 381 382
	if len(bkeys) < 1 {
		return
	}
Jeromy's avatar
Jeromy committed
383 384 385
	message := bsmsg.New()
	message.SetFull(false)
	for _, k := range bkeys {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
386
		message.Cancel(k)
Jeromy's avatar
Jeromy committed
387
	}
388
	for _, p := range bs.engine.Peers() {
Jeromy's avatar
Jeromy committed
389 390
		err := bs.send(ctx, p, message)
		if err != nil {
391
			log.Debugf("Error sending message: %s", err)
Jeromy's avatar
Jeromy committed
392 393 394 395
		}
	}
}

396
func (bs *Bitswap) wantNewBlocks(ctx context.Context, bkeys []u.Key) {
397 398 399 400 401 402 403 404 405
	if len(bkeys) < 1 {
		return
	}

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

	wg := sync.WaitGroup{}
408
	for _, p := range bs.engine.Peers() {
409
		wg.Add(1)
410
		go func(p peer.ID) {
411
			defer wg.Done()
412 413 414 415 416
			err := bs.send(ctx, p, message)
			if err != nil {
				log.Debugf("Error sending message: %s", err)
			}
		}(p)
417
	}
418 419 420 421 422 423 424 425
	done := make(chan struct{})
	go func() {
		wg.Wait()
		close(done)
	}()
	select {
	case <-done:
	case <-ctx.Done():
426 427 428
		// 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
429
	}
430 431
}

432
func (bs *Bitswap) ReceiveError(err error) {
433
	log.Debugf("Bitswap ReceiveError: %s", err)
434 435
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
436 437
}

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

448
func (bs *Bitswap) Close() error {
449
	return bs.process.Close()
450
}
451

452
func (bs *Bitswap) GetWantlist() []u.Key {
453 454 455 456 457 458
	var out []u.Key
	for _, e := range bs.wantlist.Entries() {
		out = append(out, e.Key)
	}
	return out
}