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

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

11 12
	blocks "github.com/ipfs/go-ipfs/blocks"
	blockstore "github.com/ipfs/go-ipfs/blocks/blockstore"
13
	key "github.com/ipfs/go-ipfs/blocks/key"
14 15 16 17 18 19
	exchange "github.com/ipfs/go-ipfs/exchange"
	decision "github.com/ipfs/go-ipfs/exchange/bitswap/decision"
	bsmsg "github.com/ipfs/go-ipfs/exchange/bitswap/message"
	bsnet "github.com/ipfs/go-ipfs/exchange/bitswap/network"
	notifications "github.com/ipfs/go-ipfs/exchange/bitswap/notifications"
	wantlist "github.com/ipfs/go-ipfs/exchange/bitswap/wantlist"
Jeromy's avatar
Jeromy committed
20
	flags "github.com/ipfs/go-ipfs/flags"
21
	"github.com/ipfs/go-ipfs/thirdparty/delay"
22 23
	process "gx/ipfs/QmQopLATEYMNg7dVqZRNDfeE2S1yKy8zrRh5xnYiuqeZBn/goprocess"
	procctx "gx/ipfs/QmQopLATEYMNg7dVqZRNDfeE2S1yKy8zrRh5xnYiuqeZBn/goprocess/context"
24
	peer "gx/ipfs/QmSN2ELGRp4T9kjqiSsSNJRUeR9JKXzQEgwe1HH3tdSGbC/go-libp2p/p2p/peer"
Jeromy's avatar
Jeromy committed
25
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
Jeromy's avatar
Jeromy committed
26
	logging "gx/ipfs/Qmazh5oNUVsDZTs2g59rq8aYQqwpss8tcUWQzor5sCCEuH/go-log"
27 28
)

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

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

Jeromy's avatar
Jeromy committed
45
var (
46 47 48
	HasBlockBufferSize    = 256
	provideKeysBufferSize = 2048
	provideWorkerMax      = 512
Brian Tiger Chow's avatar
Brian Tiger Chow committed
49
)
Jeromy's avatar
Jeromy committed
50

Jeromy's avatar
Jeromy committed
51 52 53 54 55 56 57 58
func init() {
	if flags.LowMemMode {
		HasBlockBufferSize = 64
		provideKeysBufferSize = 512
		provideWorkerMax = 16
	}
}

59
var rebroadcastDelay = delay.Fixed(time.Second * 10)
60

Brian Tiger Chow's avatar
Brian Tiger Chow committed
61 62 63 64
// 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.
65
func New(parent context.Context, p peer.ID, network bsnet.BitSwapNetwork,
66
	bstore blockstore.Blockstore, nice bool) exchange.Interface {
67

68 69 70 71 72 73 74
	// 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
	// coupled to the concerns of the IPFS daemon in this way.
	//
	// 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
75 76
	ctx, cancelFunc := context.WithCancel(parent)

77
	notif := notifications.New()
78 79 80 81 82
	px := process.WithTeardown(func() error {
		notif.Shutdown()
		return nil
	})

83
	bs := &Bitswap{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84
		self:          p,
85
		blockstore:    bstore,
86
		notifications: notif,
87
		engine:        decision.NewEngine(ctx, bstore), // TODO close the engine with Close() method
88
		network:       network,
Jeromy's avatar
Jeromy committed
89
		findKeys:      make(chan *blockRequest, sizeBatchRequestChan),
90
		process:       px,
Jeromy's avatar
Jeromy committed
91
		newBlocks:     make(chan *blocks.Block, HasBlockBufferSize),
92
		provideKeys:   make(chan key.Key, provideKeysBufferSize),
93
		wm:            NewWantManager(ctx, network),
94
	}
95
	go bs.wm.Run()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
96
	network.SetDelegate(bs)
97

98 99
	// Start up bitswaps async worker routines
	bs.startWorkers(px, ctx)
100 101 102 103 104 105 106 107 108

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

109 110 111
	return bs
}

112 113
// Bitswap instances implement the bitswap protocol.
type Bitswap struct {
114

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
115 116 117
	// the ID of the peer to act on behalf of
	self peer.ID

118 119
	// network delivers messages on behalf of the session
	network bsnet.BitSwapNetwork
120

121 122
	// the peermanager manages sending messages to peers in a way that
	// wont block bitswap operation
123
	wm *WantManager
124

125 126 127 128 129 130
	// blockstore is the local database
	// NB: ensure threadsafety
	blockstore blockstore.Blockstore

	notifications notifications.PubSub

Jeromy's avatar
Jeromy committed
131 132
	// send keys to a worker to find and connect to providers for them
	findKeys chan *blockRequest
Jeromy's avatar
Jeromy committed
133

134
	engine *decision.Engine
135

136
	process process.Process
137 138

	newBlocks chan *blocks.Block
139

140
	provideKeys chan key.Key
141

Jeromy's avatar
Jeromy committed
142
	counterLk      sync.Mutex
143 144
	blocksRecvd    int
	dupBlocksRecvd int
145
	dupDataRecvd   uint64
146 147
}

