bitswap.go 12.6 KB
Newer Older
1
// package bitswap implements the IPFS exchange interface with the BitSwap
Brian Tiger Chow's avatar
Brian Tiger Chow committed
2
// bilateral exchange protocol.
3 4 5
package bitswap

import (
6
	"context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7
	"errors"
8
	"math"
9
	"sync"
Jeromy's avatar
Jeromy committed
10
	"sync/atomic"
Jeromy's avatar
Jeromy committed
11 12
	"time"

Jeromy's avatar
Jeromy committed
13 14 15 16
	decision "github.com/ipfs/go-bitswap/decision"
	bsmsg "github.com/ipfs/go-bitswap/message"
	bsnet "github.com/ipfs/go-bitswap/network"
	notifications "github.com/ipfs/go-bitswap/notifications"
Jeromy's avatar
Jeromy committed
17

Jeromy's avatar
Jeromy committed
18 19 20 21 22 23 24 25 26 27 28
	blocks "github.com/ipfs/go-block-format"
	cid "github.com/ipfs/go-cid"
	blockstore "github.com/ipfs/go-ipfs-blockstore"
	delay "github.com/ipfs/go-ipfs-delay"
	exchange "github.com/ipfs/go-ipfs-exchange-interface"
	flags "github.com/ipfs/go-ipfs-flags"
	logging "github.com/ipfs/go-log"
	metrics "github.com/ipfs/go-metrics-interface"
	process "github.com/jbenet/goprocess"
	procctx "github.com/jbenet/goprocess/context"
	peer "github.com/libp2p/go-libp2p-peer"
29 30
)

Jeromy's avatar
Jeromy committed
31
var log = logging.Logger("bitswap")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
32

33 34
var _ exchange.SessionExchange = (*Bitswap)(nil)

Brian Tiger Chow's avatar
Brian Tiger Chow committed
35
const (
Brian Tiger Chow's avatar
Brian Tiger Chow committed
36 37 38
	// 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
39 40
	// TODO: if a 'non-nice' strategy is implemented, consider increasing this value
	maxProvidersPerRequest = 3
Steven Allen's avatar
Steven Allen committed
41
	findProviderDelay      = 1 * time.Second
Brian Tiger Chow's avatar
Brian Tiger Chow committed
42
	providerRequestTimeout = time.Second * 10
43 44
	provideTimeout         = time.Second * 15
	sizeBatchRequestChan   = 32
45 46
	// kMaxPriority is the max priority as defined by the bitswap protocol
	kMaxPriority = math.MaxInt32
Jeromy's avatar
Jeromy committed
47
)
48

Jeromy's avatar
Jeromy committed
49
var (
50 51 52
	HasBlockBufferSize    = 256
	provideKeysBufferSize = 2048
	provideWorkerMax      = 512
53 54 55

	// the 1<<18+15 is to observe old file chunks that are 1<<18 + 14 in size
	metricsBuckets = []float64{1 << 6, 1 << 10, 1 << 14, 1 << 18, 1<<18 + 15, 1 << 22}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
56
)
Jeromy's avatar
Jeromy committed
57

Jeromy's avatar
Jeromy committed
58 59 60 61 62 63 64 65
func init() {
	if flags.LowMemMode {
		HasBlockBufferSize = 64
		provideKeysBufferSize = 512
		provideWorkerMax = 16
	}
}

66
var rebroadcastDelay = delay.Fixed(time.Minute)
67

