bitswap.go 12.5 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 10
	"time"

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

Jeromy's avatar
Jeromy committed
13
	decision "github.com/ipfs/go-bitswap/decision"
14
	bsgetter "github.com/ipfs/go-bitswap/getter"
Jeromy's avatar
Jeromy committed
15
	bsmsg "github.com/ipfs/go-bitswap/message"
16
	bsmq "github.com/ipfs/go-bitswap/messagequeue"
Jeromy's avatar
Jeromy committed
17
	bsnet "github.com/ipfs/go-bitswap/network"
18
	bspm "github.com/ipfs/go-bitswap/peermanager"
19
	bspqm "github.com/ipfs/go-bitswap/providerquerymanager"
20
	bssession "github.com/ipfs/go-bitswap/session"
21
	bssm "github.com/ipfs/go-bitswap/sessionmanager"
22
	bsspm "github.com/ipfs/go-bitswap/sessionpeermanager"
23
	bswm "github.com/ipfs/go-bitswap/wantmanager"
Jeromy's avatar
Jeromy committed
24 25 26 27 28 29 30 31
	blocks "github.com/ipfs/go-block-format"
	cid "github.com/ipfs/go-cid"
	blockstore "github.com/ipfs/go-ipfs-blockstore"
	exchange "github.com/ipfs/go-ipfs-exchange-interface"
	logging "github.com/ipfs/go-log"
	metrics "github.com/ipfs/go-metrics-interface"
	process "github.com/jbenet/goprocess"
	procctx "github.com/jbenet/goprocess/context"
Raúl Kripalani's avatar
Raúl Kripalani committed
32
	peer "github.com/libp2p/go-libp2p-core/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 (
40
	// these requests take at _least_ two minutes at the moment.
Steven Allen's avatar
Steven Allen committed
41
	provideTimeout = time.Minute * 3
Jeromy's avatar
Jeromy committed
42
)
43

Jeromy's avatar
Jeromy committed
44
var (
45 46 47 48
	// HasBlockBufferSize is the buffer size of the channel for new blocks
	// that need to be provided. They should get pulled over by the
	// provideCollector even before they are actually provided.
	// TODO: Does this need to be this large givent that?
49 50
	HasBlockBufferSize    = 256
	provideKeysBufferSize = 2048
Steven Allen's avatar
Steven Allen committed
51
	provideWorkerMax      = 6
52 53 54

	// 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
55
)
Jeromy's avatar
Jeromy committed
56

57 58 59 60 61 62 63 64 65 66 67
// Option defines the functional option type that can be used to configure
// bitswap instances
type Option func(*Bitswap)

