bitswap.go 9.36 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"
19
	"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

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

31 32
	ctx, cancelFunc := context.WithCancel(parent)

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

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

	return bs
}

55 56 57 58
// bitswap instances implement the bitswap protocol.
type bitswap struct {

	// sender delivers messages on behalf of the session
59
	sender bsnet.BitSwapNetwork
60 61 62 63 64 65

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

	// routing interface for communication
66
	routing bsnet.Routing
67 68 69

	notifications notifications.PubSub

70 71 72 73
	// 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
74

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

80
	wantlist u.KeySet
81 82 83

	// cancelFunc signals cancellation to the bitswap event loop
	cancelFunc func()
84 85
}

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

90 91 92 93 94 95 96
	// 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.
97

98
	ctx, cancelFunc := context.WithCancel(parent)
99

100 101
	ctx = eventlog.ContextWithMetadata(ctx, eventlog.Uuid("GetBlockRequest"))
	log.Event(ctx, "GetBlockRequestBegin", &k)
102 103 104 105 106

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

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

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

120 121
}

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

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

func (bs *bitswap) sendWantListTo(ctx context.Context, peers <-chan peer.Peer) error {
Jeromy's avatar
Jeromy committed
142 143 144
	if peers == nil {
		panic("Cant send wantlist to nil peerchan")
	}
Jeromy's avatar
Jeromy committed
145 146 147 148 149
	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
150
		log.Event(ctx, "PeerToQuery", peerToQuery)
Jeromy's avatar
Jeromy committed
151 152
		go func(p peer.Peer) {

Brian Tiger Chow's avatar
Brian Tiger Chow committed
153
			log.Event(ctx, "DialPeer", p)
Jeromy's avatar
Jeromy committed
154 155
			err := bs.sender.DialPeer(ctx, p)
			if err != nil {
156
				log.Errorf("Error sender.DialPeer(%s): %s", p, err)
Jeromy's avatar
Jeromy committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
				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
}

179
// TODO ensure only one active request per key
180 181 182
func (bs *bitswap) loop(parent context.Context) {

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

184 185
	// Every so often, we should resend out our current want list
	rebroadcastTime := time.Second * 5
Brian Tiger Chow's avatar
Brian Tiger Chow committed
186

187
	broadcastSignal := time.NewTicker(bs.strategy.GetRebroadcastDelay())
188 189 190 191
	defer func() {
		cancel() // signal to derived async functions
		broadcastSignal.Stop()
	}()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
192

Jeromy's avatar
Jeromy committed
193 194
	for {
		select {
195
		case <-broadcastSignal.C:
196 197 198 199 200 201
			for _, k := range bs.wantlist.Keys() {
				providers := bs.routing.FindProvidersAsync(ctx, k, maxProvidersPerRequest)
				err := bs.sendWantListTo(ctx, providers)
				if err != nil {
					log.Errorf("error sending wantlist: %s", err)
				}
Jeromy's avatar
Jeromy committed
202
			}
203
		case ks := <-bs.batchRequests:
204 205 206 207 208
			// TODO: implement batching on len(ks) > X for some X
			if len(ks) == 0 {
				log.Warning("Received batch request for zero blocks")
				continue
			}
Jeromy's avatar
Jeromy committed
209 210
			for _, k := range ks {
				bs.wantlist.Add(k)
211 212 213 214 215 216
			}
			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
217
			}
218
		case <-parent.Done():
Jeromy's avatar
Jeromy committed
219 220 221 222 223
			return
		}
	}
}

224 225
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
Jeromy's avatar
Jeromy committed
226
func (bs *bitswap) HasBlock(ctx context.Context, blk *blocks.Block) error {
227
	// TODO check all errors
228
	log.Debugf("Has Block %s", blk.Key())
229
	bs.wantlist.Remove(blk.Key())
230
	bs.notifications.Publish(blk)
231
	bs.sendToPeersThatWant(ctx, blk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232
	return bs.routing.Provide(ctx, blk.Key())
233 234 235
}

// TODO(brian): handle errors
236 237
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
238
	log.Debugf("ReceiveMessage from %s", p)
239
	log.Debugf("Message wantlist: %v", incoming.Wantlist())
240

241
	if p == nil {
242
		log.Error("Received message from nil peer!")
243 244
		// TODO propagate the error upward
		return nil, nil
245 246
	}
	if incoming == nil {
247
		log.Error("Got nil bitswap message!")
248 249
		// TODO propagate the error upward
		return nil, nil
250
	}
251

252 253 254
	// Record message bytes in ledger
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
255
	bs.strategy.MessageReceived(p, incoming) // FIRST
256

257
	for _, block := range incoming.Blocks() {
258
		// TODO verify blocks?
Jeromy's avatar
Jeromy committed
259
		if err := bs.blockstore.Put(block); err != nil {
Jeromy's avatar
Jeromy committed
260
			log.Criticalf("error putting block: %s", err)
261
			continue // FIXME(brian): err ignored
262
		}
263 264 265 266
		err := bs.HasBlock(ctx, block)
		if err != nil {
			log.Warningf("HasBlock errored: %s", err)
		}
267 268
	}

269
	for _, key := range incoming.Wantlist() {
270 271
		// TODO: might be better to check if we have the block before checking
		//			if we should send it to someone
272
		if bs.strategy.ShouldSendBlockToPeer(key, p) {
273 274 275
			if block, errBlockNotFound := bs.blockstore.Get(key); errBlockNotFound != nil {
				continue
			} else {
276 277 278
				// Create a separate message to send this block in
				blkmsg := bsmsg.New()

279 280 281
				// TODO: only send this the first time
				for _, k := range bs.wantlist.Keys() {
					blkmsg.AddWanted(k)
282 283 284 285 286
				}

				blkmsg.AddBlock(block)
				bs.strategy.MessageSent(p, blkmsg)
				bs.send(ctx, p, blkmsg)
287 288 289
			}
		}
	}
290

291
	return nil, nil
292 293 294
}

func (bs *bitswap) ReceiveError(err error) {
295
	log.Errorf("Bitswap ReceiveError: %s", err)
296 297
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
298 299
}

300 301
// send strives to ensure that accounting is always performed when a message is
// sent
302
func (bs *bitswap) send(ctx context.Context, p peer.Peer, m bsmsg.BitSwapMessage) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
303
	bs.sender.SendMessage(ctx, p, m)
304
	bs.strategy.MessageSent(p, m)
305 306
}

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

310 311
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
312
			log.Debugf("%v wants %v", p, block.Key())
313 314
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
				message := bsmsg.New()
315
				message.AddBlock(block)
316
				for _, wanted := range bs.wantlist.Keys() {
317
					message.AddWanted(wanted)
318
				}
319
				bs.send(ctx, p, message)
320 321 322 323
			}
		}
	}
}
324 325 326 327 328

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