Brian Tiger Chow's avatar
Brian Tiger Chow committed
68 69 70 71
// 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.
Łukasz Magiera's avatar
Łukasz Magiera committed
72 73
func New(parent context.Context, network bsnet.BitSwapNetwork,
	bstore blockstore.Blockstore) exchange.Interface {
74

75 76
	// important to use provided parent context (since it may include important
	// loggable data). It's probably not a good idea to allow bitswap to be
77
	// coupled to the concerns of the ipfs daemon in this way.
78 79 80 81
	//
	// FIXME(btc) Now that bitswap manages itself using a process, it probably
	// shouldn't accept a context anymore. Clients should probably use Close()
	// exclusively. We should probably find another way to share logging data
82
	ctx, cancelFunc := context.WithCancel(parent)
83
	ctx = metrics.CtxSubScope(ctx, "bitswap")
84
	dupHist := metrics.NewCtx(ctx, "recv_dup_blocks_bytes", "Summary of duplicate"+
85
		" data blocks recived").Histogram(metricsBuckets)
86
	allHist := metrics.NewCtx(ctx, "recv_all_blocks_bytes", "Summary of all"+
87
		" data blocks recived").Histogram(metricsBuckets)
88

89
	notif := notifications.New()
90 91 92 93 94
	px := process.WithTeardown(func() error {
		notif.Shutdown()
		return nil
	})

95
	bs := &Bitswap{
96
		blockstore:    bstore,
97
		notifications: notif,
98
		engine:        decision.NewEngine(ctx, bstore), // TODO close the engine with Close() method
99
		network:       network,
100
		findKeys:      make(chan *blockRequest, sizeBatchRequestChan),
101
		process:       px,
102 103
		newBlocks:     make(chan cid.Cid, HasBlockBufferSize),
		provideKeys:   make(chan cid.Cid, provideKeysBufferSize),
104
		wm:            NewWantManager(ctx, network),
105
		counters:      new(counters),
106 107 108

		dupMetric: dupHist,
		allMetric: allHist,
109
	}
110
	go bs.wm.Run()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
111
	network.SetDelegate(bs)
112

113 114
	// Start up bitswaps async worker routines
	bs.startWorkers(px, ctx)
115 116 117 118 119 120 121 122 123

	// bind the context and process.
	// do it over here to avoid closing before all setup is done.
	go func() {
		<-px.Closing() // process closes first
		cancelFunc()
	}()
	procctx.CloseAfterContext(px, ctx) // parent cancelled first

124 125 126
	return bs
}

127 128
// Bitswap instances implement the bitswap protocol.
type Bitswap struct {
129 130 131
	// the peermanager manages sending messages to peers in a way that
	// wont block bitswap operation
	wm *WantManager
132

133 134
	// the engine is the bit of logic that decides who to send which blocks to
	engine *decision.Engine
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135

136 137
	// network delivers messages on behalf of the session
	network bsnet.BitSwapNetwork
138 139 140 141 142

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

143 144
	// notifications engine for receiving new blocks and routing them to the
	// appropriate user requests
145 146
	notifications notifications.PubSub

147
	// findKeys sends keys to a worker to find and connect to providers for them
148
	findKeys chan *blockRequest
149 150 151
	// newBlocks is a channel for newly added blocks to be provided to the
	// network.  blocks pushed down this channel get buffered and fed to the
	// provideKeys channel later on to avoid too much network activity
152
	newBlocks chan cid.Cid
153
	// provideKeys directly feeds provide workers
154
	provideKeys chan cid.Cid
155

156 157 158
	process process.Process

	// Counters for various statistics
159 160
	counterLk sync.Mutex
	counters  *counters
161 162 163 164

	// Metrics interface metrics
	dupMetric metrics.Histogram
	allMetric metrics.Histogram
Jeromy's avatar
Jeromy committed
165 166 167 168

	// Sessions
	sessions []*Session
	sessLk   sync.Mutex
Jeromy's avatar
Jeromy committed
169 170 171

	sessID   uint64
	sessIDLk sync.Mutex
172 173
}

174 175 176 177 178 179 180 181 182 183
type counters struct {
	blocksRecvd    uint64
	dupBlocksRecvd uint64
	dupDataRecvd   uint64
	blocksSent     uint64
	dataSent       uint64
	dataRecvd      uint64
	messagesRecvd  uint64
}

184
type blockRequest struct {
185
	Cid cid.Cid
186
	Ctx context.Context
187 188
}

189
// GetBlock attempts to retrieve a particular block from peers within the
190
// deadline enforced by the context.
191
func (bs *Bitswap) GetBlock(parent context.Context, k cid.Cid) (blocks.Block, error) {
Jeromy's avatar
Jeromy committed
192
	return getBlock(parent, k, bs.GetBlocks)
193 194
}

195 196
func (bs *Bitswap) WantlistForPeer(p peer.ID) []cid.Cid {
	var out []cid.Cid
197
	for _, e := range bs.engine.WantlistForPeer(p) {
198
		out = append(out, e.Cid)
199 200 201 202
	}
	return out
}

203 204 205 206
func (bs *Bitswap) LedgerForPeer(p peer.ID) *decision.Receipt {
	return bs.engine.LedgerForPeer(p)
}

