bitswap.go 11.4 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 (
6
	"fmt"
7
	"math"
8
	"sync"
Jeromy's avatar
Jeromy committed
9 10
	"time"

11
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
12

13
	blocks "github.com/jbenet/go-ipfs/blocks"
14
	blockstore "github.com/jbenet/go-ipfs/blocks/blockstore"
15
	exchange "github.com/jbenet/go-ipfs/exchange"
16
	decision "github.com/jbenet/go-ipfs/exchange/bitswap/decision"
17 18 19
	bsmsg "github.com/jbenet/go-ipfs/exchange/bitswap/message"
	bsnet "github.com/jbenet/go-ipfs/exchange/bitswap/network"
	notifications "github.com/jbenet/go-ipfs/exchange/bitswap/notifications"
20
	wantlist "github.com/jbenet/go-ipfs/exchange/bitswap/wantlist"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21
	peer "github.com/jbenet/go-ipfs/p2p/peer"
22
	u "github.com/jbenet/go-ipfs/util"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
23
	errors "github.com/jbenet/go-ipfs/util/debugerror"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
24
	"github.com/jbenet/go-ipfs/util/delay"
Jeromy's avatar
Jeromy committed
25
	eventlog "github.com/jbenet/go-ipfs/util/eventlog"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
26
	pset "github.com/jbenet/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
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
Brian Tiger Chow's avatar
Brian Tiger Chow committed
42
)
Jeromy's avatar
Jeromy committed
43

Brian Tiger Chow's avatar
Brian Tiger Chow committed
44
var (
Brian Tiger Chow's avatar
Brian Tiger Chow committed
45
	rebroadcastDelay = delay.Fixed(time.Second * 10)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
46
)
47

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

55 56
	ctx, cancelFunc := context.WithCancel(parent)

57 58
	notif := notifications.New()
	go func() {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
59
		<-ctx.Done()
Jeromy's avatar
Jeromy committed
60
		cancelFunc()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
61
		notif.Shutdown()
62 63
	}()

64
	bs := &bitswap{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65
		self:          p,
66
		blockstore:    bstore,
67
		cancelFunc:    cancelFunc,
68
		notifications: notif,
69
		engine:        decision.NewEngine(ctx, bstore),
70
		network:       network,
71
		wantlist:      wantlist.NewThreadSafe(),
Brian Tiger Chow's avatar
Brian Tiger Chow committed
72
		batchRequests: make(chan []u.Key, sizeBatchRequestChan),
73
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
74
	network.SetDelegate(bs)
75
	go bs.clientWorker(ctx)
Jeromy's avatar
Jeromy committed
76
	go bs.taskWorker(ctx)
77 78 79 80

	return bs
}

81 82 83
// bitswap instances implement the bitswap protocol.
type bitswap struct {

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84 85 86
	// the ID of the peer to act on behalf of
	self peer.ID

87 88
	// network delivers messages on behalf of the session
	network bsnet.BitSwapNetwork
89 90 91 92 93 94 95

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

	notifications notifications.PubSub

96 97 98 99
	// 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
	batchRequests chan []u.Key
Jeromy's avatar
Jeromy committed
100

101
	engine *decision.Engine
102

103
	wantlist *wantlist.ThreadSafe
104 105 106

	// cancelFunc signals cancellation to the bitswap event loop
	cancelFunc func()
107 108
}

109
// GetBlock attempts to retrieve a particular block from peers within the
110
// deadline enforced by the context.
Jeromy's avatar
Jeromy committed
111
func (bs *bitswap) GetBlock(parent context.Context, k u.Key) (*blocks.Block, error) {
112

113 114 115 116
	// 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
117 118
	// when this context's cancel func is executed. This is difficult to
	// enforce. May this comment keep you safe.
119

120
	ctx, cancelFunc := context.WithCancel(parent)
121

Jeromy's avatar
Jeromy committed
122
	ctx = eventlog.ContextWithLoggable(ctx, eventlog.Uuid("GetBlockRequest"))
123
	log.Event(ctx, "GetBlockRequestBegin", &k)
124 125 126 127 128

	defer func() {
		cancelFunc()
		log.Event(ctx, "GetBlockRequestEnd", &k)
	}()
129

130
	promise, err := bs.GetBlocks(ctx, []u.Key{k})
131 132
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
133
	}
134 135

	select {
136
	case block := <-promise:
Jeromy's avatar
Jeromy committed
137
		return block, nil
138 139
	case <-parent.Done():
		return nil, parent.Err()
140
	}
141

142 143
}

144 145 146 147 148 149 150
// 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)
Jeromy's avatar
Jeromy committed
151
func (bs *bitswap) GetBlocks(ctx context.Context, keys []u.Key) (<-chan *blocks.Block, error) {
152 153 154 155 156
	// TODO log the request

	promise := bs.notifications.Subscribe(ctx, keys...)
	select {
	case bs.batchRequests <- keys:
157
		return promise, nil
158 159 160
	case <-ctx.Done():
		return nil, ctx.Err()
	}
Jeromy's avatar
Jeromy committed
161 162
}

