bitswap.go 10.7 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
		pm:            NewPeerManager(network),
95
	}
96
	go bs.pm.Run(ctx)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
97
	network.SetDelegate(bs)
98

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

104 105
// Bitswap instances implement the bitswap protocol.
type Bitswap struct {
106

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

110 111
	// network delivers messages on behalf of the session
	network bsnet.BitSwapNetwork
112

113 114 115 116
	// the peermanager manages sending messages to peers in a way that
	// wont block bitswap operation
	pm *PeerManager

117 118 119 120 121 122
	// blockstore is the local database
	// NB: ensure threadsafety
	blockstore blockstore.Blockstore

	notifications notifications.PubSub

123 124 125
	// 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
126
	batchRequests chan *blockRequest
Jeromy's avatar
Jeromy committed
127

128
	engine *decision.Engine
129

130
	wantlist *wantlist.ThreadSafe
131

132
	process process.Process
133 134

	newBlocks chan *blocks.Block
135 136

	provideKeys chan u.Key
137 138 139

	blocksRecvd    int
	dupBlocksRecvd int
140 141
}

142 143 144 145 146
type blockRequest struct {
	keys []u.Key
	ctx  context.Context
}

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

151 152 153 154
	// 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
155 156
	// when this context's cancel func is executed. This is difficult to
	// enforce. May this comment keep you safe.
157

158
	ctx, cancelFunc := context.WithCancel(parent)
159

Jeromy's avatar
Jeromy committed
160
	ctx = eventlog.ContextWithLoggable(ctx, eventlog.Uuid("GetBlockRequest"))
Jeromy's avatar
Jeromy committed
161
	defer log.EventBegin(ctx, "GetBlockRequest", &k).Done()
162 163 164 165

	defer func() {
		cancelFunc()
	}()
166

167
	promise, err := bs.GetBlocks(ctx, []u.Key{k})
168 169
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
170
	}
171 172

	select {
173 174 175 176 177 178 179 180 181
	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
182
		return block, nil
183 184
	case <-parent.Done():
		return nil, parent.Err()
185 186 187
	}
}

188 189 190 191 192 193 194 195
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
}

196 197 198 199 200 201 202
// 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)
203
func (bs *Bitswap) GetBlocks(ctx context.Context, keys []u.Key) (<-chan *blocks.Block, error) {
204 205 206 207 208
	select {
	case <-bs.process.Closing():
		return nil, errors.New("bitswap is closed")
	default:
	}
209
	promise := bs.notifications.Subscribe(ctx, keys...)
210 211 212 213 214

	req := &blockRequest{
		keys: keys,
		ctx:  ctx,
	}
215
	select {
216
	case bs.batchRequests <- req:
217
		return promise, nil
218 219 220
	case <-ctx.Done():
		return nil, ctx.Err()
	}
Jeromy's avatar
Jeromy committed
221 222
}

223 224
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
225
func (bs *Bitswap) HasBlock(ctx context.Context, blk *blocks.Block) error {
226 227 228 229 230
	select {
	case <-bs.process.Closing():
		return errors.New("bitswap is closed")
	default:
	}
231

232 233 234
	if err := bs.blockstore.Put(blk); err != nil {
		return err
	}
235

236 237
	bs.wantlist.Remove(blk.Key())
	bs.notifications.Publish(blk)
238 239 240 241 242 243
	select {
	case bs.newBlocks <- blk:
	case <-ctx.Done():
		return ctx.Err()
	}
	return nil
244 245
}

246
func (bs *Bitswap) sendWantlistMsgToPeers(ctx context.Context, m bsmsg.BitSwapMessage, peers <-chan peer.ID) error {
247 248
	set := pset.New()

249 250 251 252 253 254 255
loop:
	for {
		select {
		case peerToQuery, ok := <-peers:
			if !ok {
				break loop
			}
256

257 258
			if !set.TryAdd(peerToQuery) { //Do once per peer
				continue
259
			}
260

261
			bs.pm.Send(peerToQuery, m)
262 263 264 265
		case <-ctx.Done():
			return nil
		}
	}
Jeromy's avatar
Jeromy committed
266 267 268
	return nil
}

269
func (bs *Bitswap) sendWantlistToPeers(ctx context.Context, peers <-chan peer.ID) error {
270 271 272 273
	entries := bs.wantlist.Entries()
	if len(entries) == 0 {
		return nil
	}
Jeromy's avatar
Jeromy committed
274 275
	message := bsmsg.New()
	message.SetFull(true)
276
	for _, wanted := range entries {
277
		message.AddEntry(wanted.Key, wanted.Priority)
Jeromy's avatar
Jeromy committed
278
	}
279 280
	return bs.sendWantlistMsgToPeers(ctx, message, peers)
}
Jeromy's avatar
Jeromy committed
281

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