207 208 209 210 211 212 213
// 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)
214
func (bs *Bitswap) GetBlocks(ctx context.Context, keys []cid.Cid) (<-chan blocks.Block, error) {
215
	if len(keys) == 0 {
216
		out := make(chan blocks.Block)
217 218 219 220
		close(out)
		return out, nil
	}

221 222 223 224 225
	select {
	case <-bs.process.Closing():
		return nil, errors.New("bitswap is closed")
	default:
	}
226
	promise := bs.notifications.Subscribe(ctx, keys...)
227

228
	for _, k := range keys {
229
		log.Event(ctx, "Bitswap.GetBlockRequest.Start", k)
230 231
	}

Jeromy's avatar
Jeromy committed
232 233 234
	mses := bs.getNextSessionID()

	bs.wm.WantBlocks(ctx, keys, nil, mses)
235

236
	remaining := cid.NewSet()
237
	for _, k := range keys {
238
		remaining.Add(k)
239 240 241 242 243 244 245 246
	}

	out := make(chan blocks.Block)
	go func() {
		ctx, cancel := context.WithCancel(ctx)
		defer cancel()
		defer close(out)
		defer func() {
247
			// can't just defer this call on its own, arguments are resolved *when* the defer is created
Jeromy's avatar
Jeromy committed
248
			bs.CancelWants(remaining.Keys(), mses)
249
		}()
Steven Allen's avatar
Steven Allen committed
250 251 252 253 254 255 256 257 258 259 260
		findProvsDelay := time.NewTimer(findProviderDelay)
		defer findProvsDelay.Stop()

		findProvsDelayCh := findProvsDelay.C
		req := &blockRequest{
			Cid: keys[0],
			Ctx: ctx,
		}

		var findProvsReqCh chan<- *blockRequest

261 262
		for {
			select {
Steven Allen's avatar
Steven Allen committed
263 264 265 266 267 268 269 270
			case <-findProvsDelayCh:
				// 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.
				findProvsReqCh = bs.findKeys
				findProvsDelayCh = nil
			case findProvsReqCh <- req:
				findProvsReqCh = nil
271 272 273 274 275
			case blk, ok := <-promise:
				if !ok {
					return
				}

Steven Allen's avatar
Steven Allen committed
276 277 278 279 280
				// No need to find providers now.
				findProvsDelay.Stop()
				findProvsDelayCh = nil
				findProvsReqCh = nil

281
				bs.CancelWants([]cid.Cid{blk.Cid()}, mses)
282
				remaining.Remove(blk.Cid())
283 284 285 286 287 288 289 290 291 292 293
				select {
				case out <- blk:
				case <-ctx.Done():
					return
				}
			case <-ctx.Done():
				return
			}
		}
	}()

Steven Allen's avatar
Steven Allen committed
294
	return out, nil
Jeromy's avatar
Jeromy committed
295 296
}

Jeromy's avatar
Jeromy committed
297 298 299 300 301 302 303
func (bs *Bitswap) getNextSessionID() uint64 {
	bs.sessIDLk.Lock()
	defer bs.sessIDLk.Unlock()
	bs.sessID++
	return bs.sessID
}

304
// CancelWant removes a given key from the wantlist
305
func (bs *Bitswap) CancelWants(cids []cid.Cid, ses uint64) {
306 307 308
	if len(cids) == 0 {
		return
	}
Jeromy's avatar
Jeromy committed
309
	bs.wm.CancelWants(context.Background(), cids, nil, ses)
310 311
}

Łukasz Magiera's avatar
Łukasz Magiera committed
312
// HasBlock announces the existence of a block to this bitswap service. The
313
// service will potentially notify its peers.
314
func (bs *Bitswap) HasBlock(blk blocks.Block) error {
315 316 317 318 319 320 321 322
	return bs.receiveBlockFrom(blk, "")
}

// TODO: Some of this stuff really only needs to be done when adding a block
// from the user, not when receiving it from the network.
// In case you run `git blame` on this comment, I'll save you some time: ask
// @whyrusleeping, I don't know the answers you seek.
func (bs *Bitswap) receiveBlockFrom(blk blocks.Block, from peer.ID) error {
323 324 325 326 327
	select {
	case <-bs.process.Closing():
		return errors.New("bitswap is closed")
	default:
	}
328

329
	err := bs.blockstore.Put(blk)
330 331
	if err != nil {
		log.Errorf("Error writing block to datastore: %s", err)
332 333
		return err
	}
334

335 336 337 338 339
	// NOTE: There exists the possiblity for a race condition here.  If a user
	// creates a node, then adds it to the dagservice while another goroutine
	// is waiting on a GetBlock for that object, they will receive a reference
	// to the same node. We should address this soon, but i'm not going to do
	// it now as it requires more thought and isnt causing immediate problems.
Jeromy's avatar
Jeromy committed
340 341
	bs.notifications.Publish(blk)

342
	k := blk.Cid()
343
	ks := []cid.Cid{k}
344 345 346
	for _, s := range bs.SessionsForBlock(k) {
		s.receiveBlockFrom(from, blk)
		bs.CancelWants(ks, s.id)
347 348
	}

349 350
	bs.engine.AddBlock(blk)

351
	select {
352
	case bs.newBlocks <- blk.Cid():
353
		// send block off to be reprovided
354 355
	case <-bs.process.Closing():
		return bs.process.Close()
356 357
	}
	return nil
358 359
}

