bitswap.go 12.9 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 20
	bssm "github.com/ipfs/go-bitswap/sessionmanager"
	bswm "github.com/ipfs/go-bitswap/wantmanager"
Jeromy's avatar
Jeromy committed
21

Jeromy's avatar
Jeromy committed
22 23 24 25 26 27 28 29 30 31 32
	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"
33 34
)

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

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

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

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

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

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

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

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

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

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

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

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

104
	wm := bswm.New(ctx)
105
	bs := &Bitswap{
106
		blockstore:    bstore,
107
		notifications: notif,
108
		engine:        decision.NewEngine(ctx, bstore), // TODO close the engine with Close() method
109
		network:       network,
110
		findKeys:      make(chan *blockRequest, sizeBatchRequestChan),
111
		process:       px,
112 113
		newBlocks:     make(chan cid.Cid, HasBlockBufferSize),
		provideKeys:   make(chan cid.Cid, provideKeysBufferSize),
114
		wm:            wm,
115
		pm:            bspm.New(ctx, peerQueueFactory),
116
		sm:            bssm.New(ctx, wm, network),
117
		counters:      new(counters),
118 119 120
		dupMetric:     dupHist,
		allMetric:     allHist,
		sentHistogram: sentHistogram,
121
	}
122 123 124 125

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

128 129
	// Start up bitswaps async worker routines
	bs.startWorkers(px, ctx)
130 131 132 133 134 135 136 137 138

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

139 140 141
	return bs
}

142 143
// Bitswap instances implement the bitswap protocol.
type Bitswap struct {
144 145
	// the peermanager manages sending messages to peers in a way that
	// wont block bitswap operation
146 147 148
	pm *bspm.PeerManager

	// the wantlist tracks global wants for bitswap
149
	wm *bswm.WantManager
150

151 152
	// 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
153

154 155
	// network delivers messages on behalf of the session
	network bsnet.BitSwapNetwork
156 157 158 159 160

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

161 162
	// notifications engine for receiving new blocks and routing them to the
	// appropriate user requests
163 164
	notifications notifications.PubSub

165
	// findKeys sends keys to a worker to find and connect to providers for them
166
	findKeys chan *blockRequest
167 168 169
	// 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
170
	newBlocks chan cid.Cid
171
	// provideKeys directly feeds provide workers
172
	provideKeys chan cid.Cid
173

174 175 176
	process process.Process

	// Counters for various statistics
177 178
	counterLk sync.Mutex
	counters  *counters
179 180

	// Metrics interface metrics
181 182 183
	dupMetric     metrics.Histogram
	allMetric     metrics.Histogram
	sentHistogram metrics.Histogram
Jeromy's avatar
Jeromy committed
184

185 186
	// the sessionmanager manages tracking sessions
	sm *bssm.SessionManager
187 188
}

189 190 191 192 193 194 195 196 197 198
type counters struct {
	blocksRecvd    uint64
	dupBlocksRecvd uint64
	dupDataRecvd   uint64
	blocksSent     uint64
	dataSent       uint64
	dataRecvd      uint64
	messagesRecvd  uint64
}

199
type blockRequest struct {
200
	Cid cid.Cid
201
	Ctx context.Context
202 203
}

204
// GetBlock attempts to retrieve a particular block from peers within the
205
// deadline enforced by the context.
206
func (bs *Bitswap) GetBlock(parent context.Context, k cid.Cid) (blocks.Block, error) {
207
	return bsgetter.SyncGetBlock(parent, k, bs.GetBlocks)
208 209
}

210 211
func (bs *Bitswap) WantlistForPeer(p peer.ID) []cid.Cid {
	var out []cid.Cid
212
	for _, e := range bs.engine.WantlistForPeer(p) {
213
		out = append(out, e.Cid)
214 215 216 217
	}
	return out
}

218 219 220 221
func (bs *Bitswap) LedgerForPeer(p peer.ID) *decision.Receipt {
	return bs.engine.LedgerForPeer(p)
}

222 223 224 225 226 227 228
// 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)
229
func (bs *Bitswap) GetBlocks(ctx context.Context, keys []cid.Cid) (<-chan blocks.Block, error) {
230
	if len(keys) == 0 {
231
		out := make(chan blocks.Block)
232 233 234 235
		close(out)
		return out, nil
	}

236 237 238 239 240
	select {
	case <-bs.process.Closing():
		return nil, errors.New("bitswap is closed")
	default:
	}
241
	promise := bs.notifications.Subscribe(ctx, keys...)
242

243
	for _, k := range keys {
244
		log.Event(ctx, "Bitswap.GetBlockRequest.Start", k)
245 246
	}

247
	mses := bs.sm.GetNextSessionID()
Jeromy's avatar
Jeromy committed
248 249

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

251
	remaining := cid.NewSet()
252
	for _, k := range keys {
253
		remaining.Add(k)
254 255 256 257 258 259 260 261
	}

	out := make(chan blocks.Block)
	go func() {
		ctx, cancel := context.WithCancel(ctx)
		defer cancel()
		defer close(out)
		defer func() {
262
			// can't just defer this call on its own, arguments are resolved *when* the defer is created
Jeromy's avatar
Jeromy committed
263
			bs.CancelWants(remaining.Keys(), mses)
264
		}()
Steven Allen's avatar
Steven Allen committed
265 266 267 268 269 270 271 272 273 274 275
		findProvsDelay := time.NewTimer(findProviderDelay)
		defer findProvsDelay.Stop()

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

		var findProvsReqCh chan<- *blockRequest

276 277
		for {
			select {
Steven Allen's avatar
Steven Allen committed
278 279 280 281 282 283 284 285
			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
286 287 288 289 290
			case blk, ok := <-promise:
				if !ok {
					return
				}

Steven Allen's avatar
Steven Allen committed
291 292 293 294 295
				// No need to find providers now.
				findProvsDelay.Stop()
				findProvsDelayCh = nil
				findProvsReqCh = nil

296
				bs.CancelWants([]cid.Cid{blk.Cid()}, mses)
297
				remaining.Remove(blk.Cid())
298 299 300 301 302 303 304 305 306 307 308
				select {
				case out <- blk:
				case <-ctx.Done():
					return
				}
			case <-ctx.Done():
				return
			}
		}
	}()

Steven Allen's avatar
Steven Allen committed
309
	return out, nil
Jeromy's avatar
Jeromy committed
310 311
}

