bitswap.go 10.5 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 25
	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"
	eventlog "github.com/ipfs/go-ipfs/thirdparty/eventlog"
26 27
)

28
var log = eventlog.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 135
}

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

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

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

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

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

	defer func() {
		cancelFunc()
	}()
161

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

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

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

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

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

210 211
	bs.wm.WantBlocks(keys)

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

224 225
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
226
func (bs *Bitswap) HasBlock(ctx context.Context, blk *blocks.Block) error {
227 228 229 230 231
	select {
	case <-bs.process.Closing():
		return errors.New("bitswap is closed")
	default:
	}
232

233 234 235
	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)
236 237
		return err
	}
238

Jeromy's avatar
Jeromy committed
239 240
	bs.notifications.Publish(blk)

241 242
	select {
	case bs.newBlocks <- blk:
243
		// send block off to be reprovided
244 245 246 247
	case <-ctx.Done():
		return ctx.Err()
	}
	return nil
248 249
}

250 251 252 253 254 255 256 257 258 259 260 261
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
}

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

264 265 266
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

267
	// Get providers for all entries in wantlist (could take a while)
Jeromy's avatar
Jeromy committed
268
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
269
	for _, e := range entries {
270
		wg.Add(1)
271
		go func(k key.Key) {
Jeromy's avatar
Jeromy committed
272
			defer wg.Done()
273

274 275
			child, cancel := context.WithTimeout(ctx, providerRequestTimeout)
			defer cancel()
276
			providers := bs.network.FindProvidersAsync(child, k, maxProvidersPerRequest)
277
			for prov := range providers {
278 279 280
				go func(p peer.ID) {
					bs.network.ConnectTo(ctx, p)
				}(prov)
Jeromy's avatar
Jeromy committed
281
			}
282
		}(e.Key)
Jeromy's avatar
Jeromy committed
283
	}
284

285
	wg.Wait() // make sure all our children do finish.
Jeromy's avatar
Jeromy committed
286 287
}

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

295 296 297
	iblocks := incoming.Blocks()

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

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

Jeromy's avatar
Jeromy committed
312 313 314 315 316
	wg := sync.WaitGroup{}
	for _, block := range iblocks {
		wg.Add(1)
		go func(b *blocks.Block) {
			defer wg.Done()
317 318 319

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

322 323 324
			k := b.Key()
			log.Event(ctx, "Bitswap.GetBlockRequest.End", &k)

325
			log.Debugf("got block %s from %s", b, p)
Jeromy's avatar
Jeromy committed
326
			hasBlockCtx, cancel := context.WithTimeout(ctx, hasBlockTimeout)
327
			defer cancel()
Jeromy's avatar
Jeromy committed
328 329 330 331
			if err := bs.HasBlock(hasBlockCtx, b); err != nil {
				log.Warningf("ReceiveMessage HasBlock error: %s", err)
			}
		}(block)
332
	}
Jeromy's avatar
Jeromy committed
333
	wg.Wait()
334 335
}

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
var ErrAlreadyHaveBlock = errors.New("already have block")

func (bs *Bitswap) updateReceiveCounters(k key.Key) error {
	bs.counterLk.Lock()
	defer bs.counterLk.Unlock()
	bs.blocksRecvd++
	has, err := bs.blockstore.Has(k)
	if err != nil {
		log.Infof("blockstore.Has error: %s", err)
		return err
	}
	if err == nil && has {
		bs.dupBlocksRecvd++
	}

	if has {
		return ErrAlreadyHaveBlock
	}
	return nil
}

357
// Connected/Disconnected warns bitswap about peer connections
358
func (bs *Bitswap) PeerConnected(p peer.ID) {
359
	bs.wm.Connected(p)
360 361 362
}

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

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
func (bs *Bitswap) Close() error {
375
	return bs.process.Close()
376
}
377

378 379
func (bs *Bitswap) GetWantlist() []key.Key {
	var out []key.Key
380
	for _, e := range bs.wm.wl.Entries() {
381 382 383 384
		out = append(out, e.Key)
	}
	return out
}