Jeromy's avatar
Jeromy committed
360
// SessionsForBlock returns a slice of all sessions that may be interested in the given cid
361
func (bs *Bitswap) SessionsForBlock(c cid.Cid) []*Session {
Jeromy's avatar
Jeromy committed
362 363 364 365 366
	bs.sessLk.Lock()
	defer bs.sessLk.Unlock()

	var out []*Session
	for _, s := range bs.sessions {
Jeromy's avatar
Jeromy committed
367
		if s.interestedIn(c) {
Jeromy's avatar
Jeromy committed
368 369 370 371 372 373
			out = append(out, s)
		}
	}
	return out
}

374
func (bs *Bitswap) ReceiveMessage(ctx context.Context, p peer.ID, incoming bsmsg.BitSwapMessage) {
375
	atomic.AddUint64(&bs.counters.messagesRecvd, 1)
Jeromy's avatar
Jeromy committed
376

Jeromy's avatar
Jeromy committed
377 378
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
379
	bs.engine.MessageReceived(p, incoming)
Jeromy's avatar
Jeromy committed
380 381
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
382

383 384 385
	iblocks := incoming.Blocks()

	if len(iblocks) == 0 {
386 387 388
		return
	}

Jeromy's avatar
Jeromy committed
389 390 391
	wg := sync.WaitGroup{}
	for _, block := range iblocks {
		wg.Add(1)
392
		go func(b blocks.Block) { // TODO: this probably doesnt need to be a goroutine...
Jeromy's avatar
Jeromy committed
393
			defer wg.Done()
394

395
			bs.updateReceiveCounters(b)
396

397
			log.Debugf("got block %s from %s", b, p)
398 399 400

			if err := bs.receiveBlockFrom(b, p); err != nil {
				log.Warningf("ReceiveMessage recvBlockFrom error: %s", err)
Jeromy's avatar
Jeromy committed
401
			}
402
			log.Event(ctx, "Bitswap.GetBlockRequest.End", b.Cid())
Jeromy's avatar
Jeromy committed
403
		}(block)
404
	}
Jeromy's avatar
Jeromy committed
405
	wg.Wait()
406 407
}

408 409
var ErrAlreadyHaveBlock = errors.New("already have block")

410
func (bs *Bitswap) updateReceiveCounters(b blocks.Block) {
411
	blkLen := len(b.RawData())
412
	has, err := bs.blockstore.Has(b.Cid())
413 414
	if err != nil {
		log.Infof("blockstore.Has error: %s", err)
415
		return
416
	}
417 418 419

	bs.allMetric.Observe(float64(blkLen))
	if has {
420
		bs.dupMetric.Observe(float64(blkLen))
421 422
	}

423 424
	bs.counterLk.Lock()
	defer bs.counterLk.Unlock()
425
	c := bs.counters
426

427 428
	c.blocksRecvd++
	c.dataRecvd += uint64(len(b.RawData()))
429
	if has {
430 431
		c.dupBlocksRecvd++
		c.dupDataRecvd += uint64(blkLen)
432 433 434
	}
}

435
// Connected/Disconnected warns bitswap about peer connections
436
func (bs *Bitswap) PeerConnected(p peer.ID) {
437
	bs.wm.Connected(p)
438
	bs.engine.PeerConnected(p)
439 440 441
}

// Connected/Disconnected warns bitswap about peer connections
442
func (bs *Bitswap) PeerDisconnected(p peer.ID) {
443
	bs.wm.Disconnected(p)
444
	bs.engine.PeerDisconnected(p)
445 446
}

447
func (bs *Bitswap) ReceiveError(err error) {
448
	log.Infof("Bitswap ReceiveError: %s", err)
449 450
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
451 452
}

453
func (bs *Bitswap) Close() error {
454
	return bs.process.Close()
455
}
456

457
func (bs *Bitswap) GetWantlist() []cid.Cid {
458
	entries := bs.wm.wl.Entries()
459
	out := make([]cid.Cid, 0, len(entries))
460
	for _, e := range entries {
461
		out = append(out, e.Cid)
462 463 464
	}
	return out
}
465 466 467 468

func (bs *Bitswap) IsOnline() bool {
	return true
}