284 285 286 287 288
	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
289

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

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

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

	err := bs.sendWantlistToPeers(ctx, sendToPeers)
	if err != nil {
313
		log.Debugf("sendWantlistToPeers error: %s", err)
314
	}
Jeromy's avatar
Jeromy committed
315 316
}

317
// TODO(brian): handle errors
Jeromy Johnson's avatar
Jeromy Johnson committed
318
func (bs *Bitswap) ReceiveMessage(ctx context.Context, p peer.ID, incoming bsmsg.BitSwapMessage) error {
Jeromy's avatar
Jeromy committed
319 320
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
321
	bs.engine.MessageReceived(p, incoming)
Jeromy's avatar
Jeromy committed
322 323
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
324

Jeromy Johnson's avatar
Jeromy Johnson committed
325
	var keys []u.Key
Brian Tiger Chow's avatar
Brian Tiger Chow committed
326
	for _, block := range incoming.Blocks() {
327 328 329 330
		bs.blocksRecvd++
		if has, err := bs.blockstore.Has(block.Key()); err == nil && has {
			bs.dupBlocksRecvd++
		}
Jeromy Johnson's avatar
Jeromy Johnson committed
331
		log.Debugf("got block %s from %s", block, p)
332
		hasBlockCtx, cancel := context.WithTimeout(ctx, hasBlockTimeout)
333
		if err := bs.HasBlock(hasBlockCtx, block); err != nil {
Jeromy Johnson's avatar
Jeromy Johnson committed
334
			return fmt.Errorf("ReceiveMessage HasBlock error: %s", err)
Jeromy's avatar
Jeromy committed
335
		}
336
		cancel()
337
		keys = append(keys, block.Key())
338
	}
339

Jeromy's avatar
Jeromy committed
340 341
	bs.cancelBlocks(ctx, keys)
	return nil
342 343
}

344
// Connected/Disconnected warns bitswap about peer connections
345
func (bs *Bitswap) PeerConnected(p peer.ID) {
346
	// TODO: add to clientWorker??
347
	bs.pm.Connected(p)
348 349 350 351 352
	peers := make(chan peer.ID, 1)
	peers <- p
	close(peers)
	err := bs.sendWantlistToPeers(context.TODO(), peers)
	if err != nil {
353
		log.Debugf("error sending wantlist: %s", err)
354
	}
355 356 357
}

// Connected/Disconnected warns bitswap about peer connections
358
func (bs *Bitswap) PeerDisconnected(p peer.ID) {
359
	bs.pm.Disconnected(p)
360
	bs.engine.PeerDisconnected(p)
361 362
}

Jeromy's avatar
Jeromy committed
363
func (bs *Bitswap) cancelBlocks(ctx context.Context, bkeys []u.Key) {
364
	if len(bkeys) < 1 {
Jeromy's avatar
Jeromy committed
365
		return
366
	}
Jeromy's avatar
Jeromy committed
367 368 369
	message := bsmsg.New()
	message.SetFull(false)
	for _, k := range bkeys {
Jeromy Johnson's avatar
Jeromy Johnson committed
370
		log.Debug("cancel block: %s", k)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
371
		message.Cancel(k)
Jeromy's avatar
Jeromy committed
372
	}
Jeromy's avatar
Jeromy committed
373

374
	bs.pm.Broadcast(message)
Jeromy's avatar
Jeromy committed
375
	return
Jeromy's avatar
Jeromy committed
376 377
}

378
func (bs *Bitswap) wantNewBlocks(ctx context.Context, bkeys []u.Key) {
379 380 381 382 383 384 385 386 387
	if len(bkeys) < 1 {
		return
	}

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

389
	bs.pm.Broadcast(message)
390 391
}

392
func (bs *Bitswap) ReceiveError(err error) {
393
	log.Debugf("Bitswap ReceiveError: %s", err)
394 395
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
396 397
}

398
func (bs *Bitswap) Close() error {
399
	return bs.process.Close()
400
}
401

402
func (bs *Bitswap) GetWantlist() []u.Key {
403 404 405 406 407 408
	var out []u.Key
	for _, e := range bs.wantlist.Entries() {
		out = append(out, e.Key)
	}
	return out
}