bitswap.go 10.8 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.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
3 4 5
package bitswap

import (
6
	"sync"
Jeromy's avatar
Jeromy committed
7 8
	"time"

9
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
10

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11
	blocks "github.com/jbenet/go-ipfs/blocks"
12
	blockstore "github.com/jbenet/go-ipfs/blocks/blockstore"
13 14 15 16 17
	exchange "github.com/jbenet/go-ipfs/exchange"
	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"
	strategy "github.com/jbenet/go-ipfs/exchange/bitswap/strategy"
Jeromy's avatar
Jeromy committed
18
	wl "github.com/jbenet/go-ipfs/exchange/bitswap/wantlist"
19
	peer "github.com/jbenet/go-ipfs/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20
	u "github.com/jbenet/go-ipfs/util"
Jeromy's avatar
Jeromy committed
21
	eventlog "github.com/jbenet/go-ipfs/util/eventlog"
Jeromy's avatar
Jeromy committed
22
	pset "github.com/jbenet/go-ipfs/util/peerset"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
23 24
)

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

Jeromy's avatar
Jeromy committed
27
// Number of providers to request for sending a wantlist to
Jeromy's avatar
Jeromy committed
28 29
// TODO: if a 'non-nice' strategy is implemented, consider increasing this value
const maxProvidersPerRequest = 3
Jeromy's avatar
Jeromy committed
30

31 32 33
var providerRequestTimeout = time.Second * 10
var hasBlockTimeout = time.Second * 15
var rebroadcastDelay = time.Second * 10
34

Jeromy's avatar
Jeromy committed
35 36
const roundTime = time.Second / 2

37 38
var bandwidthPerRound = 500000

39 40 41
// New initializes a BitSwap instance that communicates over the
// provided BitSwapNetwork. This function registers the returned instance as
// the network delegate.
42
// Runs until context is cancelled
43
func New(parent context.Context, p peer.Peer, network bsnet.BitSwapNetwork, routing bsnet.Routing,
44
	bstore blockstore.Blockstore, nice bool) exchange.Interface {
45

46 47
	ctx, cancelFunc := context.WithCancel(parent)

48 49
	notif := notifications.New()
	go func() {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
50
		<-ctx.Done()
Jeromy's avatar
Jeromy committed
51
		cancelFunc()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
52
		notif.Shutdown()
53 54
	}()

55
	bs := &bitswap{
56
		blockstore:    bstore,
57
		cancelFunc:    cancelFunc,
58
		notifications: notif,
59
		strategy:      strategy.New(nice),
60
		ledgerset:     strategy.NewLedgerSet(),
61
		routing:       routing,
Brian Tiger Chow's avatar
Brian Tiger Chow committed
62
		sender:        network,
63
		wantlist:      wl.New(),
64
		batchRequests: make(chan []u.Key, 32),
65
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
66
	network.SetDelegate(bs)
67
	go bs.clientWorker(ctx)
Jeromy's avatar
Jeromy committed
68
	go bs.roundWorker(ctx)
69 70 71 72

	return bs
}

73 74
// bitswap instances implement the bitswap protocol.
type bitswap struct {
75

76
	// sender delivers messages on behalf of the session
77
	sender bsnet.BitSwapNetwork
78

79
	// blockstore is the local database
80
	// NB: ensure threadsafety
81
	blockstore blockstore.Blockstore
82

83
	// routing interface for communication
84
	routing bsnet.Routing
85

86
	notifications notifications.PubSub
87

88 89 90 91
	// 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
92

93
	// strategy makes decisions about how to interact with partners.
94
	strategy strategy.Strategy
95

96 97
	ledgerset *strategy.LedgerSet

Jeromy's avatar
Jeromy committed
98
	wantlist *wl.Wantlist
99 100 101

	// cancelFunc signals cancellation to the bitswap event loop
	cancelFunc func()
102 103
}

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

108 109 110 111
	// 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
112 113
	// when this context's cancel func is executed. This is difficult to
	// enforce. May this comment keep you safe.
114

115
	ctx, cancelFunc := context.WithCancel(parent)
116

Jeromy's avatar
Jeromy committed
117
	ctx = eventlog.ContextWithLoggable(ctx, eventlog.Uuid("GetBlockRequest"))
118
	log.Event(ctx, "GetBlockRequestBegin", &k)
119 120 121 122 123

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

125
	promise, err := bs.GetBlocks(ctx, []u.Key{k})
126 127
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
128
	}
129 130

	select {
131
	case block := <-promise:
Jeromy's avatar
Jeromy committed
132
		return block, nil
133 134
	case <-parent.Done():
		return nil, parent.Err()
135
	}
136

137 138
}

