bitswap.go 10.5 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,
Jeromy's avatar
Jeromy committed
59
		ledgermanager: strategy.NewLedgerManager(bstore, ctx),
60
		routing:       routing,
Brian Tiger Chow's avatar
Brian Tiger Chow committed
61
		sender:        network,
62
		wantlist:      wl.New(),
63
		batchRequests: make(chan []u.Key, 32),
64
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
65
	network.SetDelegate(bs)
66
	go bs.clientWorker(ctx)
Jeromy's avatar
Jeromy committed
67
	go bs.roundWorker(ctx)
68 69 70 71

	return bs
}

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

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

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

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

85
	notifications notifications.PubSub
86

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

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

Jeromy's avatar
Jeromy committed
95
	ledgermanager *strategy.LedgerManager
96

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

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

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

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

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

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

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

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

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

136 137
}

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

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

157 158 159 160 161 162 163 164 165 166 167 168
// 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
169
func (bs *bitswap) sendWantListTo(ctx context.Context, peers <-chan peer.Peer) error {
Jeromy's avatar
Jeromy committed
170 171 172
	if peers == nil {
		panic("Cant send wantlist to nil peerchan")
	}
Jeromy's avatar
Jeromy committed
173
	message := bsmsg.New()
Jeromy's avatar
Jeromy committed
174 175
	for _, wanted := range bs.wantlist.Entries() {
		message.AddEntry(wanted.Value, wanted.Priority, false)
Jeromy's avatar
Jeromy committed
176
	}
177
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
178
	for peerToQuery := range peers {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
179
		log.Event(ctx, "PeerToQuery", peerToQuery)
180
		wg.Add(1)
Jeromy's avatar
Jeromy committed
181
		go func(p peer.Peer) {
182
			defer wg.Done()
Jeromy's avatar
Jeromy committed
183

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

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

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

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

	ps := pset.NewPeerSet()

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

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

Jeromy's avatar
Jeromy committed
237 238 239 240 241
func (bs *bitswap) roundWorker(ctx context.Context) {
	for {
		select {
		case <-ctx.Done():
			return
Jeromy's avatar
Jeromy committed
242 243
		case task := <-bs.ledgermanager.GetTaskChan():
			block, err := bs.blockstore.Get(task.Key)
Jeromy's avatar
Jeromy committed
244
			if err != nil {
Jeromy's avatar
Jeromy committed
245 246
				log.Errorf("Expected to have block %s, but it was not found!", task.Key)
				continue
247
			}
Jeromy's avatar
Jeromy committed
248 249 250

			message := bsmsg.New()
			message.AddBlock(block)
Jeromy's avatar
Jeromy committed
251 252 253
			// TODO: maybe add keys from our wantlist?

			bs.send(ctx, task.Target, message)
Jeromy's avatar
Jeromy committed
254 255 256 257
		}
	}
}

258
// TODO ensure only one active request per key
259
func (bs *bitswap) clientWorker(parent context.Context) {
260 261

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

263 264
	broadcastSignal := time.After(rebroadcastDelay)
	defer cancel()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
265

Jeromy's avatar
Jeromy committed
266 267
	for {
		select {
268
		case <-broadcastSignal:
Jeromy's avatar
Jeromy committed
269
			// Resend unfulfilled wantlist keys
Jeromy's avatar
Jeromy committed
270
			bs.sendWantlistToProviders(ctx, bs.wantlist)
271
			broadcastSignal = time.After(rebroadcastDelay)
272
		case ks := <-bs.batchRequests:
273 274 275 276
			if len(ks) == 0 {
				log.Warning("Received batch request for zero blocks")
				continue
			}
277 278
			for i, k := range ks {
				bs.wantlist.Add(k, len(ks)-i)
279
			}
Jeromy's avatar
Jeromy committed
280 281 282 283 284 285 286
			// 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.
287 288
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
			providers := bs.routing.FindProvidersAsync(child, ks[0], maxProvidersPerRequest)
289 290 291 292

			err := bs.sendWantListTo(ctx, providers)
			if err != nil {
				log.Errorf("error sending wantlist: %s", err)
Jeromy's avatar
Jeromy committed
293
			}
294
		case <-parent.Done():
Jeromy's avatar
Jeromy committed
295 296 297 298 299
			return
		}
	}
}

300
// TODO(brian): handle errors
301 302
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
303
	log.Debugf("ReceiveMessage from %s", p)
304

305
	if p == nil {
306
		log.Error("Received message from nil peer!")
307 308
		// TODO propagate the error upward
		return nil, nil
309 310
	}
	if incoming == nil {
311
		log.Error("Got nil bitswap message!")
312 313
		// TODO propagate the error upward
		return nil, nil
314
	}
315

Jeromy's avatar
Jeromy committed
316 317
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
Jeromy's avatar
Jeromy committed
318
	bs.ledgermanager.MessageReceived(p, incoming)
Jeromy's avatar
Jeromy committed
319 320
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
321

Jeromy's avatar
Jeromy committed
322
	var blkeys []u.Key
Brian Tiger Chow's avatar
Brian Tiger Chow committed
323
	for _, block := range incoming.Blocks() {
Jeromy's avatar
Jeromy committed
324
		blkeys = append(blkeys, block.Key())
Brian Tiger Chow's avatar
Brian Tiger Chow committed
325 326
		if err := bs.HasBlock(ctx, block); err != nil {
			log.Error(err)
Jeromy's avatar
Jeromy committed
327
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
328
	}
Jeromy's avatar
Jeromy committed
329 330
	if len(blkeys) > 0 {
		bs.cancelBlocks(ctx, blkeys)
331
	}
332

Jeromy's avatar
Jeromy committed
333
	// TODO: consider changing this function to not return anything
334
	return nil, nil
335 336
}

Jeromy's avatar
Jeromy committed
337 338 339 340 341 342
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)
	}
Jeromy's avatar
Jeromy committed
343
	for _, p := range bs.ledgermanager.Peers() {
Jeromy's avatar
Jeromy committed
344 345 346 347 348 349 350
		err := bs.send(ctx, p, message)
		if err != nil {
			log.Errorf("Error sending message: %s", err)
		}
	}
}

351
func (bs *bitswap) ReceiveError(err error) {
352
	log.Errorf("Bitswap ReceiveError: %s", err)
353 354
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
355
}
356

357 358
// send strives to ensure that accounting is always performed when a message is
// sent
359 360 361 362
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
	}
Jeromy's avatar
Jeromy committed
363
	return bs.ledgermanager.MessageSent(p, m)
364
}
365 366 367 368 369

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