163 164 165 166 167 168 169 170
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
func (bs *bitswap) HasBlock(ctx context.Context, blk *blocks.Block) error {
	if err := bs.blockstore.Put(blk); err != nil {
		return err
	}
	bs.wantlist.Remove(blk.Key())
	bs.notifications.Publish(blk)
171
	return bs.network.Provide(ctx, blk.Key())
172 173
}

174 175 176 177 178 179 180 181 182 183 184 185 186
func (bs *bitswap) sendWantlistMsgToPeer(ctx context.Context, m bsmsg.BitSwapMessage, p peer.ID) error {
	logd := fmt.Sprintf("%s bitswap.sendWantlistMsgToPeer(%d, %s)", bs.self, len(m.Wantlist()), p)

	log.Debugf("%s sending wantlist", logd)
	if err := bs.send(ctx, p, m); err != nil {
		log.Errorf("%s send wantlist error: %s", logd, err)
		return err
	}
	log.Debugf("%s send wantlist success", logd)
	return nil
}

func (bs *bitswap) sendWantlistMsgToPeers(ctx context.Context, m bsmsg.BitSwapMessage, peers <-chan peer.ID) error {
Jeromy's avatar
Jeromy committed
187 188 189
	if peers == nil {
		panic("Cant send wantlist to nil peerchan")
	}
190 191 192 193 194 195

	logd := fmt.Sprintf("%s bitswap.sendWantlistMsgTo(%d)", bs.self, len(m.Wantlist()))
	log.Debugf("%s begin", logd)
	defer log.Debugf("%s end", logd)

	set := pset.New()
196
	wg := sync.WaitGroup{}
197
	for peerToQuery := range peers {
198
		log.Event(ctx, "PeerToQuery", peerToQuery)
199 200 201 202 203 204 205
		logd := fmt.Sprintf("%sto(%s)", logd, peerToQuery)

		if !set.TryAdd(peerToQuery) { //Do once per peer
			log.Debugf("%s skipped (already sent)", logd)
			continue
		}

206
		wg.Add(1)
207
		go func(p peer.ID) {
208
			defer wg.Done()
209
			bs.sendWantlistMsgToPeer(ctx, m, p)
210
		}(peerToQuery)
Jeromy's avatar
Jeromy committed
211
	}
212
	wg.Wait()
Jeromy's avatar
Jeromy committed
213 214 215
	return nil
}

216
func (bs *bitswap) sendWantlistToPeers(ctx context.Context, peers <-chan peer.ID) error {
Jeromy's avatar
Jeromy committed
217 218
	message := bsmsg.New()
	message.SetFull(true)
219 220
	for _, wanted := range bs.wantlist.Entries() {
		message.AddEntry(wanted.Key, wanted.Priority)
Jeromy's avatar
Jeromy committed
221
	}
222 223
	return bs.sendWantlistMsgToPeers(ctx, message, peers)
}
Jeromy's avatar
Jeromy committed
224

225 226 227 228 229 230 231 232 233 234
func (bs *bitswap) sendWantlistToProviders(ctx context.Context) {
	logd := fmt.Sprintf("%s bitswap.sendWantlistToProviders", bs.self)
	log.Debugf("%s begin", logd)
	defer log.Debugf("%s end", logd)

	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
235

236
	// Get providers for all entries in wantlist (could take a while)
Jeromy's avatar
Jeromy committed
237
	wg := sync.WaitGroup{}
238
	for _, e := range bs.wantlist.Entries() {
239
		wg.Add(1)
Jeromy's avatar
Jeromy committed
240
		go func(k u.Key) {
Jeromy's avatar
Jeromy committed
241
			defer wg.Done()
242 243 244 245

			logd := fmt.Sprintf("%s(entry: %s)", logd, k)
			log.Debugf("%s asking dht for providers", logd)

246
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
247
			providers := bs.network.FindProvidersAsync(child, k, maxProvidersPerRequest)
248
			for prov := range providers {
249 250
				log.Debugf("%s dht returned provider %s. send wantlist", logd, prov)
				sendToPeers <- prov
Jeromy's avatar
Jeromy committed
251
			}
252
		}(e.Key)
Jeromy's avatar
Jeromy committed
253
	}
254 255 256 257 258 259 260 261 262 263

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

	err := bs.sendWantlistToPeers(ctx, sendToPeers)
	if err != nil {
		log.Errorf("%s sendWantlistToPeers error: %s", logd, err)
	}
Jeromy's avatar
Jeromy committed
264 265
}

Jeromy's avatar
Jeromy committed
266
func (bs *bitswap) taskWorker(ctx context.Context) {
Jeromy's avatar
Jeromy committed
267 268 269 270
	for {
		select {
		case <-ctx.Done():
			return
271
		case envelope := <-bs.engine.Outbox():
272
			bs.send(ctx, envelope.Peer, envelope.Message)
Jeromy's avatar
Jeromy committed
273 274 275 276
		}
	}
}