148
type blockRequest struct {
149
	keys []key.Key
150 151 152
	ctx  context.Context
}

153
// GetBlock attempts to retrieve a particular block from peers within the
154
// deadline enforced by the context.
155
func (bs *Bitswap) GetBlock(parent context.Context, k key.Key) (*blocks.Block, error) {
156

157 158 159 160
	// Any async work initiated by this function must end when this function
	// returns. To ensure this, derive a new context. Note that it is okay to
	// listen on parent in this scope, but NOT okay to pass |parent| to
	// functions called by this one. Otherwise those functions won't return
161 162
	// when this context's cancel func is executed. This is difficult to
	// enforce. May this comment keep you safe.
163

164
	ctx, cancelFunc := context.WithCancel(parent)
165

Jeromy's avatar
Jeromy committed
166
	ctx = logging.ContextWithLoggable(ctx, logging.Uuid("GetBlockRequest"))
167 168
	log.Event(ctx, "Bitswap.GetBlockRequest.Start", &k)
	defer log.Event(ctx, "Bitswap.GetBlockRequest.End", &k)
169 170 171 172

	defer func() {
		cancelFunc()
	}()
173

174
	promise, err := bs.GetBlocks(ctx, []key.Key{k})
175 176
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
177
	}
178 179

	select {
180 181 182 183 184 185 186 187 188
	case block, ok := <-promise:
		if !ok {
			select {
			case <-ctx.Done():
				return nil, ctx.Err()
			default:
				return nil, errors.New("promise channel was closed")
			}
		}
Jeromy's avatar
Jeromy committed
189
		return block, nil
190 191
	case <-parent.Done():
		return nil, parent.Err()
192 193 194
	}
}

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

203 204 205 206 207 208 209
// 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)
210
func (bs *Bitswap) GetBlocks(ctx context.Context, keys []key.Key) (<-chan *blocks.Block, error) {
211 212 213 214 215
	select {
	case <-bs.process.Closing():
		return nil, errors.New("bitswap is closed")
	default:
	}
216
	promise := bs.notifications.Subscribe(ctx, keys...)
217

218 219 220 221
	for _, k := range keys {
		log.Event(ctx, "Bitswap.GetBlockRequest.Start", &k)
	}

222 223
	bs.wm.WantBlocks(keys)

224 225 226 227
	req := &blockRequest{
		keys: keys,
		ctx:  ctx,
	}
228
	select {
Jeromy's avatar
Jeromy committed
229
	case bs.findKeys <- req:
230
		return promise, nil
231 232 233
	case <-ctx.Done():
		return nil, ctx.Err()
	}
Jeromy's avatar
Jeromy committed
234 235
}

236 237 238 239 240
// CancelWant removes a given key from the wantlist
func (bs *Bitswap) CancelWants(ks []key.Key) {
	bs.wm.CancelWants(ks)
}

241 242
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
243
func (bs *Bitswap) HasBlock(blk *blocks.Block) error {
244 245 246 247 248
	select {
	case <-bs.process.Closing():
		return errors.New("bitswap is closed")
	default:
	}
249

250 251 252
	err := bs.tryPutBlock(blk, 4) // attempt to store block up to four times
	if err != nil {
		log.Errorf("Error writing block to datastore: %s", err)
253 254
		return err
	}
255

Jeromy's avatar
Jeromy committed
256 257
	bs.notifications.Publish(blk)

258 259
	select {
	case bs.newBlocks <- blk:
260
		// send block off to be reprovided
261 262
	case <-bs.process.Closing():
		return bs.process.Close()
263 264
	}
	return nil
265 266
}

267 268 269 270 271 272 273 274 275 276 277 278
func (bs *Bitswap) tryPutBlock(blk *blocks.Block, attempts int) error {
	var err error
	for i := 0; i < attempts; i++ {
		if err = bs.blockstore.Put(blk); err == nil {
			break
		}

		time.Sleep(time.Millisecond * time.Duration(400*(i+1)))
	}
	return err
}

