bitswap.go 13.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
	"sync"
Jeromy's avatar
Jeromy committed
9
	"sync/atomic"
Jeromy's avatar
Jeromy committed
10 11
	"time"

12 13
	bssrs "github.com/ipfs/go-bitswap/sessionrequestsplitter"

Jeromy's avatar
Jeromy committed
14
	decision "github.com/ipfs/go-bitswap/decision"
15
	bsgetter "github.com/ipfs/go-bitswap/getter"
Jeromy's avatar
Jeromy committed
16
	bsmsg "github.com/ipfs/go-bitswap/message"
17
	bsmq "github.com/ipfs/go-bitswap/messagequeue"
Jeromy's avatar
Jeromy committed
18 19
	bsnet "github.com/ipfs/go-bitswap/network"
	notifications "github.com/ipfs/go-bitswap/notifications"
20
	bspm "github.com/ipfs/go-bitswap/peermanager"
21
	bssession "github.com/ipfs/go-bitswap/session"
22
	bssm "github.com/ipfs/go-bitswap/sessionmanager"
23
	bsspm "github.com/ipfs/go-bitswap/sessionpeermanager"
24
	bswm "github.com/ipfs/go-bitswap/wantmanager"
Jeromy's avatar
Jeromy committed
25 26 27 28 29 30 31 32 33 34 35
	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"
36 37
)

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

40 41
var _ exchange.SessionExchange = (*Bitswap)(nil)

Brian Tiger Chow's avatar
Brian Tiger Chow committed
42
const (
Brian Tiger Chow's avatar
Brian Tiger Chow committed
43 44 45
	// 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
46 47
	// TODO: if a 'non-nice' strategy is implemented, consider increasing this value
	maxProvidersPerRequest = 3
Steven Allen's avatar
Steven Allen committed
48
	findProviderDelay      = 1 * time.Second
Brian Tiger Chow's avatar
Brian Tiger Chow committed
49
	providerRequestTimeout = time.Second * 10
50 51
	provideTimeout         = time.Second * 15
	sizeBatchRequestChan   = 32
Jeromy's avatar
Jeromy committed
52
)
53

Jeromy's avatar
Jeromy committed
54
var (
55 56 57
	HasBlockBufferSize    = 256
	provideKeysBufferSize = 2048
	provideWorkerMax      = 512
58 59 60

	// 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
61
)
Jeromy's avatar
Jeromy committed
62

Jeromy's avatar
Jeromy committed
63 64 65 66 67 68 69 70
func init() {
	if flags.LowMemMode {
		HasBlockBufferSize = 64
		provideKeysBufferSize = 512
		provideWorkerMax = 16
	}
}

71
var rebroadcastDelay = delay.Fixed(time.Minute)
72