312
// CancelWants removes a given key from the wantlist.
313
func (bs *Bitswap) CancelWants(cids []cid.Cid, ses uint64) {
314 315 316
	if len(cids) == 0 {
		return
	}
Jeromy's avatar
Jeromy committed
317
	bs.wm.CancelWants(context.Background(), cids, nil, ses)
318 319
}

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

337
	err := bs.blockstore.Put(blk)
338 339
	if err != nil {
		log.Errorf("Error writing block to datastore: %s", err)
340 341
		return err
	}
342

343 344 345 346 347
	// 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
348 349
	bs.notifications.Publish(blk)

350
	bs.sm.ReceiveBlockFrom(from, blk)
351

352 353
	bs.engine.AddBlock(blk)

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

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

Jeromy's avatar
Jeromy committed
366 367
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
368
	bs.engine.MessageReceived(p, incoming)
Jeromy's avatar
Jeromy committed
369 370
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
371

372 373 374
	iblocks := incoming.Blocks()

	if len(iblocks) == 0 {
375 376 377
		return
	}

Jeromy's avatar
Jeromy committed
378 379
	wg := sync.WaitGroup{}
	for _, block := range iblocks {
380

Jeromy's avatar
Jeromy committed
381
		wg.Add(1)
382
		go func(b blocks.Block) { // TODO: this probably doesnt need to be a goroutine...
Jeromy's avatar
Jeromy committed
383
			defer wg.Done()
384

385
			bs.updateReceiveCounters(b)
386

387
			log.Debugf("got block %s from %s", b, p)
388

389
			// skip received blocks that are not in the wantlist
390
			if !bs.wm.IsWanted(b.Cid()) {
391 392 393
				return
			}

394 395
			if err := bs.receiveBlockFrom(b, p); err != nil {
				log.Warningf("ReceiveMessage recvBlockFrom error: %s", err)
Jeromy's avatar
Jeromy committed
396
			}
397
			log.Event(ctx, "Bitswap.GetBlockRequest.End", b.Cid())
Jeromy's avatar
Jeromy committed
398
		}(block)
399
	}
Jeromy's avatar
Jeromy committed
400
	wg.Wait()
401 402
}

403 404
var ErrAlreadyHaveBlock = errors.New("already have block")

405
func (bs *Bitswap) updateReceiveCounters(b blocks.Block) {
406
	blkLen := len(b.RawData())
407
	has, err := bs.blockstore.Has(b.Cid())
408 409
	if err != nil {
		log.Infof("blockstore.Has error: %s", err)
410
		return
411
	}
412 413 414

	bs.allMetric.Observe(float64(blkLen))
	if has {
415
		bs.dupMetric.Observe(float64(blkLen))
416 417
	}

418 419
	bs.counterLk.Lock()
	defer bs.counterLk.Unlock()
420
	c := bs.counters
421

422 423
	c.blocksRecvd++
	c.dataRecvd += uint64(len(b.RawData()))
424
	if has {
425 426
		c.dupBlocksRecvd++
		c.dupDataRecvd += uint64(blkLen)
427 428 429
	}
}

430
// Connected/Disconnected warns bitswap about peer connections.
431
func (bs *Bitswap) PeerConnected(p peer.ID) {
432 433
	initialWants := bs.wm.CurrentBroadcastWants()
	bs.pm.Connected(p, initialWants)
434
	bs.engine.PeerConnected(p)
435 436
}

437
// Connected/Disconnected warns bitswap about peer connections.
438
func (bs *Bitswap) PeerDisconnected(p peer.ID) {
439
	bs.pm.Disconnected(p)
440
	bs.engine.PeerDisconnected(p)
441 442
}

443
func (bs *Bitswap) ReceiveError(err error) {
444
	log.Infof("Bitswap ReceiveError: %s", err)
445 446
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
447 448
}

449
func (bs *Bitswap) Close() error {
450
	return bs.process.Close()
451
}
452

453
func (bs *Bitswap) GetWantlist() []cid.Cid {
454
	entries := bs.wm.CurrentWants()
455
	out := make([]cid.Cid, 0, len(entries))
456
	for _, e := range entries {
457
		out = append(out, e.Cid)
458 459 460
	}
	return out
}
461 462 463 464

func (bs *Bitswap) IsOnline() bool {
	return true
}
465 466 467 468

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