bitswap.go 10.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
	"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 18 19
	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"
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
Jeromy's avatar
Jeromy committed
20
	eventlog "github.com/jbenet/go-ipfs/util/eventlog"
21 22
)

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

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

29 30 31
const providerRequestTimeout = time.Second * 10
const hasBlockTimeout = time.Second * 15

32 33 34
// New initializes a BitSwap instance that communicates over the
// provided BitSwapNetwork. This function registers the returned instance as
// the network delegate.
35
// Runs until context is cancelled
36
func New(parent context.Context, p peer.Peer, network bsnet.BitSwapNetwork, routing bsnet.Routing,
37
	bstore blockstore.Blockstore, nice bool) exchange.Interface {
38

39 40
	ctx, cancelFunc := context.WithCancel(parent)

41 42
	notif := notifications.New()
	go func() {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
43 44
		<-ctx.Done()
		notif.Shutdown()
45 46
	}()

47
	bs := &bitswap{
48
		blockstore:    bstore,
49
		cancelFunc:    cancelFunc,
50
		notifications: notif,
51
		strategy:      strategy.New(nice),
52
		routing:       routing,
Brian Tiger Chow's avatar
Brian Tiger Chow committed
53
		sender:        network,
54
		wantlist:      u.NewKeySet(),
55
		batchRequests: make(chan []u.Key, 32),
56
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
57
	network.SetDelegate(bs)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
58
	go bs.loop(ctx)
59 60 61 62

	return bs
}

63 64 65 66
// bitswap instances implement the bitswap protocol.
type bitswap struct {

	// sender delivers messages on behalf of the session
67
	sender bsnet.BitSwapNetwork
68 69 70 71 72 73

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

	// routing interface for communication
74
	routing bsnet.Routing
75 76 77

	notifications notifications.PubSub

78 79 80 81
	// 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
82

83 84 85 86
	// strategy listens to network traffic and makes decisions about how to
	// interact with partners.
	// TODO(brian): save the strategy's state to the datastore
	strategy strategy.Strategy
87

88
	wantlist u.KeySet
89 90 91

	// cancelFunc signals cancellation to the bitswap event loop
	cancelFunc func()
92 93
}

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

98 99 100 101
	// 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
102 103
	// when this context's cancel func is executed. This is difficult to
	// enforce. May this comment keep you safe.
104

105
	ctx, cancelFunc := context.WithCancel(parent)
106

Jeromy's avatar
Jeromy committed
107
	ctx = eventlog.ContextWithLoggable(ctx, eventlog.Uuid("GetBlockRequest"))
108
	log.Event(ctx, "GetBlockRequestBegin", &k)
109 110 111 112 113

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

115
	promise, err := bs.GetBlocks(ctx, []u.Key{k})
116 117
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
118
	}
119 120

	select {
121
	case block := <-promise:
Jeromy's avatar
Jeromy committed
122
		return block, nil
123 124
	case <-parent.Done():
		return nil, parent.Err()
125
	}
126

127 128
}

129 130 131 132 133 134 135
// 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
136
func (bs *bitswap) GetBlocks(ctx context.Context, keys []u.Key) (<-chan *blocks.Block, error) {
137 138 139 140 141
	// TODO log the request

	promise := bs.notifications.Subscribe(ctx, keys...)
	select {
	case bs.batchRequests <- keys:
142
		return promise, nil
143 144 145
	case <-ctx.Done():
		return nil, ctx.Err()
	}
Jeromy's avatar
Jeromy committed
146 147 148
}

func (bs *bitswap) sendWantListTo(ctx context.Context, peers <-chan peer.Peer) error {
Jeromy's avatar
Jeromy committed
149 150 151
	if peers == nil {
		panic("Cant send wantlist to nil peerchan")
	}
Jeromy's avatar
Jeromy committed
152 153 154 155 156
	message := bsmsg.New()
	for _, wanted := range bs.wantlist.Keys() {
		message.AddWanted(wanted)
	}
	for peerToQuery := range peers {
157
		log.Debug("sending query to: %s", peerToQuery)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
158
		log.Event(ctx, "PeerToQuery", peerToQuery)
Jeromy's avatar
Jeromy committed
159 160
		go func(p peer.Peer) {

Brian Tiger Chow's avatar
Brian Tiger Chow committed
161
			log.Event(ctx, "DialPeer", p)
Jeromy's avatar
Jeromy committed
162 163
			err := bs.sender.DialPeer(ctx, p)
			if err != nil {
164
				log.Errorf("Error sender.DialPeer(%s): %s", p, err)
Jeromy's avatar
Jeromy committed
165 166 167
				return
			}

168
			err = bs.sender.SendMessage(ctx, p, message)
Jeromy's avatar
Jeromy committed
169
			if err != nil {
170
				log.Errorf("Error sender.SendMessage(%s) = %s", p, err)
Jeromy's avatar
Jeromy committed
171 172 173 174 175 176 177 178 179 180 181
				return
			}
			// FIXME ensure accounting is handled correctly when
			// communication fails. May require slightly different API to
			// get better guarantees. May need shared sequence numbers.
			bs.strategy.MessageSent(p, message)
		}(peerToQuery)
	}
	return nil
}

