bitswap.go 9.88 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 25 26
// Number of providers to request for sending a wantlist to
const maxProvidersPerRequest = 6

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

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

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

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

	return bs
}

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

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

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

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

	notifications notifications.PubSub

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

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

83
	wantlist u.KeySet
84 85 86

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

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

93 94 95 96 97 98 99
	// 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
	// when this context Otherwise those functions won't return 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
			bs.sendWantlistToProviders(ctx, bs.wantlist.Keys())
215
		case ks := <-bs.batchRequests:
216
			// TODO: implement batching on len(ks) > X for some X
Jeromy's avatar
Jeromy committed
217 218 219
			//		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
220 221 222 223
			if len(ks) == 0 {
				log.Warning("Received batch request for zero blocks")
				continue
			}
Jeromy's avatar
Jeromy committed
224 225
			for _, k := range ks {
				bs.wantlist.Add(k)
226 227 228 229 230 231
			}
			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
232
			}
233
		case <-parent.Done():
Jeromy's avatar
Jeromy committed
234 235 236 237 238
			return
		}
	}
}

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

Jeromy's avatar
Jeromy committed
250 251 252 253 254 255 256 257 258 259 260 261
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)
	}
}

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

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

279 280 281
	// Record message bytes in ledger
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
282
	bs.strategy.MessageReceived(p, incoming) // FIRST
283

284
	for _, block := range incoming.Blocks() {
Jeromy's avatar
Jeromy committed
285
		go bs.receiveBlock(ctx, block)
286 287
	}

288
	for _, key := range incoming.Wantlist() {
289 290
		// TODO: might be better to check if we have the block before checking
		//			if we should send it to someone
291
		if bs.strategy.ShouldSendBlockToPeer(key, p) {
292 293 294
			if block, errBlockNotFound := bs.blockstore.Get(key); errBlockNotFound != nil {
				continue
			} else {
295 296 297
				// Create a separate message to send this block in
				blkmsg := bsmsg.New()

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

				blkmsg.AddBlock(block)
				bs.strategy.MessageSent(p, blkmsg)
				bs.send(ctx, p, blkmsg)
308 309 310
			}
		}
	}
311

312
	return nil, nil
313 314 315
}

func (bs *bitswap) ReceiveError(err error) {
316
	log.Errorf("Bitswap ReceiveError: %s", err)
317 318
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
319 320
}

321 322
// send strives to ensure that accounting is always performed when a message is
// sent
323
func (bs *bitswap) send(ctx context.Context, p peer.Peer, m bsmsg.BitSwapMessage) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
324
	bs.sender.SendMessage(ctx, p, m)
325
	bs.strategy.MessageSent(p, m)
326 327
}

Jeromy's avatar
Jeromy committed
328
func (bs *bitswap) sendToPeersThatWant(ctx context.Context, block *blocks.Block) {
329
	log.Debugf("Sending %v to peers that want it", block.Key())
330

331 332
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
333
			log.Debugf("%v wants %v", p, block.Key())
334 335
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
				message := bsmsg.New()
336
				message.AddBlock(block)
337
				for _, wanted := range bs.wantlist.Keys() {
338
					message.AddWanted(wanted)
339
				}
340
				bs.send(ctx, p, message)
341 342 343 344
			}
		}
	}
}
345 346 347 348 349

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