bitswap.go 10.2 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
	"sync"
Jeromy's avatar
Jeromy committed
7 8
	"time"

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

	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 20
	peer "github.com/jbenet/go-ipfs/peer"
	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"
23 24
)

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
27 28 29 30 31 32 33
const (
	// Number of providers to request for sending a wantlist to
	// TODO: if a 'non-nice' strategy is implemented, consider increasing this value
	maxProvidersPerRequest = 3
	providerRequestTimeout = time.Second * 10
	hasBlockTimeout        = time.Second * 15
)
Jeromy's avatar
Jeromy committed
34

Brian Tiger Chow's avatar
Brian Tiger Chow committed
35 36 37
var (
	rebroadcastDelay = time.Second * 10
)
38

Brian Tiger Chow's avatar
Brian Tiger Chow committed
39 40 41 42
// 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.
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.taskWorker(ctx)
68 69 70 71

	return bs
}

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

	// sender delivers messages on behalf of the session
76
	sender bsnet.BitSwapNetwork
77 78 79 80 81 82

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

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

	notifications notifications.PubSub

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.
Jeromy's avatar
Jeromy committed
93 94
	// TODO: strategy commented out until we have a use for it again
	//strategy strategy.Strategy
95

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

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
// 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)
166
	return bs.routing.Provide(ctx, blk.Key())
167 168
}

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
	for _, wanted := range bs.wantlist.Entries() {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
175
		message.AddEntry(wanted.Value, wanted.Priority)
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
	message := bsmsg.New()
	message.SetFull(true)
	for _, e := range bs.wantlist.Entries() {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
213
		message.AddEntry(e.Value, e.Priority)
Jeromy's avatar
Jeromy committed
214 215 216 217
	}

	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
				if ps.TryAdd(prov) { //Do once per peer
Jeromy's avatar
Jeromy committed
229 230
					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
func (bs *bitswap) taskWorker(ctx context.Context) {
Jeromy's avatar
Jeromy committed
238 239 240 241
	for {
		select {
		case <-ctx.Done():
			return
242 243
		case envelope := <-bs.ledgermanager.Outbox():
			bs.send(ctx, envelope.Peer, envelope.Message)
Jeromy's avatar
Jeromy committed
244 245 246 247
		}
	}
}

248
// TODO ensure only one active request per key
249
func (bs *bitswap) clientWorker(parent context.Context) {
250 251

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

253 254
	broadcastSignal := time.After(rebroadcastDelay)
	defer cancel()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
255

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

			err := bs.sendWantListTo(ctx, providers)
			if err != nil {
				log.Errorf("error sending wantlist: %s", err)
Jeromy's avatar
Jeromy committed
283
			}
284
		case <-parent.Done():
Jeromy's avatar
Jeromy committed
285 286 287 288 289
			return
		}
	}
}

290
// TODO(brian): handle errors
291 292
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
293
	log.Debugf("ReceiveMessage from %s", p)
294

295
	if p == nil {
296
		log.Error("Received message from nil peer!")
297 298
		// TODO propagate the error upward
		return nil, nil
299 300
	}
	if incoming == nil {
301
		log.Error("Got nil bitswap message!")
302 303
		// TODO propagate the error upward
		return nil, nil
304
	}
305

Jeromy's avatar
Jeromy committed
306 307
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
Jeromy's avatar
Jeromy committed
308
	bs.ledgermanager.MessageReceived(p, incoming)
Jeromy's avatar
Jeromy committed
309 310
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
311

Brian Tiger Chow's avatar
Brian Tiger Chow committed
312
	for _, block := range incoming.Blocks() {
313 314
		hasBlockCtx, _ := context.WithTimeout(ctx, hasBlockTimeout)
		if err := bs.HasBlock(hasBlockCtx, block); err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
315
			log.Error(err)
Jeromy's avatar
Jeromy committed
316
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
317
	}
318
	var keys []u.Key
Brian Tiger Chow's avatar
Brian Tiger Chow committed
319
	for _, block := range incoming.Blocks() {
320
		keys = append(keys, block.Key())
321
	}
322
	bs.cancelBlocks(ctx, keys)
323

Jeromy's avatar
Jeromy committed
324
	// TODO: consider changing this function to not return anything
325
	return nil, nil
326 327
}

Jeromy's avatar
Jeromy committed
328
func (bs *bitswap) cancelBlocks(ctx context.Context, bkeys []u.Key) {
329 330 331
	if len(bkeys) < 1 {
		return
	}
Jeromy's avatar
Jeromy committed
332 333 334
	message := bsmsg.New()
	message.SetFull(false)
	for _, k := range bkeys {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
335
		message.Cancel(k)
Jeromy's avatar
Jeromy committed
336
	}
Jeromy's avatar
Jeromy committed
337
	for _, p := range bs.ledgermanager.Peers() {
Jeromy's avatar
Jeromy committed
338 339 340 341 342 343 344
		err := bs.send(ctx, p, message)
		if err != nil {
			log.Errorf("Error sending message: %s", err)
		}
	}
}

345
func (bs *bitswap) ReceiveError(err error) {
346
	log.Errorf("Bitswap ReceiveError: %s", err)
347 348
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
349 350
}

351 352
// send strives to ensure that accounting is always performed when a message is
// sent
353 354 355 356
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
357
	return bs.ledgermanager.MessageSent(p, m)
358
}
359 360 361 362 363

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