bitswap.go 8.61 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 29
func New(ctx context.Context, p peer.Peer, network bsnet.BitSwapNetwork, routing bsnet.Routing,
	bstore blockstore.Blockstore, nice bool) exchange.Interface {
30

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

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

	return bs
}

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

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

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

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

	notifications notifications.PubSub

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

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

77
	wantlist u.KeySet
78 79
}

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

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

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

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

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

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

108 109 110 111 112 113 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)
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
125 126 127
}

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

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

165
// TODO ensure only one active request per key
166 167 168 169
func (bs *bitswap) loop(parent context.Context) {

	ctx, cancel := context.WithCancel(parent)
	defer cancel() // signal termination
Jeromy's avatar
Jeromy committed
170

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

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

Jeromy's avatar
Jeromy committed
177 178
	for {
		select {
179
		case <-broadcastSignal.C:
180 181 182 183 184 185
			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
186
			}
187
		case ks := <-bs.batchRequests:
Jeromy's avatar
Jeromy committed
188 189
			for _, k := range ks {
				bs.wantlist.Add(k)
190 191 192 193 194
				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
195
			}
196
		case <-parent.Done():
Jeromy's avatar
Jeromy committed
197 198 199 200 201
			return
		}
	}
}

202 203
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
204
func (bs *bitswap) HasBlock(ctx context.Context, blk blocks.Block) error {
205
	log.Debugf("Has Block %v", blk.Key())
206
	bs.wantlist.Remove(blk.Key())
207
	bs.sendToPeersThatWant(ctx, blk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208
	return bs.routing.Provide(ctx, blk.Key())
209 210 211
}

// TODO(brian): handle errors
212 213
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
214
	log.Debugf("ReceiveMessage from %s", p)
215
	log.Debugf("Message wantlist: %v", incoming.Wantlist())
216

217
	if p == nil {
218
		log.Error("Received message from nil peer!")
219 220
		// TODO propagate the error upward
		return nil, nil
221 222
	}
	if incoming == nil {
223
		log.Error("Got nil bitswap message!")
224 225
		// TODO propagate the error upward
		return nil, nil
226
	}
227

228 229 230
	// Record message bytes in ledger
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
231
	bs.strategy.MessageReceived(p, incoming) // FIRST
232

233
	for _, block := range incoming.Blocks() {
234
		// TODO verify blocks?
235
		if err := bs.blockstore.Put(&block); err != nil {
Jeromy's avatar
Jeromy committed
236
			log.Criticalf("error putting block: %s", err)
237
			continue // FIXME(brian): err ignored
238
		}
239
		bs.notifications.Publish(block)
240
		bs.wantlist.Remove(block.Key())
241 242 243 244
		err := bs.HasBlock(ctx, block)
		if err != nil {
			log.Warningf("HasBlock errored: %s", err)
		}
245 246
	}

247 248
	message := bsmsg.New()
	for _, wanted := range bs.wantlist.Keys() {
249
		message.AddWanted(wanted)
250
	}
251
	for _, key := range incoming.Wantlist() {
252 253
		// TODO: might be better to check if we have the block before checking
		//			if we should send it to someone
254
		if bs.strategy.ShouldSendBlockToPeer(key, p) {
255 256 257
			if block, errBlockNotFound := bs.blockstore.Get(key); errBlockNotFound != nil {
				continue
			} else {
258
				message.AddBlock(*block)
259 260 261
			}
		}
	}
262

Jeromy's avatar
Jeromy committed
263
	bs.strategy.MessageSent(p, message)
264
	log.Debug("Returning message.")
265 266 267 268
	return p, message
}

func (bs *bitswap) ReceiveError(err error) {
269
	log.Errorf("Bitswap ReceiveError: %s", err)
270 271
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
272 273
}

274 275
// send strives to ensure that accounting is always performed when a message is
// sent
276
func (bs *bitswap) send(ctx context.Context, p peer.Peer, m bsmsg.BitSwapMessage) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
277
	bs.sender.SendMessage(ctx, p, m)
278
	bs.strategy.MessageSent(p, m)
279 280
}

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

284 285
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
286
			log.Debugf("%v wants %v", p, block.Key())
287 288
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
				message := bsmsg.New()
289
				message.AddBlock(block)
290
				for _, wanted := range bs.wantlist.Keys() {
291
					message.AddWanted(wanted)
292
				}
293
				bs.send(ctx, p, message)
294 295 296 297
			}
		}
	}
}