Brian Tiger Chow's avatar
Brian Tiger Chow committed
73 74 75 76
// 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
77 78
func New(parent context.Context, network bsnet.BitSwapNetwork,
	bstore blockstore.Blockstore) exchange.Interface {
79

80 81
	// 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
82
	// coupled to the concerns of the ipfs daemon in this way.
83 84 85 86
	//
	// 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
87
	ctx, cancelFunc := context.WithCancel(parent)
88
	ctx = metrics.CtxSubScope(ctx, "bitswap")
89
	dupHist := metrics.NewCtx(ctx, "recv_dup_blocks_bytes", "Summary of duplicate"+
90
		" data blocks recived").Histogram(metricsBuckets)
91
	allHist := metrics.NewCtx(ctx, "recv_all_blocks_bytes", "Summary of all"+
92
		" data blocks recived").Histogram(metricsBuckets)
93

94 95 96
	sentHistogram := metrics.NewCtx(ctx, "sent_all_blocks_bytes", "Histogram of blocks sent by"+
		" this bitswap").Histogram(metricsBuckets)

97
	notif := notifications.New()
98 99 100 101 102
	px := process.WithTeardown(func() error {
		notif.Shutdown()
		return nil
	})

103 104 105 106
	peerQueueFactory := func(p peer.ID) bspm.PeerQueue {
		return bsmq.New(p, network)
	}

107
	wm := bswm.New(ctx)
108 109
	sessionFactory := func(ctx context.Context, id uint64, pm bssession.PeerManager, srs bssession.RequestSplitter) bssm.Session {
		return bssession.New(ctx, id, wm, pm, srs)
110 111 112 113
	}
	sessionPeerManagerFactory := func(ctx context.Context, id uint64) bssession.PeerManager {
		return bsspm.New(ctx, id, network)
	}
114 115 116
	sessionRequestSplitterFactory := func(ctx context.Context) bssession.RequestSplitter {
		return bssrs.New(ctx)
	}
117

118
	bs := &Bitswap{
119
		blockstore:    bstore,
120
		notifications: notif,
121
		engine:        decision.NewEngine(ctx, bstore), // TODO close the engine with Close() method
122
		network:       network,
123
		findKeys:      make(chan *blockRequest, sizeBatchRequestChan),
124
		process:       px,
125 126
		newBlocks:     make(chan cid.Cid, HasBlockBufferSize),
		provideKeys:   make(chan cid.Cid, provideKeysBufferSize),
127
		wm:            wm,
128
		pm:            bspm.New(ctx, peerQueueFactory),
129
		sm:            bssm.New(ctx, sessionFactory, sessionPeerManagerFactory, sessionRequestSplitterFactory),
130
		counters:      new(counters),
131 132 133
		dupMetric:     dupHist,
		allMetric:     allHist,
		sentHistogram: sentHistogram,
134
	}
135 136 137 138

	bs.wm.SetDelegate(bs.pm)
	bs.pm.Startup()
	bs.wm.Startup()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
139
	network.SetDelegate(bs)
140

141 142
	// Start up bitswaps async worker routines
	bs.startWorkers(px, ctx)
143 144 145 146 147 148 149 150 151

	// 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

152 153 154
	return bs
}

155 156
// Bitswap instances implement the bitswap protocol.
type Bitswap struct {
157 158
	// the peermanager manages sending messages to peers in a way that
	// wont block bitswap operation
159 160 161
	pm *bspm.PeerManager

	// the wantlist tracks global wants for bitswap
162
	wm *bswm.WantManager
163

164 165
	// 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
166

167 168
	// network delivers messages on behalf of the session
	network bsnet.BitSwapNetwork
169 170 171 172 173

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

174 175
	// notifications engine for receiving new blocks and routing them to the
	// appropriate user requests
176 177
	notifications notifications.PubSub

178
	// findKeys sends keys to a worker to find and connect to providers for them
179
	findKeys chan *blockRequest
180 181 182
	// 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
183
	newBlocks chan cid.Cid
184
	// provideKeys directly feeds provide workers
185
	provideKeys chan cid.Cid
186

187 188 189
	process process.Process

	// Counters for various statistics
190 191
	counterLk sync.Mutex
	counters  *counters
192 193

	// Metrics interface metrics
194 195 196
	dupMetric     metrics.Histogram
	allMetric     metrics.Histogram
	sentHistogram metrics.Histogram
Jeromy's avatar
Jeromy committed
197

198 199
	// the sessionmanager manages tracking sessions
	sm *bssm.SessionManager
200 201
}

202 203 204 205 206 207 208 209 210 211
type counters struct {
	blocksRecvd    uint64
	dupBlocksRecvd uint64
	dupDataRecvd   uint64
	blocksSent     uint64
	dataSent       uint64
	dataRecvd      uint64
	messagesRecvd  uint64
}

212
type blockRequest struct {
213
	Cid cid.Cid
214
	Ctx context.Context
215 216
}

217
// GetBlock attempts to retrieve a particular block from peers within the
218
// deadline enforced by the context.
219
func (bs *Bitswap) GetBlock(parent context.Context, k cid.Cid) (blocks.Block, error) {
220
	return bsgetter.SyncGetBlock(parent, k, bs.GetBlocks)
221 222
}