277
// TODO ensure only one active request per key
278
func (bs *bitswap) clientWorker(parent context.Context) {
279 280

	ctx, cancel := context.WithCancel(parent)
Jeromy's avatar
Jeromy committed
281

Brian Tiger Chow's avatar
Brian Tiger Chow committed
282
	broadcastSignal := time.After(rebroadcastDelay.Get())
283
	defer cancel()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
284

Jeromy's avatar
Jeromy committed
285 286
	for {
		select {
287
		case <-broadcastSignal:
Jeromy's avatar
Jeromy committed
288
			// Resend unfulfilled wantlist keys
289
			bs.sendWantlistToProviders(ctx)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
290
			broadcastSignal = time.After(rebroadcastDelay.Get())
291
		case ks := <-bs.batchRequests:
292 293 294 295
			if len(ks) == 0 {
				log.Warning("Received batch request for zero blocks")
				continue
			}
296
			for i, k := range ks {
297
				bs.wantlist.Add(k, kMaxPriority-i)
298
			}
Jeromy's avatar
Jeromy committed
299 300 301 302 303 304 305
			// NB: send want list to providers for the first peer in this list.
			//		the assumption is made that the providers of the first key in
			//		the set are likely to have others as well.
			//		This currently holds true in most every situation, since when
			//		pinning a file, you store and provide all blocks associated with
			//		it. Later, this assumption may not hold as true if we implement
			//		newer bitswap strategies.
306
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
307
			providers := bs.network.FindProvidersAsync(child, ks[0], maxProvidersPerRequest)
308
			err := bs.sendWantlistToPeers(ctx, providers)
309 310
			if err != nil {
				log.Errorf("error sending wantlist: %s", err)
Jeromy's avatar
Jeromy committed
311
			}
312
		case <-parent.Done():
Jeromy's avatar
Jeromy committed
313 314 315 316 317
			return
		}
	}
}

318
// TODO(brian): handle errors
319 320
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.ID, incoming bsmsg.BitSwapMessage) (
	peer.ID, bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
321
	log.Debugf("ReceiveMessage from %s", p)
322

323
	if p == "" {
324
		log.Error("Received message from nil peer!")
325
		// TODO propagate the error upward
326
		return "", nil
327 328
	}
	if incoming == nil {
329
		log.Error("Got nil bitswap message!")
330
		// TODO propagate the error upward
331
		return "", nil
332
	}
333

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
340
	for _, block := range incoming.Blocks() {
341 342
		hasBlockCtx, _ := context.WithTimeout(ctx, hasBlockTimeout)
		if err := bs.HasBlock(hasBlockCtx, block); err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
343
			log.Error(err)
Jeromy's avatar
Jeromy committed
344
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
345
	}
346
	var keys []u.Key
Brian Tiger Chow's avatar
Brian Tiger Chow committed
347
	for _, block := range incoming.Blocks() {
348
		keys = append(keys, block.Key())
349
	}
350
	bs.cancelBlocks(ctx, keys)
351

Jeromy's avatar
Jeromy committed
352
	// TODO: consider changing this function to not return anything
353
	return "", nil
354 355
}

Jeromy's avatar
Jeromy committed
356
func (bs *bitswap) cancelBlocks(ctx context.Context, bkeys []u.Key) {
357 358 359
	if len(bkeys) < 1 {
		return
	}
Jeromy's avatar
Jeromy committed
360 361 362
	message := bsmsg.New()
	message.SetFull(false)
	for _, k := range bkeys {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
363
		message.Cancel(k)
Jeromy's avatar
Jeromy committed
364
	}
365
	for _, p := range bs.engine.Peers() {
Jeromy's avatar
Jeromy committed
366 367 368 369 370 371 372
		err := bs.send(ctx, p, message)
		if err != nil {
			log.Errorf("Error sending message: %s", err)
		}
	}
}

373
func (bs *bitswap) ReceiveError(err error) {
374
	log.Errorf("Bitswap ReceiveError: %s", err)
375 376
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
377 378
}

379 380
// send strives to ensure that accounting is always performed when a message is
// sent
381
func (bs *bitswap) send(ctx context.Context, p peer.ID, m bsmsg.BitSwapMessage) error {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
382
	log.Event(ctx, "DialPeer", p)
383
	err := bs.network.DialPeer(ctx, p)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
384 385 386
	if err != nil {
		return errors.Wrap(err)
	}
387
	if err := bs.network.SendMessage(ctx, p, m); err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
388
		return errors.Wrap(err)
389
	}
390
	return bs.engine.MessageSent(p, m)
391
}
392 393 394 395 396

func (bs *bitswap) Close() error {
	bs.cancelFunc()
	return nil // to conform to Closer interface
}