279
func (bs *Bitswap) connectToProviders(ctx context.Context, entries []wantlist.Entry) {
Jeromy's avatar
Jeromy committed
280

281 282 283
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

284
	// Get providers for all entries in wantlist (could take a while)
Jeromy's avatar
Jeromy committed
285
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
286
	for _, e := range entries {
287
		wg.Add(1)
288
		go func(k key.Key) {
Jeromy's avatar
Jeromy committed
289
			defer wg.Done()
290

291 292
			child, cancel := context.WithTimeout(ctx, providerRequestTimeout)
			defer cancel()
293
			providers := bs.network.FindProvidersAsync(child, k, maxProvidersPerRequest)
294
			for prov := range providers {
295 296 297
				go func(p peer.ID) {
					bs.network.ConnectTo(ctx, p)
				}(prov)
Jeromy's avatar
Jeromy committed
298
			}
299
		}(e.Key)
Jeromy's avatar
Jeromy committed
300
	}
301

302
	wg.Wait() // make sure all our children do finish.
Jeromy's avatar
Jeromy committed
303 304
}

305
func (bs *Bitswap) ReceiveMessage(ctx context.Context, p peer.ID, incoming bsmsg.BitSwapMessage) {
Jeromy's avatar
Jeromy committed
306 307
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
308
	bs.engine.MessageReceived(p, incoming)
Jeromy's avatar
Jeromy committed
309 310
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
311

312 313 314
	iblocks := incoming.Blocks()

	if len(iblocks) == 0 {
315 316 317 318
		return
	}

	// quickly send out cancels, reduces chances of duplicate block receives
319
	var keys []key.Key
320 321
	for _, block := range iblocks {
		if _, found := bs.wm.wl.Contains(block.Key()); !found {
322
			log.Infof("received un-asked-for %s from %s", block, p)
323 324
			continue
		}
Jeromy's avatar
Jeromy committed
325 326 327
		keys = append(keys, block.Key())
	}
	bs.wm.CancelWants(keys)
328

Jeromy's avatar
Jeromy committed
329 330 331 332 333
	wg := sync.WaitGroup{}
	for _, block := range iblocks {
		wg.Add(1)
		go func(b *blocks.Block) {
			defer wg.Done()
334

335
			if err := bs.updateReceiveCounters(b); err != nil {
336
				return // ignore error, is either logged previously, or ErrAlreadyHaveBlock
Jeromy's avatar
Jeromy committed
337
			}
338

339 340 341
			k := b.Key()
			log.Event(ctx, "Bitswap.GetBlockRequest.End", &k)

342
			log.Debugf("got block %s from %s", b, p)
343
			if err := bs.HasBlock(b); err != nil {
Jeromy's avatar
Jeromy committed
344 345 346
				log.Warningf("ReceiveMessage HasBlock error: %s", err)
			}
		}(block)
347
	}
Jeromy's avatar
Jeromy committed
348
	wg.Wait()
349 350
}

351 352
var ErrAlreadyHaveBlock = errors.New("already have block")

353
func (bs *Bitswap) updateReceiveCounters(b *blocks.Block) error {
354 355 356
	bs.counterLk.Lock()
	defer bs.counterLk.Unlock()
	bs.blocksRecvd++
357
	has, err := bs.blockstore.Has(b.Key())
358 359 360 361 362 363
	if err != nil {
		log.Infof("blockstore.Has error: %s", err)
		return err
	}
	if err == nil && has {
		bs.dupBlocksRecvd++
364
		bs.dupDataRecvd += uint64(len(b.Data))
365 366 367 368 369 370 371 372
	}

	if has {
		return ErrAlreadyHaveBlock
	}
	return nil
}

373
// Connected/Disconnected warns bitswap about peer connections
374
func (bs *Bitswap) PeerConnected(p peer.ID) {
375
	bs.wm.Connected(p)
376 377 378
}

// Connected/Disconnected warns bitswap about peer connections
379
func (bs *Bitswap) PeerDisconnected(p peer.ID) {
380
	bs.wm.Disconnected(p)
381
	bs.engine.PeerDisconnected(p)
382 383
}

384
func (bs *Bitswap) ReceiveError(err error) {
385
	log.Infof("Bitswap ReceiveError: %s", err)
386 387
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
388 389
}

390
func (bs *Bitswap) Close() error {
391
	return bs.process.Close()
392
}
393

394 395
func (bs *Bitswap) GetWantlist() []key.Key {
	var out []key.Key
396
	for _, e := range bs.wm.wl.Entries() {
397 398 399 400
		out = append(out, e.Key)
	}
	return out
}