223 224
func (bs *Bitswap) WantlistForPeer(p peer.ID) []cid.Cid {
	var out []cid.Cid
225
	for _, e := range bs.engine.WantlistForPeer(p) {
226
		out = append(out, e.Cid)
227 228 229 230
	}
	return out
}

231 232 233 234
func (bs *Bitswap) LedgerForPeer(p peer.ID) *decision.Receipt {
	return bs.engine.LedgerForPeer(p)
}

235 236 237 238 239 240 241
// 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)
242
func (bs *Bitswap) GetBlocks(ctx context.Context, keys []cid.Cid) (<-chan blocks.Block, error) {
243
	if len(keys) == 0 {
244
		out := make(chan blocks.Block)
245 246 247 248
		close(out)
		return out, nil
	}

249 250 251 252 253
	select {
	case <-bs.process.Closing():
		return nil, errors.New("bitswap is closed")
	default:
	}
254
	promise := bs.notifications.Subscribe(ctx, keys...)
255

256
	for _, k := range keys {
257
		log.Event(ctx, "Bitswap.GetBlockRequest.Start", k)
258 259
	}

260
	mses := bs.sm.GetNextSessionID()
Jeromy's avatar
Jeromy committed
261 262

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

264
	remaining := cid.NewSet()
265
	for _, k := range keys {
266
		remaining.Add(k)
267 268 269 270 271 272 273 274
	}

	out := make(chan blocks.Block)
	go func() {
		ctx, cancel := context.WithCancel(ctx)
		defer cancel()
		defer close(out)
		defer func() {
275
			// can't just defer this call on its own, arguments are resolved *when* the defer is created
Jeromy's avatar
Jeromy committed
276
			bs.CancelWants(remaining.Keys(), mses)
277
		}()
Steven Allen's avatar
Steven Allen committed
278 279 280 281 282 283 284 285 286 287 288
		findProvsDelay := time.NewTimer(findProviderDelay)
		defer findProvsDelay.Stop()

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

		var findProvsReqCh chan<- *blockRequest

289 290
		for {
			select {
Steven Allen's avatar
Steven Allen committed
291 292 293 294 295 296 297 298
			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
299 300 301 302 303
			case blk, ok := <-promise:
				if !ok {
					return
				}

Steven Allen's avatar
Steven Allen committed
304 305 306 307 308
				// No need to find providers now.
				findProvsDelay.Stop()
				findProvsDelayCh = nil
				findProvsReqCh = nil

309
				bs.CancelWants([]cid.Cid{blk.Cid()}, mses)
310
				remaining.Remove(blk.Cid())
311 312 313 314 315 316 317 318 319 320 321
				select {
				case out <- blk:
				case <-ctx.Done():
					return
				}
			case <-ctx.Done():
				return
			}
		}
	}()

Steven Allen's avatar
Steven Allen committed
322
	return out, nil
Jeromy's avatar
Jeromy committed
323 324
}

325
// CancelWants removes a given key from the wantlist.
326
func (bs *Bitswap) CancelWants(cids []cid.Cid, ses uint64) {
327 328 329
	if len(cids) == 0 {
		return
	}
Jeromy's avatar
Jeromy committed
330
	bs.wm.CancelWants(context.Background(), cids, nil, ses)
331 332
}

