bitswap.go 10.5 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
	"math"
7
	"sync"
Jeromy's avatar
Jeromy committed
8 9
	"time"

10
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
11

12
	blocks "github.com/jbenet/go-ipfs/blocks"
13
	blockstore "github.com/jbenet/go-ipfs/blocks/blockstore"
14
	exchange "github.com/jbenet/go-ipfs/exchange"
15
	decision "github.com/jbenet/go-ipfs/exchange/bitswap/decision"
16 17 18
	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"
19
	wantlist "github.com/jbenet/go-ipfs/exchange/bitswap/wantlist"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20
	peer "github.com/jbenet/go-ipfs/p2p/peer"
21 22
	"github.com/jbenet/go-ipfs/thirdparty/delay"
	eventlog "github.com/jbenet/go-ipfs/thirdparty/eventlog"
23
	u "github.com/jbenet/go-ipfs/util"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
24 25
	errors "github.com/jbenet/go-ipfs/util/debugerror"
	pset "github.com/jbenet/go-ipfs/util/peerset" // TODO move this to peerstore
26 27
)

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
30
const (
Brian Tiger Chow's avatar
Brian Tiger Chow committed
31 32 33
	// maxProvidersPerRequest specifies the maximum number of providers desired
	// from the network. This value is specified because the network streams
	// results.
Brian Tiger Chow's avatar
Brian Tiger Chow committed
34 35 36 37
	// TODO: if a 'non-nice' strategy is implemented, consider increasing this value
	maxProvidersPerRequest = 3
	providerRequestTimeout = time.Second * 10
	hasBlockTimeout        = time.Second * 15
Brian Tiger Chow's avatar
Brian Tiger Chow committed
38
	sizeBatchRequestChan   = 32
39 40
	// kMaxPriority is the max priority as defined by the bitswap protocol
	kMaxPriority = math.MaxInt32
Brian Tiger Chow's avatar
Brian Tiger Chow committed
41
)
Jeromy's avatar
Jeromy committed
42

Brian Tiger Chow's avatar
Brian Tiger Chow committed
43
var (
Brian Tiger Chow's avatar
Brian Tiger Chow committed
44
	rebroadcastDelay = delay.Fixed(time.Second * 10)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
45
)
46

Brian Tiger Chow's avatar
Brian Tiger Chow committed
47 48 49 50
// 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.
51
func New(parent context.Context, p peer.ID, network bsnet.BitSwapNetwork,
52
	bstore blockstore.Blockstore, nice bool) exchange.Interface {
53

54 55
	ctx, cancelFunc := context.WithCancel(parent)

56 57
	notif := notifications.New()
	go func() {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
58
		<-ctx.Done()
Jeromy's avatar
Jeromy committed
59
		cancelFunc()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
60
		notif.Shutdown()
61 62
	}()

63
	bs := &bitswap{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64
		self:          p,
65
		blockstore:    bstore,
66
		cancelFunc:    cancelFunc,
67
		notifications: notif,
68
		engine:        decision.NewEngine(ctx, bstore),
69
		network:       network,
70
		wantlist:      wantlist.NewThreadSafe(),
Brian Tiger Chow's avatar
Brian Tiger Chow committed
71
		batchRequests: make(chan []u.Key, sizeBatchRequestChan),
72
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
73
	network.SetDelegate(bs)
74
	go bs.clientWorker(ctx)
Jeromy's avatar
Jeromy committed
75
	go bs.taskWorker(ctx)
76 77 78 79

	return bs
}

80 81 82
// bitswap instances implement the bitswap protocol.
type bitswap struct {

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83 84 85
	// the ID of the peer to act on behalf of
	self peer.ID

86 87
	// network delivers messages on behalf of the session
	network bsnet.BitSwapNetwork
88 89 90 91 92 93 94

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

	notifications notifications.PubSub

95 96 97 98
	// 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
99

100
	engine *decision.Engine
101

102
	wantlist *wantlist.ThreadSafe
103 104 105

	// cancelFunc signals cancellation to the bitswap event loop
	cancelFunc func()
106 107
}

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

112 113 114 115
	// 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
116 117
	// when this context's cancel func is executed. This is difficult to
	// enforce. May this comment keep you safe.
118

119
	ctx, cancelFunc := context.WithCancel(parent)
120

Jeromy's avatar
Jeromy committed
121
	ctx = eventlog.ContextWithLoggable(ctx, eventlog.Uuid("GetBlockRequest"))
Jeromy's avatar
Jeromy committed
122
	defer log.EventBegin(ctx, "GetBlockRequest", &k).Done()
123 124 125 126

	defer func() {
		cancelFunc()
	}()
127

128
	promise, err := bs.GetBlocks(ctx, []u.Key{k})
129 130
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
131
	}