139 140 141 142 143 144 145
// 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
146
func (bs *bitswap) GetBlocks(ctx context.Context, keys []u.Key) (<-chan *blocks.Block, error) {
147 148 149 150 151
	// TODO log the request

	promise := bs.notifications.Subscribe(ctx, keys...)
	select {
	case bs.batchRequests <- keys:
152
		return promise, nil
153 154 155
	case <-ctx.Done():
		return nil, ctx.Err()
	}
Jeromy's avatar
Jeromy committed
156 157
}

158 159 160 161 162 163 164 165 166 167 168 169
// 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)
	child, _ := context.WithTimeout(ctx, hasBlockTimeout)
	return bs.routing.Provide(child, blk.Key())
}

Jeromy's avatar
Jeromy committed
170
func (bs *bitswap) sendWantListTo(ctx context.Context, peers <-chan peer.Peer) error {
Jeromy's avatar
Jeromy committed
171 172 173
	if peers == nil {
		panic("Cant send wantlist to nil peerchan")
	}
Jeromy's avatar
Jeromy committed
174
	message := bsmsg.New()
Jeromy's avatar
Jeromy committed
175 176
	for _, wanted := range bs.wantlist.Entries() {
		message.AddEntry(wanted.Value, wanted.Priority, false)
Jeromy's avatar
Jeromy committed
177
	}
178
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
179
	for peerToQuery := range peers {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
180
		log.Event(ctx, "PeerToQuery", peerToQuery)
181
		wg.Add(1)
Jeromy's avatar
Jeromy committed
182
		go func(p peer.Peer) {
183
			defer wg.Done()
Jeromy's avatar
Jeromy committed
184

Brian Tiger Chow's avatar
Brian Tiger Chow committed
185
			log.Event(ctx, "DialPeer", p)
Jeromy's avatar
Jeromy committed
186 187
			err := bs.sender.DialPeer(ctx, p)
			if err != nil {
188
				log.Errorf("Error sender.DialPeer(%s): %s", p, err)
Jeromy's avatar
Jeromy committed
189 190 191
				return
			}

192
			err = bs.sender.SendMessage(ctx, p, message)
Jeromy's avatar
Jeromy committed
193
			if err != nil {
194
				log.Errorf("Error sender.SendMessage(%s) = %s", p, err)
Jeromy's avatar
Jeromy committed
195 196 197 198 199
				return
			}
			// FIXME ensure accounting is handled correctly when
			// communication fails. May require slightly different API to
			// get better guarantees. May need shared sequence numbers.
200
			bs.ledgerset.MessageSent(p, message)
Jeromy's avatar
Jeromy committed
201 202
		}(peerToQuery)
	}
203
	wg.Wait()
Jeromy's avatar
Jeromy committed
204 205 206
	return nil
}

Jeromy's avatar
Jeromy committed
207
func (bs *bitswap) sendWantlistToProviders(ctx context.Context, wantlist *wl.Wantlist) {
208 209 210
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

Jeromy's avatar
Jeromy committed
211 212 213 214 215 216 217 218
	message := bsmsg.New()
	message.SetFull(true)
	for _, e := range bs.wantlist.Entries() {
		message.AddEntry(e.Value, e.Priority, false)
	}

	ps := pset.NewPeerSet()

219
	// Get providers for all entries in wantlist (could take a while)
Jeromy's avatar
Jeromy committed
220
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
221
	for _, e := range wantlist.Entries() {
222
		wg.Add(1)
Jeromy's avatar
Jeromy committed
223
		go func(k u.Key) {
Jeromy's avatar
Jeromy committed
224
			defer wg.Done()
225 226
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
			providers := bs.routing.FindProvidersAsync(child, k, maxProvidersPerRequest)
Jeromy's avatar
Jeromy committed
227

228
			for prov := range providers {
Jeromy's avatar
Jeromy committed
229 230 231
				if ps.AddIfSmallerThan(prov, -1) { //Do once per peer
					bs.send(ctx, prov, message)
				}
Jeromy's avatar
Jeromy committed
232
			}
Jeromy's avatar
Jeromy committed
233
		}(e.Value)
Jeromy's avatar
Jeromy committed
234
	}
Jeromy's avatar
Jeromy committed
235
	wg.Wait()
Jeromy's avatar
Jeromy committed
236 237
}

Jeromy's avatar
Jeromy committed
238 239 240 241 242 243 244
func (bs *bitswap) roundWorker(ctx context.Context) {
	roundTicker := time.NewTicker(roundTime)
	for {
		select {
		case <-ctx.Done():
			return
		case <-roundTicker.C:
245
			alloc, err := bs.strategy.GetTasks(bandwidthPerRound, bs.ledgerset, bs.blockstore)
Jeromy's avatar
Jeromy committed
246 247 248
			if err != nil {
				log.Critical("%s", err)
			}
249 250 251 252
			err = bs.processStrategyAllocation(ctx, alloc)
			if err != nil {
				log.Critical("Error processing strategy allocation: %s", err)
			}
Jeromy's avatar
Jeromy committed
253 254 255 256
		}
	}
}

