bitswap.go 10.1 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
	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
	exchange "github.com/jbenet/go-ipfs/exchange"
13
	decision "github.com/jbenet/go-ipfs/exchange/bitswap/decision"
14 15 16
	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"
17
	wantlist "github.com/jbenet/go-ipfs/exchange/bitswap/wantlist"
18 19
	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"
Jeromy's avatar
Jeromy committed
21
	pset "github.com/jbenet/go-ipfs/util/peerset"
22 23
)

24
var log = eventlog.Logger("bitswap")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25

Brian Tiger Chow's avatar
Brian Tiger Chow committed
26 27 28 29 30 31 32
const (
	// Number of providers to request for sending a wantlist to
	// TODO: if a 'non-nice' strategy is implemented, consider increasing this value
	maxProvidersPerRequest = 3
	providerRequestTimeout = time.Second * 10
	hasBlockTimeout        = time.Second * 15
)
Jeromy's avatar
Jeromy committed
33

Brian Tiger Chow's avatar
Brian Tiger Chow committed
34 35 36
var (
	rebroadcastDelay = time.Second * 10
)
37

Brian Tiger Chow's avatar
Brian Tiger Chow committed
38 39 40 41
// New initializes a BitSwap instance that communicates over the provided
// BitSwapNetwork. This function registers the returned instance as the network
// delegate.
// Runs until context is cancelled.
42
func New(parent context.Context, p peer.Peer, network bsnet.BitSwapNetwork, routing bsnet.Routing,
43
	bstore blockstore.Blockstore, nice bool) exchange.Interface {
44

45 46
	ctx, cancelFunc := context.WithCancel(parent)

47 48
	notif := notifications.New()
	go func() {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
49
		<-ctx.Done()
Jeromy's avatar
Jeromy committed
50
		cancelFunc()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
51
		notif.Shutdown()
52 53
	}()

54
	bs := &bitswap{
55
		blockstore:    bstore,
56
		cancelFunc:    cancelFunc,
57
		notifications: notif,
58
		engine:        decision.NewEngine(ctx, bstore),
59
		routing:       routing,
Brian Tiger Chow's avatar
Brian Tiger Chow committed
60
		sender:        network,
61
		wantlist:      wantlist.NewThreadSafe(),
62
		batchRequests: make(chan []u.Key, 32),
63
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
64
	network.SetDelegate(bs)
65
	go bs.clientWorker(ctx)
Jeromy's avatar
Jeromy committed
66
	go bs.taskWorker(ctx)
67 68 69 70

	return bs
}

71 72 73 74
// bitswap instances implement the bitswap protocol.
type bitswap struct {

	// sender delivers messages on behalf of the session
75
	sender bsnet.BitSwapNetwork
76 77 78 79 80 81

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

	// routing interface for communication
82
	routing bsnet.Routing
83 84 85

	notifications notifications.PubSub

86 87 88 89
	// 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
90

91
	engine *decision.Engine
92

93
	wantlist *wantlist.ThreadSafe
94 95 96

	// cancelFunc signals cancellation to the bitswap event loop
	cancelFunc func()
97 98
}

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

103 104 105 106
	// 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
107 108
	// when this context's cancel func is executed. This is difficult to
	// enforce. May this comment keep you safe.
109

110
	ctx, cancelFunc := context.WithCancel(parent)
111

Jeromy's avatar
Jeromy committed
112
	ctx = eventlog.ContextWithLoggable(ctx, eventlog.Uuid("GetBlockRequest"))
113
	log.Event(ctx, "GetBlockRequestBegin", &k)
114 115 116 117 118

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

120
	promise, err := bs.GetBlocks(ctx, []u.Key{k})
121 122
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
123
	}
124 125

	select {
126
	case block := <-promise:
Jeromy's avatar
Jeromy committed
127
		return block, nil
128 129
	case <-parent.Done():
		return nil, parent.Err()
130
	}
131

132 133
}