132 133

	select {
134
	case block := <-promise:
Jeromy's avatar
Jeromy committed
135
		return block, nil
136 137
	case <-parent.Done():
		return nil, parent.Err()
138
	}
139

140 141
}

142 143 144 145 146 147 148
// 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
149
func (bs *bitswap) GetBlocks(ctx context.Context, keys []u.Key) (<-chan *blocks.Block, error) {
150 151 152 153

	promise := bs.notifications.Subscribe(ctx, keys...)
	select {
	case bs.batchRequests <- keys:
154
		return promise, nil
155 156 157
	case <-ctx.Done():
		return nil, ctx.Err()
	}
Jeromy's avatar
Jeromy committed
158 159
}

160 161 162 163 164 165 166 167
// 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)
168
	return bs.network.Provide(ctx, blk.Key())
169 170
}

171
func (bs *bitswap) sendWantlistMsgToPeers(ctx context.Context, m bsmsg.BitSwapMessage, peers <-chan peer.ID) error {
Jeromy's avatar
Jeromy committed
172 173 174
	if peers == nil {
		panic("Cant send wantlist to nil peerchan")
	}
175 176

	set := pset.New()
177
	wg := sync.WaitGroup{}
178
	for peerToQuery := range peers {
179
		log.Event(ctx, "PeerToQuery", peerToQuery)
180 181

		if !set.TryAdd(peerToQuery) { //Do once per peer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182
			log.Debugf("%s skipped (already sent)", peerToQuery)
183 184
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
185
		log.Debugf("%s sending", peerToQuery)
186

187
		wg.Add(1)
188
		go func(p peer.ID) {
189
			defer wg.Done()
190 191 192
			if err := bs.send(ctx, p, m); err != nil {
				log.Error(err) // TODO remove if too verbose
			}
193
		}(peerToQuery)
Jeromy's avatar
Jeromy committed
194
	}
195
	wg.Wait()
Jeromy's avatar
Jeromy committed
196 197 198
	return nil
}

199
func (bs *bitswap) sendWantlistToPeers(ctx context.Context, peers <-chan peer.ID) error {
Jeromy's avatar
Jeromy committed
200 201
	message := bsmsg.New()
	message.SetFull(true)
202 203
	for _, wanted := range bs.wantlist.Entries() {
		message.AddEntry(wanted.Key, wanted.Priority)
Jeromy's avatar
Jeromy committed
204
	}
205 206
	return bs.sendWantlistMsgToPeers(ctx, message, peers)
}
Jeromy's avatar
Jeromy committed
207

208
func (bs *bitswap) sendWantlistToProviders(ctx context.Context) {
Jeromy's avatar
Jeromy committed
209 210 211 212 213 214
	entries := bs.wantlist.Entries()
	if len(entries) == 0 {
		log.Debug("No entries in wantlist, skipping send routine.")
		return
	}

215 216 217 218 219
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	// prepare a channel to hand off to sendWantlistToPeers
	sendToPeers := make(chan peer.ID)
Jeromy's avatar
Jeromy committed
220

221
	// Get providers for all entries in wantlist (could take a while)
Jeromy's avatar
Jeromy committed
222
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
223
	for _, e := range entries {
224
		wg.Add(1)
Jeromy's avatar
Jeromy committed
225
		go func(k u.Key) {
Jeromy's avatar
Jeromy committed
226
			defer wg.Done()
227

228
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
229
			providers := bs.network.FindProvidersAsync(child, k, maxProvidersPerRequest)
230
			for prov := range providers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231
				log.Debugf("dht returned provider %s. send wantlist", prov)
232
				sendToPeers <- prov
Jeromy's avatar
Jeromy committed
233
			}
234
		}(e.Key)
Jeromy's avatar
Jeromy committed
235
	}
236 237 238 239 240 241 242 243

	go func() {
		wg.Wait() // make sure all our children do finish.
		close(sendToPeers)
	}()

	err := bs.sendWantlistToPeers(ctx, sendToPeers)
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
244
		log.Errorf("sendWantlistToPeers error: %s", err)
245
	}
Jeromy's avatar
Jeromy committed
246 247
}

Jeromy's avatar
Jeromy committed
248
func (bs *bitswap) taskWorker(ctx context.Context) {
Jeromy's avatar
Jeromy committed
249 250 251
	for {
		select {
		case <-ctx.Done():
252
			log.Debugf("exiting")
Jeromy's avatar
Jeromy committed
253
			return
254 255 256 257
		case nextEnvelope := <-bs.engine.Outbox():
			select {
			case <-ctx.Done():
				return
Brian Tiger Chow's avatar
Brian Tiger Chow committed
258 259 260 261
			case envelope, ok := <-nextEnvelope:
				if !ok {
					continue
				}
262 263
				bs.send(ctx, envelope.Peer, envelope.Message)
			}
Jeromy's avatar
Jeromy committed
264 265 266 267
		}
	}
}