257
func (bs *bitswap) processStrategyAllocation(ctx context.Context, alloc []*strategy.Task) error {
Jeromy's avatar
Jeromy committed
258 259 260 261 262
	for _, t := range alloc {
		for _, block := range t.Blocks {
			message := bsmsg.New()
			message.AddBlock(block)
			if err := bs.send(ctx, t.Peer, message); err != nil {
263
				return err
Jeromy's avatar
Jeromy committed
264 265 266
			}
		}
	}
267
	return nil
Jeromy's avatar
Jeromy committed
268 269
}

270
// TODO ensure only one active request per key
271
func (bs *bitswap) clientWorker(parent context.Context) {
272 273

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

275 276
	broadcastSignal := time.After(rebroadcastDelay)
	defer cancel()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
277

Jeromy's avatar
Jeromy committed
278 279
	for {
		select {
280
		case <-broadcastSignal:
Jeromy's avatar
Jeromy committed
281
			// Resend unfulfilled wantlist keys
Jeromy's avatar
Jeromy committed
282
			bs.sendWantlistToProviders(ctx, bs.wantlist)
283
			broadcastSignal = time.After(rebroadcastDelay)
284
		case ks := <-bs.batchRequests:
285 286 287 288
			if len(ks) == 0 {
				log.Warning("Received batch request for zero blocks")
				continue
			}
289 290
			for i, k := range ks {
				bs.wantlist.Add(k, len(ks)-i)
291
			}
Jeromy's avatar
Jeromy committed
292 293 294 295 296 297 298
			// 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.
299 300
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
			providers := bs.routing.FindProvidersAsync(child, ks[0], maxProvidersPerRequest)
301 302 303 304

			err := bs.sendWantListTo(ctx, providers)
			if err != nil {
				log.Errorf("error sending wantlist: %s", err)
Jeromy's avatar
Jeromy committed
305
			}
306
		case <-parent.Done():
Jeromy's avatar
Jeromy committed
307 308 309 310 311
			return
		}
	}
}

312
// TODO(brian): handle errors
313 314
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
315
	log.Debugf("ReceiveMessage from %s", p)
316

317
	if p == nil {
318
		log.Error("Received message from nil peer!")
319 320
		// TODO propagate the error upward
		return nil, nil
321 322
	}
	if incoming == nil {
323
		log.Error("Got nil bitswap message!")
324 325
		// TODO propagate the error upward
		return nil, nil
326
	}
327

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

Jeromy's avatar
Jeromy committed
334
	var blkeys []u.Key
Brian Tiger Chow's avatar
Brian Tiger Chow committed
335
	for _, block := range incoming.Blocks() {
Jeromy's avatar
Jeromy committed
336
		blkeys = append(blkeys, block.Key())
Brian Tiger Chow's avatar
Brian Tiger Chow committed
337 338
		if err := bs.HasBlock(ctx, block); err != nil {
			log.Error(err)
Jeromy's avatar
Jeromy committed
339
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
340
	}
Jeromy's avatar
Jeromy committed
341 342
	if len(blkeys) > 0 {
		bs.cancelBlocks(ctx, blkeys)
343
	}
344

Jeromy's avatar
Jeromy committed
345
	// TODO: consider changing this function to not return anything
346
	return nil, nil
347 348
}

Jeromy's avatar
Jeromy committed
349 350 351 352 353 354
func (bs *bitswap) cancelBlocks(ctx context.Context, bkeys []u.Key) {
	message := bsmsg.New()
	message.SetFull(false)
	for _, k := range bkeys {
		message.AddEntry(k, 0, true)
	}
355
	for _, p := range bs.ledgerset.Peers() {
Jeromy's avatar
Jeromy committed
356 357 358 359 360 361 362
		err := bs.send(ctx, p, message)
		if err != nil {
			log.Errorf("Error sending message: %s", err)
		}
	}
}

363
func (bs *bitswap) ReceiveError(err error) {
364
	log.Errorf("Bitswap ReceiveError: %s", err)
365 366
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
367
}
368

369 370
// send strives to ensure that accounting is always performed when a message is
// sent
371 372 373 374
func (bs *bitswap) send(ctx context.Context, p peer.Peer, m bsmsg.BitSwapMessage) error {
	if err := bs.sender.SendMessage(ctx, p, m); err != nil {
		return err
	}
375
	return bs.ledgerset.MessageSent(p, m)
376
}
377 378 379 380 381

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