bitswap.go 10.6 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
	process "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess"
12
	procctx "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess/context"
13 14 15
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	blocks "github.com/ipfs/go-ipfs/blocks"
	blockstore "github.com/ipfs/go-ipfs/blocks/blockstore"
16
	key "github.com/ipfs/go-ipfs/blocks/key"
17 18 19 20 21 22 23 24
	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"
	peer "github.com/ipfs/go-ipfs/p2p/peer"
	"github.com/ipfs/go-ipfs/thirdparty/delay"
25
	logging "github.com/ipfs/go-ipfs/vendor/QmXJkcEXB6C9h6Ytb6rrUTFU56Ro62zxgrbxTT3dgjQGA8/go-log"
26 27
)

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

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

43 44 45
	HasBlockBufferSize    = 256
	provideKeysBufferSize = 2048
	provideWorkerMax      = 512
Brian Tiger Chow's avatar
Brian Tiger Chow committed
46
)
Jeromy's avatar
Jeromy committed
47

48
var rebroadcastDelay = delay.Fixed(time.Second * 10)
49

Brian Tiger Chow's avatar
Brian Tiger Chow committed
50 51 52 53
// 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.
54
func New(parent context.Context, p peer.ID, network bsnet.BitSwapNetwork,
55
	bstore blockstore.Blockstore, nice bool) exchange.Interface {
56

57 58 59 60 61 62 63
	// 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
64 65
	ctx, cancelFunc := context.WithCancel(parent)

66
	notif := notifications.New()
67 68 69 70 71
	px := process.WithTeardown(func() error {
		notif.Shutdown()
		return nil
	})

72
	bs := &Bitswap{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
73
		self:          p,
74
		blockstore:    bstore,
75
		notifications: notif,
76
		engine:        decision.NewEngine(ctx, bstore), // TODO close the engine with Close() method
77
		network:       network,
Jeromy's avatar
Jeromy committed
78
		findKeys:      make(chan *blockRequest, sizeBatchRequestChan),
79
		process:       px,
Jeromy's avatar
Jeromy committed
80
		newBlocks:     make(chan *blocks.Block, HasBlockBufferSize),
81
		provideKeys:   make(chan key.Key, provideKeysBufferSize),
82
		wm:            NewWantManager(ctx, network),
83
	}
84
	go bs.wm.Run()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
85
	network.SetDelegate(bs)
86

87 88
	// Start up bitswaps async worker routines
	bs.startWorkers(px, ctx)
89 90 91 92 93 94 95 96 97

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

98 99 100
	return bs
}

101 102
// Bitswap instances implement the bitswap protocol.
type Bitswap struct {
103

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104 105 106
	// the ID of the peer to act on behalf of
	self peer.ID

107 108
	// network delivers messages on behalf of the session
	network bsnet.BitSwapNetwork
109

110 111
	// the peermanager manages sending messages to peers in a way that
	// wont block bitswap operation
112
	wm *WantManager
113

114 115 116 117 118 119
	// blockstore is the local database
	// NB: ensure threadsafety
	blockstore blockstore.Blockstore

	notifications notifications.PubSub

Jeromy's avatar
Jeromy committed
120 121
	// send keys to a worker to find and connect to providers for them
	findKeys chan *blockRequest
Jeromy's avatar
Jeromy committed
122

123
	engine *decision.Engine
124

125
	process process.Process
126 127

	newBlocks chan *blocks.Block
128

129
	provideKeys chan key.Key
130

Jeromy's avatar
Jeromy committed
131
	counterLk      sync.Mutex
132 133
	blocksRecvd    int
	dupBlocksRecvd int
134
	dupDataRecvd   uint64
135 136
}

137
type blockRequest struct {
138
	keys []key.Key
139 140 141
	ctx  context.Context
}

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

146 147 148 149
	// 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
150 151
	// when this context's cancel func is executed. This is difficult to
	// enforce. May this comment keep you safe.
152

153
	ctx, cancelFunc := context.WithCancel(parent)
154

Jeromy's avatar
Jeromy committed
155
	ctx = logging.ContextWithLoggable(ctx, logging.Uuid("GetBlockRequest"))
156 157
	log.Event(ctx, "Bitswap.GetBlockRequest.Start", &k)
	defer log.Event(ctx, "Bitswap.GetBlockRequest.End", &k)
158 159 160 161

	defer func() {
		cancelFunc()
	}()
162

163
	promise, err := bs.GetBlocks(ctx, []key.Key{k})
164 165
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
166
	}
167 168

	select {
169 170 171 172 173 174 175 176 177
	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
178
		return block, nil
179 180
	case <-parent.Done():
		return nil, parent.Err()
181 182 183
	}
}

184 185
func (bs *Bitswap) WantlistForPeer(p peer.ID) []key.Key {
	var out []key.Key
186 187 188 189 190 191
	for _, e := range bs.engine.WantlistForPeer(p) {
		out = append(out, e.Key)
	}
	return out
}

192 193 194 195 196 197 198
// 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)
199
func (bs *Bitswap) GetBlocks(ctx context.Context, keys []key.Key) (<-chan *blocks.Block, error) {
200 201 202 203 204
	select {
	case <-bs.process.Closing():
		return nil, errors.New("bitswap is closed")
	default:
	}
205
	promise := bs.notifications.Subscribe(ctx, keys...)
206

207 208 209 210
	for _, k := range keys {
		log.Event(ctx, "Bitswap.GetBlockRequest.Start", &k)
	}

211 212
	bs.wm.WantBlocks(keys)

213 214 215 216
	req := &blockRequest{
		keys: keys,
		ctx:  ctx,
	}
217
	select {
Jeromy's avatar
Jeromy committed
218
	case bs.findKeys <- req:
219
		return promise, nil
220 221 222
	case <-ctx.Done():
		return nil, ctx.Err()
	}
Jeromy's avatar
Jeromy committed
223 224
}

