bitswap.go 10 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
	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
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{
64
		blockstore:    bstore,
65
		cancelFunc:    cancelFunc,
66
		notifications: notif,
67
		engine:        decision.NewEngine(ctx, bstore),
68
		network:       network,
69
		wantlist:      wantlist.NewThreadSafe(),
Brian Tiger Chow's avatar
Brian Tiger Chow committed
70
		batchRequests: make(chan []u.Key, sizeBatchRequestChan),
71
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
72
	network.SetDelegate(bs)
73
	go bs.clientWorker(ctx)
Jeromy's avatar
Jeromy committed
74
	go bs.taskWorker(ctx)
75 76 77 78

	return bs
}

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

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

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

	notifications notifications.PubSub

91 92 93 94
	// 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
95

96
	engine *decision.Engine
97

98
	wantlist *wantlist.ThreadSafe
99 100 101

	// cancelFunc signals cancellation to the bitswap event loop
	cancelFunc func()
102 103
}

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

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

115
	ctx, cancelFunc := context.WithCancel(parent)
116

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

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

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

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

137 138
}

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

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

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

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

193
func (bs *bitswap) sendWantlistToProviders(ctx context.Context, wantlist *wantlist.ThreadSafe) {
194 195 196
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

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

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

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

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

234
// TODO ensure only one active request per key
235
func (bs *bitswap) clientWorker(parent context.Context) {
236 237

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
239
	broadcastSignal := time.After(rebroadcastDelay.Get())
240
	defer cancel()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
241

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

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

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

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

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

Jeromy's avatar
Jeromy committed
309
	// TODO: consider changing this function to not return anything
310
	return "", nil
311 312
}

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

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

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

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