bitswap.go 9.14 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

	// make sure to derive a new |ctx| and pass it to children. It's correct to
	// listen on |parent| here, but incorrect to pass |parent| to new async
	// functions. This is difficult to enforce. May this comment keep you safe.
93

94
	ctx, cancelFunc := context.WithCancel(parent)
95

96 97
	ctx = eventlog.ContextWithMetadata(ctx, eventlog.Uuid("GetBlockRequest"))
	log.Event(ctx, "GetBlockRequestBegin", &k)
98 99 100 101 102

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

104 105 106
	promise, err := bs.GetBlocks(parent, []u.Key{k})
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
107
	}
108 109

	select {
110
	case block := <-promise:
Jeromy's avatar
Jeromy committed
111
		return block, nil
112 113
	case <-parent.Done():
		return nil, parent.Err()
114
	}
115

116 117
}

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

	promise := bs.notifications.Subscribe(ctx, keys...)
	select {
	case bs.batchRequests <- keys:
131
		return promise, nil
132 133 134
	case <-ctx.Done():
		return nil, ctx.Err()
	}
Jeromy's avatar
Jeromy committed
135 136 137
}

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

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

175
// TODO ensure only one active request per key
176 177 178
func (bs *bitswap) loop(parent context.Context) {

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

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

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

Jeromy's avatar
Jeromy committed
189 190
	for {
		select {
191
		case <-broadcastSignal.C:
192 193 194 195 196 197
			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
198
			}
199
		case ks := <-bs.batchRequests:
200 201 202 203 204
			// 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
205 206
			for _, k := range ks {
				bs.wantlist.Add(k)
207 208 209 210 211 212
			}
			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
213
			}
214
		case <-parent.Done():
Jeromy's avatar
Jeromy committed
215 216 217 218 219
			return
		}
	}
}

220 221
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
Jeromy's avatar
Jeromy committed
222
func (bs *bitswap) HasBlock(ctx context.Context, blk *blocks.Block) error {
223
	log.Debugf("Has Block %s", blk.Key())
224
	bs.wantlist.Remove(blk.Key())
225
	bs.sendToPeersThatWant(ctx, blk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
226
	return bs.routing.Provide(ctx, blk.Key())
227 228 229
}

// TODO(brian): handle errors
230 231
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
232
	log.Debugf("ReceiveMessage from %s", p)
233
	log.Debugf("Message wantlist: %v", incoming.Wantlist())
234

235
	if p == nil {
236
		log.Error("Received message from nil peer!")
237 238
		// TODO propagate the error upward
		return nil, nil
239 240
	}
	if incoming == nil {
241
		log.Error("Got nil bitswap message!")
242 243
		// TODO propagate the error upward
		return nil, nil
244
	}
245

246 247 248
	// Record message bytes in ledger
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
249
	bs.strategy.MessageReceived(p, incoming) // FIRST
250

251
	for _, block := range incoming.Blocks() {
252
		// TODO verify blocks?
Jeromy's avatar
Jeromy committed
253
		if err := bs.blockstore.Put(block); err != nil {
Jeromy's avatar
Jeromy committed
254
			log.Criticalf("error putting block: %s", err)
255
			continue // FIXME(brian): err ignored
256
		}
257
		bs.notifications.Publish(block)
258
		bs.wantlist.Remove(block.Key())
259 260 261 262
		err := bs.HasBlock(ctx, block)
		if err != nil {
			log.Warningf("HasBlock errored: %s", err)
		}
263 264
	}

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

275 276 277
				// TODO: only send this the first time
				for _, k := range bs.wantlist.Keys() {
					blkmsg.AddWanted(k)
278 279 280 281 282
				}

				blkmsg.AddBlock(block)
				bs.strategy.MessageSent(p, blkmsg)
				bs.send(ctx, p, blkmsg)
283 284 285
			}
		}
	}
286

287
	return nil, nil
288 289 290
}

func (bs *bitswap) ReceiveError(err error) {
291
	log.Errorf("Bitswap ReceiveError: %s", err)
292 293
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
294 295
}

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

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

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

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