134 135 136 137 138 139 140
// 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
141
func (bs *bitswap) GetBlocks(ctx context.Context, keys []u.Key) (<-chan *blocks.Block, error) {
142 143 144 145 146
	// TODO log the request

	promise := bs.notifications.Subscribe(ctx, keys...)
	select {
	case bs.batchRequests <- keys:
147
		return promise, nil
148 149 150
	case <-ctx.Done():
		return nil, ctx.Err()
	}
Jeromy's avatar
Jeromy committed
151 152
}

153 154 155 156 157 158 159 160
// 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)
161
	return bs.routing.Provide(ctx, blk.Key())
162 163
}

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
	message := bsmsg.New()
Jeromy's avatar
Jeromy committed
169
	for _, wanted := range bs.wantlist.Entries() {
170
		message.AddEntry(wanted.Key, wanted.Priority)
Jeromy's avatar
Jeromy committed
171
	}
172
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
173
	for peerToQuery := range peers {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
174
		log.Event(ctx, "PeerToQuery", peerToQuery)
175
		wg.Add(1)
Jeromy's avatar
Jeromy committed
176
		go func(p peer.Peer) {
177
			defer wg.Done()
Jeromy's avatar
Jeromy committed
178

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

186
			err = bs.sender.SendMessage(ctx, p, message)
Jeromy's avatar
Jeromy committed
187
			if err != nil {
188
				log.Errorf("Error sender.SendMessage(%s) = %s", p, err)
Jeromy's avatar
Jeromy committed
189 190 191 192 193
				return
			}
			// FIXME ensure accounting is handled correctly when
			// communication fails. May require slightly different API to
			// get better guarantees. May need shared sequence numbers.
194
			bs.engine.MessageSent(p, message)
Jeromy's avatar
Jeromy committed
195 196
		}(peerToQuery)
	}
197
	wg.Wait()
Jeromy's avatar
Jeromy committed
198 199 200
	return nil
}

201
func (bs *bitswap) sendWantlistToProviders(ctx context.Context, wantlist *wantlist.ThreadSafe) {
202 203 204
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

Jeromy's avatar
Jeromy committed
205 206 207
	message := bsmsg.New()
	message.SetFull(true)
	for _, e := range bs.wantlist.Entries() {
208
		message.AddEntry(e.Key, e.Priority)
Jeromy's avatar
Jeromy committed
209 210 211 212
	}

	ps := pset.NewPeerSet()

213
	// Get providers for all entries in wantlist (could take a while)
Jeromy's avatar
Jeromy committed
214
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
215
	for _, e := range wantlist.Entries() {
216
		wg.Add(1)
Jeromy's avatar
Jeromy committed
217
		go func(k u.Key) {
Jeromy's avatar
Jeromy committed
218
			defer wg.Done()
219 220
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
			providers := bs.routing.FindProvidersAsync(child, k, maxProvidersPerRequest)
Jeromy's avatar
Jeromy committed
221

222
			for prov := range providers {
Jeromy's avatar
Jeromy committed
223
				if ps.TryAdd(prov) { //Do once per peer
Jeromy's avatar
Jeromy committed
224 225
					bs.send(ctx, prov, message)
				}
Jeromy's avatar
Jeromy committed
226
			}
227
		}(e.Key)
Jeromy's avatar
Jeromy committed
228
	}
Jeromy's avatar
Jeromy committed
229
	wg.Wait()
Jeromy's avatar
Jeromy committed
230 231
}

Jeromy's avatar
Jeromy committed
232
func (bs *bitswap) taskWorker(ctx context.Context) {
Jeromy's avatar
Jeromy committed
233 234 235 236
	for {
		select {
		case <-ctx.Done():
			return
237
		case envelope := <-bs.engine.Outbox():
238
			bs.send(ctx, envelope.Peer, envelope.Message)
Jeromy's avatar
Jeromy committed
239 240 241 242
		}
	}
}