268
// TODO ensure only one active request per key
269
func (bs *bitswap) clientWorker(parent context.Context) {
270 271

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
273
	broadcastSignal := time.After(rebroadcastDelay.Get())
274
	defer cancel()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
275

Jeromy's avatar
Jeromy committed
276 277
	for {
		select {
Brian Tiger Chow's avatar
doc  
Brian Tiger Chow committed
278
		case <-broadcastSignal: // resend unfulfilled wantlist keys
279
			bs.sendWantlistToProviders(ctx)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
280
			broadcastSignal = time.After(rebroadcastDelay.Get())
281 282
		case keys := <-bs.batchRequests:
			if len(keys) == 0 {
283 284 285
				log.Warning("Received batch request for zero blocks")
				continue
			}
286
			for i, k := range keys {
287
				bs.wantlist.Add(k, kMaxPriority-i)
288
			}
289 290 291
			// NB: Optimization. Assumes that providers of key[0] are likely to
			// be able to provide for all keys. This currently holds true in most
			// every situation. Later, this assumption may not hold as true.
292
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
293
			providers := bs.network.FindProvidersAsync(child, keys[0], maxProvidersPerRequest)
294
			err := bs.sendWantlistToPeers(ctx, providers)
295 296
			if err != nil {
				log.Errorf("error sending wantlist: %s", err)
Jeromy's avatar
Jeromy committed
297
			}
298
		case <-parent.Done():
Jeromy's avatar
Jeromy committed
299 300 301 302 303
			return
		}
	}
}

304
// TODO(brian): handle errors
305 306
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.ID, incoming bsmsg.BitSwapMessage) (
	peer.ID, bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
307
	log.Debugf("ReceiveMessage from %s", p)
308

309
	if p == "" {
310
		log.Error("Received message from nil peer!")
311
		// TODO propagate the error upward
312
		return "", nil
313 314
	}
	if incoming == nil {
315
		log.Error("Got nil bitswap message!")
316
		// TODO propagate the error upward
317
		return "", nil
318
	}
319

Jeromy's avatar
Jeromy committed
320 321
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
322
	bs.engine.MessageReceived(p, incoming)
Jeromy's avatar
Jeromy committed
323 324
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
325

Brian Tiger Chow's avatar
Brian Tiger Chow committed
326
	for _, block := range incoming.Blocks() {
327 328
		hasBlockCtx, _ := context.WithTimeout(ctx, hasBlockTimeout)
		if err := bs.HasBlock(hasBlockCtx, block); err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
329
			log.Error(err)
Jeromy's avatar
Jeromy committed
330
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
331
	}
332
	var keys []u.Key
Brian Tiger Chow's avatar
Brian Tiger Chow committed
333
	for _, block := range incoming.Blocks() {
334
		keys = append(keys, block.Key())
335
	}
336
	bs.cancelBlocks(ctx, keys)
337

Jeromy's avatar
Jeromy committed
338
	// TODO: consider changing this function to not return anything
339
	return "", nil
340 341
}

Jeromy's avatar
Jeromy committed
342
func (bs *bitswap) cancelBlocks(ctx context.Context, bkeys []u.Key) {
343 344 345
	if len(bkeys) < 1 {
		return
	}
Jeromy's avatar
Jeromy committed
346 347 348
	message := bsmsg.New()
	message.SetFull(false)
	for _, k := range bkeys {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
349
		message.Cancel(k)
Jeromy's avatar
Jeromy committed
350
	}
351
	for _, p := range bs.engine.Peers() {
Jeromy's avatar
Jeromy committed
352 353 354 355 356 357 358
		err := bs.send(ctx, p, message)
		if err != nil {
			log.Errorf("Error sending message: %s", err)
		}
	}
}

359
func (bs *bitswap) ReceiveError(err error) {
360
	log.Errorf("Bitswap ReceiveError: %s", err)
361 362
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
363 364
}

365 366
// send strives to ensure that accounting is always performed when a message is
// sent
367
func (bs *bitswap) send(ctx context.Context, p peer.ID, m bsmsg.BitSwapMessage) error {
368
	if err := bs.network.SendMessage(ctx, p, m); err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
369
		return errors.Wrap(err)
370
	}
371
	return bs.engine.MessageSent(p, m)
372
}
373 374 375 376 377

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