bitswap.go 10.3 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 (
Jeromy's avatar
Jeromy committed
6 7
	"time"

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

	blocks "github.com/jbenet/go-ipfs/blocks"
11
	blockstore "github.com/jbenet/go-ipfs/blocks/blockstore"
12 13 14 15 16 17 18
	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
19
	eventlog "github.com/jbenet/go-ipfs/util/eventlog"
20 21
)

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

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

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

35 36
	ctx, cancelFunc := context.WithCancel(parent)

37 38
	notif := notifications.New()
	go func() {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
39 40
		<-ctx.Done()
		notif.Shutdown()
41 42
	}()

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

	return bs
}

59 60 61 62
// bitswap instances implement the bitswap protocol.
type bitswap struct {

	// sender delivers messages on behalf of the session
63
	sender bsnet.BitSwapNetwork
64 65 66 67 68 69

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

	// routing interface for communication
70
	routing bsnet.Routing
71 72 73

	notifications notifications.PubSub

74 75 76 77
	// 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
78

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

84
	wantlist u.KeySet
85 86 87

	// cancelFunc signals cancellation to the bitswap event loop
	cancelFunc func()
88 89
}

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

94 95 96 97
	// 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
98 99
	// when this context's cancel func is executed. This is difficult to
	// enforce. May this comment keep you safe.
100

101
	ctx, cancelFunc := context.WithCancel(parent)
102

Jeromy's avatar
Jeromy committed
103
	ctx = eventlog.ContextWithLoggable(ctx, eventlog.Uuid("GetBlockRequest"))
104
	log.Event(ctx, "GetBlockRequestBegin", &k)
105 106 107 108 109

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

111
	promise, err := bs.GetBlocks(ctx, []u.Key{k})
112 113
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
114
	}
115 116

	select {
117
	case block := <-promise:
Jeromy's avatar
Jeromy committed
118
		return block, nil
119 120
	case <-parent.Done():
		return nil, parent.Err()
121
	}
122

123 124
}

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

	promise := bs.notifications.Subscribe(ctx, keys...)
	select {
	case bs.batchRequests <- keys:
138
		return promise, nil
139 140 141
	case <-ctx.Done():
		return nil, ctx.Err()
	}
Jeromy's avatar
Jeromy committed
142 143 144
}

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
156
			log.Event(ctx, "DialPeer", p)
Jeromy's avatar
Jeromy committed
157 158
			err := bs.sender.DialPeer(ctx, p)
			if err != nil {
159
				log.Errorf("Error sender.DialPeer(%s): %s", p, err)
Jeromy's avatar
Jeromy committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
				return
			}

			response, err := bs.sender.SendRequest(ctx, p, message)
			if err != nil {
				log.Errorf("Error sender.SendRequest(%s) = %s", p, err)
				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)

			if response == nil {
				return
			}
			bs.ReceiveMessage(ctx, p, response)
		}(peerToQuery)
	}
	return nil
}

Jeromy's avatar
Jeromy committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
func (bs *bitswap) sendWantlistToProviders(ctx context.Context, ks []u.Key) {
	done := make(chan struct{})
	for _, k := range ks {
		go func(k u.Key) {
			providers := bs.routing.FindProvidersAsync(ctx, k, maxProvidersPerRequest)

			err := bs.sendWantListTo(ctx, providers)
			if err != nil {
				log.Errorf("error sending wantlist: %s", err)
			}
			done <- struct{}{}
		}(k)
	}
	for _ = range ks {
		<-done
	}
}

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 237 238 239
			providers := bs.routing.FindProvidersAsync(ctx, ks[0], maxProvidersPerRequest)

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

247 248
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
Jeromy's avatar
Jeromy committed
249
func (bs *bitswap) HasBlock(ctx context.Context, blk *blocks.Block) error {
250
	// TODO check all errors
251
	log.Debugf("Has Block %s", blk.Key())
252
	bs.wantlist.Remove(blk.Key())
253
	bs.notifications.Publish(blk)
254
	bs.sendToPeersThatWant(ctx, blk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
255
	return bs.routing.Provide(ctx, blk.Key())
256 257
}

Jeromy's avatar
Jeromy committed
258 259 260 261 262 263 264 265 266 267 268 269
func (bs *bitswap) receiveBlock(ctx context.Context, block *blocks.Block) {
	// TODO verify blocks?
	if err := bs.blockstore.Put(block); err != nil {
		log.Criticalf("error putting block: %s", err)
		return
	}
	err := bs.HasBlock(ctx, block)
	if err != nil {
		log.Warningf("HasBlock errored: %s", err)
	}
}

270
// TODO(brian): handle errors
271 272
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
273
	log.Debugf("ReceiveMessage from %s", p)
274

275
	if p == nil {
276
		log.Error("Received message from nil peer!")
277 278
		// TODO propagate the error upward
		return nil, nil
279 280
	}
	if incoming == nil {
281
		log.Error("Got nil bitswap message!")
282 283
		// TODO propagate the error upward
		return nil, nil
284
	}
285

286 287 288
	// 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
289 290 291
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
	bs.strategy.MessageReceived(p, incoming)
292

Jeromy's avatar
Jeromy committed
293 294 295 296 297
	go func() {
		for _, block := range incoming.Blocks() {
			bs.receiveBlock(ctx, block)
		}
	}()
298

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

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

				blkmsg.AddBlock(block)
				bs.send(ctx, p, blkmsg)
316 317 318
			}
		}
	}
319

Jeromy's avatar
Jeromy committed
320
	// TODO: consider changing this function to not return anything
321
	return nil, nil
322 323 324
}

func (bs *bitswap) ReceiveError(err error) {
325
	log.Errorf("Bitswap ReceiveError: %s", err)
326 327
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
328 329
}

330 331
// send strives to ensure that accounting is always performed when a message is
// sent
332
func (bs *bitswap) send(ctx context.Context, p peer.Peer, m bsmsg.BitSwapMessage) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
333
	bs.sender.SendMessage(ctx, p, m)
334
	bs.strategy.MessageSent(p, m)
335 336
}

Jeromy's avatar
Jeromy committed
337
func (bs *bitswap) sendToPeersThatWant(ctx context.Context, block *blocks.Block) {
Jeromy's avatar
Jeromy committed
338
	log.Debugf("Sending %s to peers that want it", block)
339

340 341
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
342
			log.Debugf("%v wants %v", p, block.Key())
343 344
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
				message := bsmsg.New()
345
				message.AddBlock(block)
346
				for _, wanted := range bs.wantlist.Keys() {
347
					message.AddWanted(wanted)
348
				}
349
				bs.send(ctx, p, message)
350 351 352 353
			}
		}
	}
}
354 355 356 357 358

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