243
// TODO ensure only one active request per key
244
func (bs *bitswap) clientWorker(parent context.Context) {
245 246

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

248 249
	broadcastSignal := time.After(rebroadcastDelay)
	defer cancel()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
250

Jeromy's avatar
Jeromy committed
251 252
	for {
		select {
253
		case <-broadcastSignal:
Jeromy's avatar
Jeromy committed
254
			// Resend unfulfilled wantlist keys
Jeromy's avatar
Jeromy committed
255
			bs.sendWantlistToProviders(ctx, bs.wantlist)
256
			broadcastSignal = time.After(rebroadcastDelay)
257
		case ks := <-bs.batchRequests:
258 259 260 261
			if len(ks) == 0 {
				log.Warning("Received batch request for zero blocks")
				continue
			}
262 263
			for i, k := range ks {
				bs.wantlist.Add(k, len(ks)-i)
264
			}
Jeromy's avatar
Jeromy committed
265 266 267 268 269 270 271
			// 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.
272 273
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
			providers := bs.routing.FindProvidersAsync(child, ks[0], maxProvidersPerRequest)
274 275 276 277

			err := bs.sendWantListTo(ctx, providers)
			if err != nil {
				log.Errorf("error sending wantlist: %s", err)
Jeromy's avatar
Jeromy committed
278
			}
279
		case <-parent.Done():
Jeromy's avatar
Jeromy committed
280 281 282 283 284
			return
		}
	}
}

285
// TODO(brian): handle errors
286 287
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
288
	log.Debugf("ReceiveMessage from %s", p)
289

290
	if p == nil {
291
		log.Error("Received message from nil peer!")
292 293
		// TODO propagate the error upward
		return nil, nil
294 295
	}
	if incoming == nil {
296
		log.Error("Got nil bitswap message!")
297 298
		// TODO propagate the error upward
		return nil, nil
299
	}
300

Jeromy's avatar
Jeromy committed
301 302
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
303
	bs.engine.MessageReceived(p, incoming)
Jeromy's avatar
Jeromy committed
304 305
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
306

Brian Tiger Chow's avatar
Brian Tiger Chow committed
307
	for _, block := range incoming.Blocks() {
308 309
		hasBlockCtx, _ := context.WithTimeout(ctx, hasBlockTimeout)
		if err := bs.HasBlock(hasBlockCtx, block); err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
310
			log.Error(err)
Jeromy's avatar
Jeromy committed
311
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
312
	}
313
	var keys []u.Key
Brian Tiger Chow's avatar
Brian Tiger Chow committed
314
	for _, block := range incoming.Blocks() {
315
		keys = append(keys, block.Key())
316
	}
317
	bs.cancelBlocks(ctx, keys)
318

Jeromy's avatar
Jeromy committed
319
	// TODO: consider changing this function to not return anything
320
	return nil, nil
321 322
}

Jeromy's avatar
Jeromy committed
323
func (bs *bitswap) cancelBlocks(ctx context.Context, bkeys []u.Key) {
324 325 326
	if len(bkeys) < 1 {
		return
	}
Jeromy's avatar
Jeromy committed
327 328 329
	message := bsmsg.New()
	message.SetFull(false)
	for _, k := range bkeys {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
330
		message.Cancel(k)
Jeromy's avatar
Jeromy committed
331
	}
332
	for _, p := range bs.engine.Peers() {
Jeromy's avatar
Jeromy committed
333 334 335 336 337 338 339
		err := bs.send(ctx, p, message)
		if err != nil {
			log.Errorf("Error sending message: %s", err)
		}
	}
}

340
func (bs *bitswap) ReceiveError(err error) {
341
	log.Errorf("Bitswap ReceiveError: %s", err)
342 343
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
344 345
}

346 347
// send strives to ensure that accounting is always performed when a message is
// sent
348 349 350 351
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
	}
352
	return bs.engine.MessageSent(p, m)
353
}
354 355 356 357 358

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