bitswap.go 13.3 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"

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

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

38 39
var _ exchange.SessionExchange = (*Bitswap)(nil)

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

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

	// 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
59
)
Jeromy's avatar
Jeromy committed
60

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

69
var rebroadcastDelay = delay.Fixed(time.Minute)
70

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

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

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

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

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

105
	wm := bswm.New(ctx)
106 107 108 109 110 111 112
	sessionFactory := func(ctx context.Context, id uint64, pm bssession.PeerManager) bssm.Session {
		return bssession.New(ctx, id, wm, pm)
	}
	sessionPeerManagerFactory := func(ctx context.Context, id uint64) bssession.PeerManager {
		return bsspm.New(ctx, id, network)
	}

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

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

136 137
	// Start up bitswaps async worker routines
	bs.startWorkers(px, ctx)
138 139 140 141 142 143 144 145 146

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

147 148 149
	return bs
}

150 151
// Bitswap instances implement the bitswap protocol.
type Bitswap struct {
152 153
	// the peermanager manages sending messages to peers in a way that
	// wont block bitswap operation
154 155 156
	pm *bspm.PeerManager

	// the wantlist tracks global wants for bitswap
157
	wm *bswm.WantManager
158

159 160
	// 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
161

162 163
	// network delivers messages on behalf of the session
	network bsnet.BitSwapNetwork
164 165 166 167 168

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

169 170
	// notifications engine for receiving new blocks and routing them to the
	// appropriate user requests
171 172
	notifications notifications.PubSub

173
	// findKeys sends keys to a worker to find and connect to providers for them
174
	findKeys chan *blockRequest
175 176 177
	// 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
178
	newBlocks chan cid.Cid
179
	// provideKeys directly feeds provide workers
180
	provideKeys chan cid.Cid
181

182 183 184
	process process.Process

	// Counters for various statistics
185 186
	counterLk sync.Mutex
	counters  *counters
187 188

	// Metrics interface metrics
189 190 191
	dupMetric     metrics.Histogram
	allMetric     metrics.Histogram
	sentHistogram metrics.Histogram
Jeromy's avatar
Jeromy committed
192

193 194
	// the sessionmanager manages tracking sessions
	sm *bssm.SessionManager
195 196
}

197 198 199 200 201 202 203 204 205 206
type counters struct {
	blocksRecvd    uint64
	dupBlocksRecvd uint64
	dupDataRecvd   uint64
	blocksSent     uint64
	dataSent       uint64
	dataRecvd      uint64
	messagesRecvd  uint64
}

207
type blockRequest struct {
208
	Cid cid.Cid
209
	Ctx context.Context
210 211
}

212
// GetBlock attempts to retrieve a particular block from peers within the
213
// deadline enforced by the context.
214
func (bs *Bitswap) GetBlock(parent context.Context, k cid.Cid) (blocks.Block, error) {
215
	return bsgetter.SyncGetBlock(parent, k, bs.GetBlocks)
216 217
}

218 219
func (bs *Bitswap) WantlistForPeer(p peer.ID) []cid.Cid {
	var out []cid.Cid
220
	for _, e := range bs.engine.WantlistForPeer(p) {
221
		out = append(out, e.Cid)
222 223 224 225
	}
	return out
}

226 227 228 229
func (bs *Bitswap) LedgerForPeer(p peer.ID) *decision.Receipt {
	return bs.engine.LedgerForPeer(p)
}

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

244 245 246 247 248
	select {
	case <-bs.process.Closing():
		return nil, errors.New("bitswap is closed")
	default:
	}
249
	promise := bs.notifications.Subscribe(ctx, keys...)
250

251
	for _, k := range keys {
252
		log.Event(ctx, "Bitswap.GetBlockRequest.Start", k)
253 254
	}

255
	mses := bs.sm.GetNextSessionID()
Jeromy's avatar
Jeromy committed
256 257

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

259
	remaining := cid.NewSet()
260
	for _, k := range keys {
261
		remaining.Add(k)
262 263 264 265 266 267 268 269
	}

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

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

		var findProvsReqCh chan<- *blockRequest