225 226 227 228 229
// CancelWant removes a given key from the wantlist
func (bs *Bitswap) CancelWants(ks []key.Key) {
	bs.wm.CancelWants(ks)
}

230 231
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
232
func (bs *Bitswap) HasBlock(blk *blocks.Block) error {
233 234 235 236 237
	select {
	case <-bs.process.Closing():
		return errors.New("bitswap is closed")
	default:
	}
238

239 240 241
	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)
242 243
		return err
	}
244

Jeromy's avatar
Jeromy committed
245 246
	bs.notifications.Publish(blk)

247 248
	select {
	case bs.newBlocks <- blk:
249
		// send block off to be reprovided
250 251
	case <-bs.process.Closing():
		return bs.process.Close()
252 253
	}
	return nil
254 255
}

256 257 258 259 260 261 262 263 264 265 266 267
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
}

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

270 271 272
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

273
	// Get providers for all entries in wantlist (could take a while)
Jeromy's avatar
Jeromy committed
274
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
275
	for _, e := range entries {
276
		wg.Add(1)
277
		go func(k key.Key) {
Jeromy's avatar
Jeromy committed
278
			defer wg.Done()
279

280 281
			child, cancel := context.WithTimeout(ctx, providerRequestTimeout)
			defer cancel()
282
			providers := bs.network.FindProvidersAsync(child, k, maxProvidersPerRequest)
283
			for prov := range providers {
284 285 286
				go func(p peer.ID) {
					bs.network.ConnectTo(ctx, p)
				}(prov)
Jeromy's avatar
Jeromy committed
287
			}
288
		}(e.Key)
Jeromy's avatar
Jeromy committed
289
	}
290

291
	wg.Wait() // make sure all our children do finish.
Jeromy's avatar
Jeromy committed
292 293
}

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

301 302 303
	iblocks := incoming.Blocks()

	if len(iblocks) == 0 {
304 305 306 307
		return
	}

	// quickly send out cancels, reduces chances of duplicate block receives
308
	var keys []key.Key
309 310
	for _, block := range iblocks {
		if _, found := bs.wm.wl.Contains(block.Key()); !found {
rht's avatar
rht committed
311
			log.Info("received un-asked-for block: %s", block)
312 313
			continue
		}
Jeromy's avatar
Jeromy committed
314 315 316
		keys = append(keys, block.Key())
	}
	bs.wm.CancelWants(keys)
317

Jeromy's avatar
Jeromy committed
318 319 320 321 322
	wg := sync.WaitGroup{}
	for _, block := range iblocks {
		wg.Add(1)
		go func(b *blocks.Block) {
			defer wg.Done()
323

324
			if err := bs.updateReceiveCounters(b); err != nil {
325
				return // ignore error, is either logged previously, or ErrAlreadyHaveBlock
Jeromy's avatar
Jeromy committed
326
			}
327

328 329 330
			k := b.Key()
			log.Event(ctx, "Bitswap.GetBlockRequest.End", &k)

331
			log.Debugf("got block %s from %s", b, p)
332
			if err := bs.HasBlock(b); err != nil {
Jeromy's avatar
Jeromy committed
333 334 335
				log.Warningf("ReceiveMessage HasBlock error: %s", err)
			}
		}(block)
336
	}
Jeromy's avatar
Jeromy committed
337
	wg.Wait()
338 339
}

340 341
var ErrAlreadyHaveBlock = errors.New("already have block")

342
func (bs *Bitswap) updateReceiveCounters(b *blocks.Block) error {
343 344 345
	bs.counterLk.Lock()
	defer bs.counterLk.Unlock()
	bs.blocksRecvd++
346
	has, err := bs.blockstore.Has(b.Key())
347 348 349 350 351 352
	if err != nil {
		log.Infof("blockstore.Has error: %s", err)
		return err
	}
	if err == nil && has {
		bs.dupBlocksRecvd++
353
		bs.dupDataRecvd += uint64(len(b.Data))
354 355 356 357 358 359 360 361
	}

	if has {
		return ErrAlreadyHaveBlock
	}
	return nil
}

362
// Connected/Disconnected warns bitswap about peer connections
363
func (bs *Bitswap) PeerConnected(p peer.ID) {
364
	bs.wm.Connected(p)
365 366 367
}

// Connected/Disconnected warns bitswap about peer connections
368
func (bs *Bitswap) PeerDisconnected(p peer.ID) {
369
	bs.wm.Disconnected(p)
370
	bs.engine.PeerDisconnected(p)
371 372
}

373
func (bs *Bitswap) ReceiveError(err error) {
374
	log.Infof("Bitswap ReceiveError: %s", err)
375 376
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
377 378
}

379
func (bs *Bitswap) Close() error {
380
	return bs.process.Close()
381
}
382

383 384
func (bs *Bitswap) GetWantlist() []key.Key {
	var out []key.Key
385
	for _, e := range bs.wm.wl.Entries() {
386 387 388 389
		out = append(out, e.Key)
	}
	return out
}