bitswap.go 8.8 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
	"math/rand"
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"
20
	"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

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

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

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

	return bs
}

53 54 55 56
// bitswap instances implement the bitswap protocol.
type bitswap struct {

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

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

	// routing interface for communication
64
	routing bsnet.Routing
65 66 67

	notifications notifications.PubSub

68 69 70 71
	// 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
72

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

78
	wantlist u.KeySet
79 80
}

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

	// 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.
88

89
	ctx, cancelFunc := context.WithCancel(parent)
90 91
	defer cancelFunc()

92 93
	ctx = eventlog.ContextWithMetadata(ctx, eventlog.Uuid("GetBlockRequest"))
	log.Event(ctx, "GetBlockRequestBegin", &k)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
94
	defer log.Event(ctx, "GetBlockRequestEnd", &k)
95

96 97 98
	promise, err := bs.GetBlocks(parent, []u.Key{k})
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
99
	}
100 101

	select {
102
	case block := <-promise:
103
		return &block, nil
104 105
	case <-parent.Done():
		return nil, parent.Err()
106 107 108
	}
}

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
// 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)
func (bs *bitswap) GetBlocks(ctx context.Context, keys []u.Key) (<-chan blocks.Block, error) {
	// TODO log the request

	promise := bs.notifications.Subscribe(ctx, keys...)
	select {
	case bs.batchRequests <- keys:
		return promise, nil
	case <-ctx.Done():
		return nil, ctx.Err()
	}
Jeromy's avatar
Jeromy committed
126 127 128
}

func (bs *bitswap) sendWantListTo(ctx context.Context, peers <-chan peer.Peer) error {
Jeromy's avatar
Jeromy committed
129 130 131
	if peers == nil {
		panic("Cant send wantlist to nil peerchan")
	}
Jeromy's avatar
Jeromy committed
132 133 134 135 136
	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
137
		log.Event(ctx, "PeerToQuery", peerToQuery)
Jeromy's avatar
Jeromy committed
138 139
		go func(p peer.Peer) {

Brian Tiger Chow's avatar
Brian Tiger Chow committed
140
			log.Event(ctx, "DialPeer", p)
Jeromy's avatar
Jeromy committed
141 142
			err := bs.sender.DialPeer(ctx, p)
			if err != nil {
143
				log.Errorf("Error sender.DialPeer(%s): %s", p, err)
Jeromy's avatar
Jeromy committed
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
				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
}

166
// TODO ensure only one active request per key
Jeromy's avatar
Jeromy committed
167 168
func (bs *bitswap) run(ctx context.Context) {

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

172
	broadcastSignal := time.NewTicker(bs.strategy.GetRebroadcastDelay())
173
	defer broadcastSignal.Stop()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
174

Jeromy's avatar
Jeromy committed
175 176
	for {
		select {
177
		case <-broadcastSignal.C:
Jeromy's avatar
Jeromy committed
178 179 180 181
			wantlist := bs.wantlist.Keys()
			if len(wantlist) == 0 {
				continue
			}
Jeromy's avatar
Jeromy committed
182 183
			n := rand.Intn(len(wantlist))
			providers := bs.routing.FindProvidersAsync(ctx, wantlist[n], maxProvidersPerRequest)
184

Brian Tiger Chow's avatar
Brian Tiger Chow committed
185
			err := bs.sendWantListTo(ctx, providers)
Jeromy's avatar
Jeromy committed
186
			if err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
187
				log.Errorf("error sending wantlist: %s", err)
Jeromy's avatar
Jeromy committed
188
			}
189
		case ks := <-bs.batchRequests:
Jeromy's avatar
Jeromy committed
190
			// TODO: implement batching on len(ks) > X for some X
191 192 193
			for _, k := range ks {
				bs.wantlist.Add(k)
			}
194 195 196
			if len(ks) == 0 {
				log.Warning("Received batch request for zero blocks")
				continue
Jeromy's avatar
Jeromy committed
197
			}
Jeromy's avatar
Jeromy committed
198 199 200
			for _, k := range ks {
				bs.wantlist.Add(k)
			}
201 202 203 204 205
			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
206 207 208 209 210 211 212
			}
		case <-ctx.Done():
			return
		}
	}
}

213 214
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
215
func (bs *bitswap) HasBlock(ctx context.Context, blk blocks.Block) error {
216
	log.Debugf("Has Block %v", blk.Key())
217
	bs.wantlist.Remove(blk.Key())
218
	bs.sendToPeersThatWant(ctx, blk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219
	return bs.routing.Provide(ctx, blk.Key())
220 221 222
}

// TODO(brian): handle errors
223 224
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
225
	log.Debugf("ReceiveMessage from %s", p)
226
	log.Debugf("Message wantlist: %v", incoming.Wantlist())
227

228
	if p == nil {
229
		log.Error("Received message from nil peer!")
230 231
		// TODO propagate the error upward
		return nil, nil
232 233
	}
	if incoming == nil {
234
		log.Error("Got nil bitswap message!")
235 236
		// TODO propagate the error upward
		return nil, nil
237
	}
238

239 240 241
	// Record message bytes in ledger
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
242
	bs.strategy.MessageReceived(p, incoming) // FIRST
243

244
	for _, block := range incoming.Blocks() {
245
		// TODO verify blocks?
246
		if err := bs.blockstore.Put(&block); err != nil {
Jeromy's avatar
Jeromy committed
247
			log.Criticalf("error putting block: %s", err)
248
			continue // FIXME(brian): err ignored
249
		}
250
		bs.notifications.Publish(block)
251
		bs.wantlist.Remove(block.Key())
252 253 254 255
		err := bs.HasBlock(ctx, block)
		if err != nil {
			log.Warningf("HasBlock errored: %s", err)
		}
256 257
	}

258 259
	message := bsmsg.New()
	for _, wanted := range bs.wantlist.Keys() {
260
		message.AddWanted(wanted)
261
	}
262
	for _, key := range incoming.Wantlist() {
263 264
		// TODO: might be better to check if we have the block before checking
		//			if we should send it to someone
265
		if bs.strategy.ShouldSendBlockToPeer(key, p) {
266 267 268
			if block, errBlockNotFound := bs.blockstore.Get(key); errBlockNotFound != nil {
				continue
			} else {
269
				message.AddBlock(*block)
270 271 272
			}
		}
	}
273

Jeromy's avatar
Jeromy committed
274
	bs.strategy.MessageSent(p, message)
275
	log.Debug("Returning message.")
276 277 278 279
	return p, message
}

func (bs *bitswap) ReceiveError(err error) {
280
	log.Errorf("Bitswap ReceiveError: %s", err)
281 282
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
283 284
}

285 286
// send strives to ensure that accounting is always performed when a message is
// sent
287
func (bs *bitswap) send(ctx context.Context, p peer.Peer, m bsmsg.BitSwapMessage) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
288
	bs.sender.SendMessage(ctx, p, m)
289
	bs.strategy.MessageSent(p, m)
290 291
}

292
func (bs *bitswap) sendToPeersThatWant(ctx context.Context, block blocks.Block) {
293
	log.Debugf("Sending %v to peers that want it", block.Key())
294

295 296
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
297
			log.Debugf("%v wants %v", p, block.Key())
298 299
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
				message := bsmsg.New()
300
				message.AddBlock(block)
301
				for _, wanted := range bs.wantlist.Keys() {
302
					message.AddWanted(wanted)
303
				}
304
				bs.send(ctx, p, message)
305 306 307 308
			}
		}
	}
}