// ProvideEnabled is an option for enabling/disabling provide announcements
func ProvideEnabled(enabled bool) Option {
	return func(bs *Bitswap) {
		bs.provideEnabled = enabled
	}
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
68 69
// New initializes a BitSwap instance that communicates over the provided
// BitSwapNetwork. This function registers the returned instance as the network
70
// delegate. Runs until context is cancelled or bitswap.Close is called.
Łukasz Magiera's avatar
Łukasz Magiera committed
71
func New(parent context.Context, network bsnet.BitSwapNetwork,
72
	bstore blockstore.Blockstore, options ...Option) exchange.Interface {
73

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

88 89 90
	sentHistogram := metrics.NewCtx(ctx, "sent_all_blocks_bytes", "Histogram of blocks sent by"+
		" this bitswap").Histogram(metricsBuckets)

91 92 93 94
	px := process.WithTeardown(func() error {
		return nil
	})

95 96
	peerQueueFactory := func(ctx context.Context, p peer.ID) bspm.PeerQueue {
		return bsmq.New(ctx, p, network)
97 98
	}

99
	wm := bswm.New(ctx, bspm.New(ctx, peerQueueFactory))
100 101
	pqm := bspqm.New(ctx, network)

102 103
	sessionFactory := func(ctx context.Context, id uint64, pm bssession.PeerManager, srs bssession.RequestSplitter) bssm.Session {
		return bssession.New(ctx, id, wm, pm, srs)
104 105
	}
	sessionPeerManagerFactory := func(ctx context.Context, id uint64) bssession.PeerManager {
106
		return bsspm.New(ctx, id, network.ConnectionManager(), pqm)
107
	}
108 109 110
	sessionRequestSplitterFactory := func(ctx context.Context) bssession.RequestSplitter {
		return bssrs.New(ctx)
	}
111

112
	bs := &Bitswap{
113
		blockstore:     bstore,
114
		engine:         decision.NewEngine(ctx, bstore, network.ConnectionManager()), // TODO close the engine with Close() method
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
		network:        network,
		process:        px,
		newBlocks:      make(chan cid.Cid, HasBlockBufferSize),
		provideKeys:    make(chan cid.Cid, provideKeysBufferSize),
		wm:             wm,
		pqm:            pqm,
		sm:             bssm.New(ctx, sessionFactory, sessionPeerManagerFactory, sessionRequestSplitterFactory),
		counters:       new(counters),
		dupMetric:      dupHist,
		allMetric:      allHist,
		sentHistogram:  sentHistogram,
		provideEnabled: true,
	}

	// apply functional options before starting and running bitswap
	for _, option := range options {
		option(bs)
132
	}
133 134

	bs.wm.Startup()
135
	bs.pqm.Startup()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
136
	network.SetDelegate(bs)
137

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

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

149 150 151
	return bs
}

152 153
// Bitswap instances implement the bitswap protocol.
type Bitswap struct {
154
	// the wantlist tracks global wants for bitswap
155
	wm *bswm.WantManager
156

157 158 159
	// the provider query manager manages requests to find providers
	pqm *bspqm.ProviderQueryManager

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

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

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

170 171 172
	// 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
173
	newBlocks chan cid.Cid
174
	// provideKeys directly feeds provide workers
175
	provideKeys chan cid.Cid
176

177 178 179
	process process.Process

	// Counters for various statistics
180 181
	counterLk sync.Mutex
	counters  *counters
182 183

	// Metrics interface metrics
184 185 186
	dupMetric     metrics.Histogram
	allMetric     metrics.Histogram
	sentHistogram metrics.Histogram
Jeromy's avatar
Jeromy committed
187

188 189
	// the sessionmanager manages tracking sessions
	sm *bssm.SessionManager
190 191 192

	// whether or not to make provide announcements
	provideEnabled bool
193 194
}

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

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

211 212
// WantlistForPeer returns the currently understood list of blocks requested by a
// given peer.
213 214
func (bs *Bitswap) WantlistForPeer(p peer.ID) []cid.Cid {
	var out []cid.Cid
215
	for _, e := range bs.engine.WantlistForPeer(p) {
216
		out = append(out, e.Cid)
217 218 219 220
	}
	return out
}

221 222
// LedgerForPeer returns aggregated data about blocks swapped and communication
// with a given peer.
223 224 225 226
func (bs *Bitswap) LedgerForPeer(p peer.ID) *decision.Receipt {
	return bs.engine.LedgerForPeer(p)
}

227 228 229 230 231 232 233
// 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)
234
func (bs *Bitswap) GetBlocks(ctx context.Context, keys []cid.Cid) (<-chan blocks.Block, error) {
235 236
	session := bs.sm.NewSession(ctx)
	return session.GetBlocks(ctx, keys)
Jeromy's avatar
Jeromy committed
237 238
}

Łukasz Magiera's avatar
Łukasz Magiera committed
239
// HasBlock announces the existence of a block to this bitswap service. The
240
// service will potentially notify its peers.
241
func (bs *Bitswap) HasBlock(blk blocks.Block) error {
242 243 244 245 246 247 248 249
	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 {
250 251 252 253 254
	select {
	case <-bs.process.Closing():
		return errors.New("bitswap is closed")
	default:
	}
255

256
	err := bs.blockstore.Put(blk)
257 258
	if err != nil {
		log.Errorf("Error writing block to datastore: %s", err)
259 260
		return err
	}
261

262 263 264 265 266
	// 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
267

268
	bs.sm.ReceiveBlockFrom(from, blk)
269

270 271
	bs.engine.AddBlock(blk)

272
	if bs.provideEnabled {
273 274 275 276 277 278
		select {
		case bs.newBlocks <- blk.Cid():
			// send block off to be reprovided
		case <-bs.process.Closing():
			return bs.process.Close()
		}
279 280
	}
	return nil
281 282
}

283 284
// ReceiveMessage is called by the network interface when a new message is
// received.
285
func (bs *Bitswap) ReceiveMessage(ctx context.Context, p peer.ID, incoming bsmsg.BitSwapMessage) {
Steven Allen's avatar
Steven Allen committed
286 287 288
	bs.counterLk.Lock()
	bs.counters.messagesRecvd++
	bs.counterLk.Unlock()
Jeromy's avatar
Jeromy committed
289

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

296 297 298
	iblocks := incoming.Blocks()

	if len(iblocks) == 0 {
299 300 301
		return
	}

Jeromy's avatar
Jeromy committed
302 303
	wg := sync.WaitGroup{}
	for _, block := range iblocks {
304

Jeromy's avatar
Jeromy committed
305
		wg.Add(1)
306
		go func(b blocks.Block) { // TODO: this probably doesnt need to be a goroutine...
Jeromy's avatar
Jeromy committed
307
			defer wg.Done()
308

309
			bs.updateReceiveCounters(b)
310
			bs.sm.UpdateReceiveCounters(b)
311
			log.Debugf("got block %s from %s", b, p)
312

313
			// skip received blocks that are not in the wantlist
314
			if !bs.wm.IsWanted(b.Cid()) {
315 316 317
				return
			}

318 319
			if err := bs.receiveBlockFrom(b, p); err != nil {
				log.Warningf("ReceiveMessage recvBlockFrom error: %s", err)
Jeromy's avatar
Jeromy committed
320
			}
321
			log.Event(ctx, "Bitswap.GetBlockRequest.End", b.Cid())
Jeromy's avatar
Jeromy committed
322
		}(block)
323
	}
Jeromy's avatar
Jeromy committed
324
	wg.Wait()
325 326
}

327
func (bs *Bitswap) updateReceiveCounters(b blocks.Block) {
328
	blkLen := len(b.RawData())
329
	has, err := bs.blockstore.Has(b.Cid())
330 331
	if err != nil {
		log.Infof("blockstore.Has error: %s", err)
332
		return
333
	}
334 335 336

	bs.allMetric.Observe(float64(blkLen))
	if has {
337
		bs.dupMetric.Observe(float64(blkLen))
338 339
	}

340 341
	bs.counterLk.Lock()
	defer bs.counterLk.Unlock()
342
	c := bs.counters
343

344 345
	c.blocksRecvd++
	c.dataRecvd += uint64(len(b.RawData()))
346
	if has {
347 348
		c.dupBlocksRecvd++
		c.dupDataRecvd += uint64(blkLen)
349 350 351
	}
}

352 353
// PeerConnected is called by the network interface
// when a peer initiates a new connection to bitswap.
354
func (bs *Bitswap) PeerConnected(p peer.ID) {
355
	bs.wm.Connected(p)
356
	bs.engine.PeerConnected(p)
357 358
}

359 360
// PeerDisconnected is called by the network interface when a peer
// closes a connection
361
func (bs *Bitswap) PeerDisconnected(p peer.ID) {
362
	bs.wm.Disconnected(p)
363
	bs.engine.PeerDisconnected(p)
364 365
}

366 367
// ReceiveError is called by the network interface when an error happens
// at the network layer. Currently just logs error.
368
func (bs *Bitswap) ReceiveError(err error) {
369
	log.Infof("Bitswap ReceiveError: %s", err)
370 371
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
372 373
}

374
// Close is called to shutdown Bitswap
375
func (bs *Bitswap) Close() error {
376
	return bs.process.Close()
377
}
378

379
// GetWantlist returns the current local wantlist.
380
func (bs *Bitswap) GetWantlist() []cid.Cid {
381
	entries := bs.wm.CurrentWants()
382
	out := make([]cid.Cid, 0, len(entries))
383
	for _, e := range entries {
384
		out = append(out, e.Cid)
385 386 387
	}
	return out
}
388

389
// IsOnline is needed to match go-ipfs-exchange-interface
390 391 392
func (bs *Bitswap) IsOnline() bool {
	return true
}
393

394 395 396 397 398 399
// NewSession generates a new Bitswap session. You should use this, rather
// that calling Bitswap.GetBlocks, any time you intend to do several related
// block requests in a row. The session returned will have it's own GetBlocks
// method, but the session will use the fact that the requests are related to
// be more efficient in its requests to peers. If you are using a session
// from go-blockservice, it will create a bitswap session automatically.
400 401 402
func (bs *Bitswap) NewSession(ctx context.Context) exchange.Fetcher {
	return bs.sm.NewSession(ctx)
}