bitswap.go 10.2 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"
20 21
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
22
	errors "github.com/jbenet/go-ipfs/util/debugerror"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
23
	"github.com/jbenet/go-ipfs/util/delay"
Jeromy's avatar
Jeromy committed
24
	eventlog "github.com/jbenet/go-ipfs/util/eventlog"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
25
	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 31 32 33 34 35
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
Brian Tiger Chow's avatar
Brian Tiger Chow committed
36
	sizeBatchRequestChan   = 32
37 38
	// kMaxPriority is the max priority as defined by the bitswap protocol
	kMaxPriority = math.MaxInt32
Brian Tiger Chow's avatar
Brian Tiger Chow committed
39
)
Jeromy's avatar
Jeromy committed
40

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

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

52 53
	ctx, cancelFunc := context.WithCancel(parent)

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

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

	return bs
}

78 79 80
// bitswap instances implement the bitswap protocol.
type bitswap struct {

81 82
	// network delivers messages on behalf of the session
	network bsnet.BitSwapNetwork
83 84 85 86 87 88

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

	// routing interface for communication
89
	routing bsnet.Routing
90 91 92

	notifications notifications.PubSub

93 94 95 96
	// 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
97

98
	engine *decision.Engine
99

100
	wantlist *wantlist.ThreadSafe
101 102 103

	// cancelFunc signals cancellation to the bitswap event loop
	cancelFunc func()
104 105
}

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

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

117
	ctx, cancelFunc := context.WithCancel(parent)
118

Jeromy's avatar
Jeromy committed
119
	ctx = eventlog.ContextWithLoggable(ctx, eventlog.Uuid("GetBlockRequest"))
120
	log.Event(ctx, "GetBlockRequestBegin", &k)
121 122 123 124 125

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

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

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

139 140
}

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

	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.routing.Provide(ctx, blk.Key())
169 170
}

171
func (bs *bitswap) sendWantListTo(ctx context.Context, peers <-chan peer.PeerInfo) error {
Jeromy's avatar
Jeromy committed
172 173 174
	if peers == nil {
		panic("Cant send wantlist to nil peerchan")
	}
Jeromy's avatar
Jeromy committed
175
	message := bsmsg.New()
Jeromy's avatar
Jeromy committed
176
	for _, wanted := range bs.wantlist.Entries() {
177
		message.AddEntry(wanted.Key, wanted.Priority)
Jeromy's avatar
Jeromy committed
178
	}
179
	wg := sync.WaitGroup{}
180 181
	for peerToQuery := range peers {
		log.Event(ctx, "PeerToQuery", peerToQuery.ID)
182
		wg.Add(1)
183
		bs.network.Peerstore().AddAddresses(peerToQuery.ID, peerToQuery.Addrs)
184
		go func(p peer.ID) {
185
			defer wg.Done()
186 187
			if err := bs.send(ctx, p, message); err != nil {
				log.Error(err)
Jeromy's avatar
Jeromy committed
188 189
				return
			}
190
		}(peerToQuery.ID)
Jeromy's avatar
Jeromy committed
191
	}
192
	wg.Wait()
Jeromy's avatar
Jeromy committed
193 194 195
	return nil
}

196
func (bs *bitswap) sendWantlistToProviders(ctx context.Context, wantlist *wantlist.ThreadSafe) {
197 198 199
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

Jeromy's avatar
Jeromy committed
200 201 202
	message := bsmsg.New()
	message.SetFull(true)
	for _, e := range bs.wantlist.Entries() {
203
		message.AddEntry(e.Key, e.Priority)
Jeromy's avatar
Jeromy committed
204 205
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
206
	set := pset.New()
Jeromy's avatar
Jeromy committed
207

208
	// Get providers for all entries in wantlist (could take a while)
Jeromy's avatar
Jeromy committed
209
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
210
	for _, e := range wantlist.Entries() {
211
		wg.Add(1)
Jeromy's avatar
Jeromy committed
212
		go func(k u.Key) {
Jeromy's avatar
Jeromy committed
213
			defer wg.Done()
214 215
			child, _ := context.WithTimeout(ctx, providerRequestTimeout)
			providers := bs.routing.FindProvidersAsync(child, k, maxProvidersPerRequest)
216
			for prov := range providers {
217
				bs.network.Peerstore().AddAddresses(prov.ID, prov.Addrs)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
218
				if set.TryAdd(prov.ID) { //Do once per peer
219
					bs.send(ctx, prov.ID, message)
Jeromy's avatar
Jeromy committed
220
				}
Jeromy's avatar
Jeromy committed
221
			}
222
		}(e.Key)
Jeromy's avatar
Jeromy committed
223
	}
Jeromy's avatar
Jeromy committed
224
	wg.Wait()
Jeromy's avatar
Jeromy committed
225 226
}

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

238
// TODO ensure only one active request per key
239
func (bs *bitswap) clientWorker(parent context.Context) {
240 241

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
243
	broadcastSignal := time.After(rebroadcastDelay.Get())
244
	defer cancel()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
245

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

279
// TODO(brian): handle errors
280 281
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.ID, incoming bsmsg.BitSwapMessage) (
	peer.ID, bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
282
	log.Debugf("ReceiveMessage from %s", p)
283

284
	if p == "" {
285
		log.Error("Received message from nil peer!")
286
		// TODO propagate the error upward
287
		return "", nil
288 289
	}
	if incoming == nil {
290
		log.Error("Got nil bitswap message!")
291
		// TODO propagate the error upward
292
		return "", nil
293
	}
294

Jeromy's avatar
Jeromy committed
295 296
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
297
	bs.engine.MessageReceived(p, incoming)
Jeromy's avatar
Jeromy committed
298 299
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
300

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

Jeromy's avatar
Jeromy committed
313
	// TODO: consider changing this function to not return anything
314
	return "", nil
315 316
}

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

334
func (bs *bitswap) ReceiveError(err error) {
335
	log.Errorf("Bitswap ReceiveError: %s", err)
336 337
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
338 339
}

340 341
// send strives to ensure that accounting is always performed when a message is
// sent
342
func (bs *bitswap) send(ctx context.Context, p peer.ID, m bsmsg.BitSwapMessage) error {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
343
	log.Event(ctx, "DialPeer", p)
344
	err := bs.network.DialPeer(ctx, p)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
345 346 347
	if err != nil {
		return errors.Wrap(err)
	}
348
	if err := bs.network.SendMessage(ctx, p, m); err != nil {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
349
		return errors.Wrap(err)
350
	}
351
	return bs.engine.MessageSent(p, m)
352
}
353 354 355 356 357

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