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 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
// 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)
	if err := bs.sendToPeersThatWant(child, blk); err != nil {
		return err
	}
	child, _ = context.WithTimeout(ctx, hasBlockTimeout)
	return bs.routing.Provide(child, blk.Key())
}

Jeromy's avatar
Jeromy committed
164
func (bs *bitswap) sendWantListTo(ctx context.Context, peers <-chan peer.Peer) error {
Jeromy's avatar
Jeromy committed
165 166 167
	if peers == nil {
		panic("Cant send wantlist to nil peerchan")
	}
Jeromy's avatar
Jeromy committed
168 169 170 171 172
	message := bsmsg.New()
	for _, wanted := range bs.wantlist.Keys() {
		message.AddWanted(wanted)
	}
	for peerToQuery := range peers {
173
		log.Debug("sending query to: %s", peerToQuery)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
174
		log.Event(ctx, "PeerToQuery", peerToQuery)
Jeromy's avatar
Jeromy committed
175 176
		go func(p peer.Peer) {

Brian Tiger Chow's avatar
Brian Tiger Chow committed
177
			log.Event(ctx, "DialPeer", p)
Jeromy's avatar
Jeromy committed
178 179
			err := bs.sender.DialPeer(ctx, p)
			if err != nil {
180
				log.Errorf("Error sender.DialPeer(%s): %s", p, err)
Jeromy's avatar
Jeromy committed
181 182 183
				return
			}

184
			err = bs.sender.SendMessage(ctx, p, message)
Jeromy's avatar
Jeromy committed
185
			if err != nil {
186
				log.Errorf("Error sender.SendMessage(%s) = %s", p, err)
Jeromy's avatar
Jeromy committed
187 188 189 190 191 192 193 194 195 196 197
				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
198
func (bs *bitswap) sendWantlistToProviders(ctx context.Context, ks []u.Key) {
199
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
200
	for _, k := range ks {
201
		wg.Add(1)
Jeromy's avatar
Jeromy committed
202
		go func(k u.Key) {
203 204
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
			providers := bs.routing.FindProvidersAsync(child, k, maxProvidersPerRequest)
Jeromy's avatar
Jeromy committed
205 206 207 208 209

			err := bs.sendWantListTo(ctx, providers)
			if err != nil {
				log.Errorf("error sending wantlist: %s", err)
			}
210
			wg.Done()
Jeromy's avatar
Jeromy committed
211 212
		}(k)
	}
213
	wg.Wait()
Jeromy's avatar
Jeromy committed
214 215
}

216
// TODO ensure only one active request per key
217 218 219
func (bs *bitswap) loop(parent context.Context) {

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

221
	broadcastSignal := time.NewTicker(bs.strategy.GetRebroadcastDelay())
222 223 224 225
	defer func() {
		cancel() // signal to derived async functions
		broadcastSignal.Stop()
	}()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
226

Jeromy's avatar
Jeromy committed
227 228
	for {
		select {
229
		case <-broadcastSignal.C:
Jeromy's avatar
Jeromy committed
230
			// Resend unfulfilled wantlist keys
Jeromy's avatar
Jeromy committed
231
			bs.sendWantlistToProviders(ctx, bs.wantlist.Keys())
232
		case ks := <-bs.batchRequests:
233
			// TODO: implement batching on len(ks) > X for some X
Jeromy's avatar
Jeromy committed
234 235 236
			//		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
237 238 239 240
			if len(ks) == 0 {
				log.Warning("Received batch request for zero blocks")
				continue
			}
Jeromy's avatar
Jeromy committed
241 242
			for _, k := range ks {
				bs.wantlist.Add(k)
243
			}
Jeromy's avatar
Jeromy committed
244 245 246 247 248 249 250
			// 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.
251 252
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
			providers := bs.routing.FindProvidersAsync(child, ks[0], maxProvidersPerRequest)
253 254 255 256

			err := bs.sendWantListTo(ctx, providers)
			if err != nil {
				log.Errorf("error sending wantlist: %s", err)
Jeromy's avatar
Jeromy committed
257
			}
258
		case <-parent.Done():
Jeromy's avatar
Jeromy committed
259 260 261 262 263
			return
		}
	}
}

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

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

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

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

				blkmsg.AddBlock(block)
				bs.send(ctx, p, blkmsg)
310
				bs.strategy.BlockSentToPeer(block.Key(), p)
311 312 313
			}
		}
	}
314

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

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

325 326
// send strives to ensure that accounting is always performed when a message is
// sent
327 328 329 330 331
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)
332 333
}

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

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