Jeromy's avatar
Jeromy committed
182
func (bs *bitswap) sendWantlistToProviders(ctx context.Context, ks []u.Key) {
183
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
184
	for _, k := range ks {
185
		wg.Add(1)
Jeromy's avatar
Jeromy committed
186
		go func(k u.Key) {
187 188
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
			providers := bs.routing.FindProvidersAsync(child, k, maxProvidersPerRequest)
Jeromy's avatar
Jeromy committed
189 190 191 192 193

			err := bs.sendWantListTo(ctx, providers)
			if err != nil {
				log.Errorf("error sending wantlist: %s", err)
			}
194
			wg.Done()
Jeromy's avatar
Jeromy committed
195 196
		}(k)
	}
197
	wg.Wait()
Jeromy's avatar
Jeromy committed
198 199
}

200
// TODO ensure only one active request per key
201 202 203
func (bs *bitswap) loop(parent context.Context) {

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

205
	broadcastSignal := time.NewTicker(bs.strategy.GetRebroadcastDelay())
206 207 208 209
	defer func() {
		cancel() // signal to derived async functions
		broadcastSignal.Stop()
	}()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
210

Jeromy's avatar
Jeromy committed
211 212
	for {
		select {
213
		case <-broadcastSignal.C:
Jeromy's avatar
Jeromy committed
214
			// Resend unfulfilled wantlist keys
Jeromy's avatar
Jeromy committed
215
			bs.sendWantlistToProviders(ctx, bs.wantlist.Keys())
216
		case ks := <-bs.batchRequests:
217
			// TODO: implement batching on len(ks) > X for some X
Jeromy's avatar
Jeromy committed
218 219 220
			//		i.e. if given 20 keys, fetch first five, then next
			//		five, and so on, so we are more likely to be able to
			//		effectively stream the data
221 222 223 224
			if len(ks) == 0 {
				log.Warning("Received batch request for zero blocks")
				continue
			}
Jeromy's avatar
Jeromy committed
225 226
			for _, k := range ks {
				bs.wantlist.Add(k)
227
			}
Jeromy's avatar
Jeromy committed
228 229 230 231 232 233 234
			// 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.
235 236
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
			providers := bs.routing.FindProvidersAsync(child, ks[0], maxProvidersPerRequest)
237 238 239 240

			err := bs.sendWantListTo(ctx, providers)
			if err != nil {
				log.Errorf("error sending wantlist: %s", err)
Jeromy's avatar
Jeromy committed
241
			}
242
		case <-parent.Done():
Jeromy's avatar
Jeromy committed
243 244 245 246 247
			return
		}
	}
}

248 249
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
Jeromy's avatar
Jeromy committed
250
func (bs *bitswap) HasBlock(ctx context.Context, blk *blocks.Block) error {
251 252 253
	if err := bs.blockstore.Put(blk); err != nil {
		return err
	}
254
	bs.wantlist.Remove(blk.Key())
255
	bs.notifications.Publish(blk)
256
	child, _ := context.WithTimeout(ctx, hasBlockTimeout)
257 258 259
	if err := bs.sendToPeersThatWant(child, blk); err != nil {
		return err
	}
260 261
	child, _ = context.WithTimeout(ctx, hasBlockTimeout)
	return bs.routing.Provide(child, blk.Key())
262 263 264
}

// TODO(brian): handle errors
265 266
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
267
	log.Debugf("ReceiveMessage from %s", p)
268

269
	if p == nil {
270
		log.Error("Received message from nil peer!")
271 272
		// TODO propagate the error upward
		return nil, nil
273 274
	}
	if incoming == nil {
275
		log.Error("Got nil bitswap message!")
276 277
		// TODO propagate the error upward
		return nil, nil
278
	}
279

280 281 282
	// Record message bytes in ledger
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
Jeromy's avatar
Jeromy committed
283 284 285
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
	bs.strategy.MessageReceived(p, incoming)
286

Jeromy's avatar
Jeromy committed
287 288
	go func() {
		for _, block := range incoming.Blocks() {
289 290 291
			if err := bs.HasBlock(ctx, block); err != nil {
				log.Error(err)
			}
Jeromy's avatar
Jeromy committed
292 293
		}
	}()
294

295 296
	for _, key := range incoming.Wantlist() {
		if bs.strategy.ShouldSendBlockToPeer(key, p) {
297 298 299
			if block, errBlockNotFound := bs.blockstore.Get(key); errBlockNotFound != nil {
				continue
			} else {
300 301 302
				// Create a separate message to send this block in
				blkmsg := bsmsg.New()

303
				// TODO: only send this the first time
Jeromy's avatar
Jeromy committed
304 305
				//		no sense in sending our wantlist to the
				//		same peer multiple times
306 307
				for _, k := range bs.wantlist.Keys() {
					blkmsg.AddWanted(k)
308 309 310 311
				}

				blkmsg.AddBlock(block)
				bs.send(ctx, p, blkmsg)
312 313 314
			}
		}
	}
315

Jeromy's avatar
Jeromy committed
316
	// TODO: consider changing this function to not return anything
317
	return nil, nil
318 319 320
}

func (bs *bitswap) ReceiveError(err error) {
321
	log.Errorf("Bitswap ReceiveError: %s", err)
322 323
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
324 325
}

326 327
// send strives to ensure that accounting is always performed when a message is
// sent
328 329 330 331 332
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
	}
	return bs.strategy.MessageSent(p, m)
333 334
}

335
func (bs *bitswap) sendToPeersThatWant(ctx context.Context, block *blocks.Block) error {
336 337 338 339
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
				message := bsmsg.New()
340
				message.AddBlock(block)
341
				for _, wanted := range bs.wantlist.Keys() {
342
					message.AddWanted(wanted)
343
				}
344 345 346
				if err := bs.send(ctx, p, message); err != nil {
					return err
				}
347 348 349
			}
		}
	}
350
	return nil
351
}
352 353 354 355 356

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