Łukasz Magiera's avatar
Łukasz Magiera committed
333
// HasBlock announces the existence of a block to this bitswap service. The
334
// service will potentially notify its peers.
335
func (bs *Bitswap) HasBlock(blk blocks.Block) error {
336 337 338 339 340 341 342 343
	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 {
344 345 346 347 348
	select {
	case <-bs.process.Closing():
		return errors.New("bitswap is closed")
	default:
	}
349

350
	err := bs.blockstore.Put(blk)
351 352
	if err != nil {
		log.Errorf("Error writing block to datastore: %s", err)
353 354
		return err
	}
355

356 357 358 359 360
	// 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
361 362
	bs.notifications.Publish(blk)

363
	bs.sm.ReceiveBlockFrom(from, blk)
364

365 366
	bs.engine.AddBlock(blk)

367
	select {
368
	case bs.newBlocks <- blk.Cid():
369
		// send block off to be reprovided
370 371
	case <-bs.process.Closing():
		return bs.process.Close()
372 373
	}
	return nil
374 375
}

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

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

385 386 387
	iblocks := incoming.Blocks()

	if len(iblocks) == 0 {
388 389 390
		return
	}

Jeromy's avatar
Jeromy committed
391 392
	wg := sync.WaitGroup{}
	for _, block := range iblocks {
393

Jeromy's avatar
Jeromy committed
394
		wg.Add(1)
395
		go func(b blocks.Block) { // TODO: this probably doesnt need to be a goroutine...
Jeromy's avatar
Jeromy committed
396
			defer wg.Done()
397

398
			bs.updateReceiveCounters(b)
399
			bs.sm.UpdateReceiveCounters(b)
400
			log.Debugf("got block %s from %s", b, p)
401

402
			// skip received blocks that are not in the wantlist
403
			if !bs.wm.IsWanted(b.Cid()) {
404 405 406
				return
			}

407 408
			if err := bs.receiveBlockFrom(b, p); err != nil {
				log.Warningf("ReceiveMessage recvBlockFrom error: %s", err)
Jeromy's avatar
Jeromy committed
409
			}
410
			log.Event(ctx, "Bitswap.GetBlockRequest.End", b.Cid())
Jeromy's avatar
Jeromy committed
411
		}(block)
412
	}
Jeromy's avatar
Jeromy committed
413
	wg.Wait()
414 415
}

416 417
var ErrAlreadyHaveBlock = errors.New("already have block")

418
func (bs *Bitswap) updateReceiveCounters(b blocks.Block) {
419
	blkLen := len(b.RawData())
420
	has, err := bs.blockstore.Has(b.Cid())
421 422
	if err != nil {
		log.Infof("blockstore.Has error: %s", err)
423
		return
424
	}
425 426 427

	bs.allMetric.Observe(float64(blkLen))
	if has {
428
		bs.dupMetric.Observe(float64(blkLen))
429 430
	}

431 432
	bs.counterLk.Lock()
	defer bs.counterLk.Unlock()
433
	c := bs.counters
434

435 436
	c.blocksRecvd++
	c.dataRecvd += uint64(len(b.RawData()))
437
	if has {
438 439
		c.dupBlocksRecvd++
		c.dupDataRecvd += uint64(blkLen)
440 441 442
	}
}

443
// Connected/Disconnected warns bitswap about peer connections.
444
func (bs *Bitswap) PeerConnected(p peer.ID) {
445 446
	initialWants := bs.wm.CurrentBroadcastWants()
	bs.pm.Connected(p, initialWants)
447
	bs.engine.PeerConnected(p)
448 449
}

450
// Connected/Disconnected warns bitswap about peer connections.
451
func (bs *Bitswap) PeerDisconnected(p peer.ID) {
452
	bs.pm.Disconnected(p)
453
	bs.engine.PeerDisconnected(p)
454 455
}

456
func (bs *Bitswap) ReceiveError(err error) {
457
	log.Infof("Bitswap ReceiveError: %s", err)
458 459
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
460 461
}

462
func (bs *Bitswap) Close() error {
463
	return bs.process.Close()
464
}
465

466
func (bs *Bitswap) GetWantlist() []cid.Cid {
467
	entries := bs.wm.CurrentWants()
468
	out := make([]cid.Cid, 0, len(entries))
469
	for _, e := range entries {
470
		out = append(out, e.Cid)
471 472 473
	}
	return out
}
474 475 476 477

func (bs *Bitswap) IsOnline() bool {
	return true
}
478 479 480 481

func (bs *Bitswap) NewSession(ctx context.Context) exchange.Fetcher {
	return bs.sm.NewSession(ctx)
}