284 285
		for {
			select {
Steven Allen's avatar
Steven Allen committed
286 287 288 289 290 291 292 293
			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
294 295 296 297 298
			case blk, ok := <-promise:
				if !ok {
					return
				}

Steven Allen's avatar
Steven Allen committed
299 300 301 302 303
				// No need to find providers now.
				findProvsDelay.Stop()
				findProvsDelayCh = nil
				findProvsReqCh = nil

304
				bs.CancelWants([]cid.Cid{blk.Cid()}, mses)
305
				remaining.Remove(blk.Cid())
306 307 308 309 310 311 312 313 314 315 316
				select {
				case out <- blk:
				case <-ctx.Done():
					return
				}
			case <-ctx.Done():
				return
			}
		}
	}()

Steven Allen's avatar
Steven Allen committed
317
	return out, nil
Jeromy's avatar
Jeromy committed
318 319
}

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

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

345
	err := bs.blockstore.Put(blk)
346 347
	if err != nil {
		log.Errorf("Error writing block to datastore: %s", err)
348 349
		return err
	}
350

351 352 353 354 355
	// 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
356 357
	bs.notifications.Publish(blk)

358
	bs.sm.ReceiveBlockFrom(from, blk)
359

360 361
	bs.engine.AddBlock(blk)

362
	select {
363
	case bs.newBlocks <- blk.Cid():
364
		// send block off to be reprovided
365 366
	case <-bs.process.Closing():
		return bs.process.Close()
367 368
	}
	return nil
369 370
}

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

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

380 381 382
	iblocks := incoming.Blocks()

	if len(iblocks) == 0 {
383 384 385
		return
	}

Jeromy's avatar
Jeromy committed
386 387
	wg := sync.WaitGroup{}
	for _, block := range iblocks {
388

Jeromy's avatar
Jeromy committed
389
		wg.Add(1)
390
		go func(b blocks.Block) { // TODO: this probably doesnt need to be a goroutine...
Jeromy's avatar
Jeromy committed
391
			defer wg.Done()
392

393
			bs.updateReceiveCounters(b)
394
			bs.sm.UpdateReceiveCounters(b)
395
			log.Debugf("got block %s from %s", b, p)
396

397
			// skip received blocks that are not in the wantlist
398
			if !bs.wm.IsWanted(b.Cid()) {
399 400 401
				return
			}

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

411 412
var ErrAlreadyHaveBlock = errors.New("already have block")

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

	bs.allMetric.Observe(float64(blkLen))
	if has {
423
		bs.dupMetric.Observe(float64(blkLen))
424 425
	}

426 427
	bs.counterLk.Lock()
	defer bs.counterLk.Unlock()
428
	c := bs.counters
429

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

438
// Connected/Disconnected warns bitswap about peer connections.
439
func (bs *Bitswap) PeerConnected(p peer.ID) {
440 441
	initialWants := bs.wm.CurrentBroadcastWants()
	bs.pm.Connected(p, initialWants)
442
	bs.engine.PeerConnected(p)
443 444
}

445
// Connected/Disconnected warns bitswap about peer connections.
446
func (bs *Bitswap) PeerDisconnected(p peer.ID) {
447
	bs.pm.Disconnected(p)
448
	bs.engine.PeerDisconnected(p)
449 450
}

451
func (bs *Bitswap) ReceiveError(err error) {
452
	log.Infof("Bitswap ReceiveError: %s", err)
453 454
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
455 456
}

457
func (bs *Bitswap) Close() error {
458
	return bs.process.Close()
459
}
460

461
func (bs *Bitswap) GetWantlist() []cid.Cid {
462
	entries := bs.wm.CurrentWants()
463
	out := make([]cid.Cid, 0, len(entries))
464
	for _, e := range entries {
465
		out = append(out, e.Cid)
466 467 468
	}
	return out
}
469 470 471 472

func (bs *Bitswap) IsOnline() bool {
	return true
}
473 474 475 476

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