bitswap.go 10.3 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 13 14
	process "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess"
	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"
15
	key "github.com/ipfs/go-ipfs/blocks/key"
16 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"
	eventlog "github.com/ipfs/go-ipfs/thirdparty/eventlog"
25 26
)

27
var log = eventlog.Logger("bitswap")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
28

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

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

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

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

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

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

71
	go func() {
72
		<-px.Closing() // process closes first
Jeromy's avatar
Jeromy committed
73
		cancelFunc()
74 75 76 77
	}()
	go func() {
		<-ctx.Done() // parent cancelled first
		px.Close()
78 79
	}()

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

95 96
	// Start up bitswaps async worker routines
	bs.startWorkers(px, ctx)
97 98 99
	return bs
}

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

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

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

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

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

	notifications notifications.PubSub

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

122
	engine *decision.Engine
123

124
	process process.Process
125 126

	newBlocks chan *blocks.Block
127

128
	provideKeys chan key.Key
129

Jeromy's avatar
Jeromy committed
130
	counterLk      sync.Mutex
131 132
	blocksRecvd    int
	dupBlocksRecvd int
133 134
}

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

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

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

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

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

	defer func() {
		cancelFunc()
	}()
160

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

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

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

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

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

209 210
	bs.wm.WantBlocks(keys)

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

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

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

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

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

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

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

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

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

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

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

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

294 295 296
	iblocks := incoming.Blocks()

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

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

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

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

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

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

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
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
}

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

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

367
func (bs *Bitswap) ReceiveError(err error) {
368
	log.Infof("Bitswap ReceiveError: %s", err)
369 370
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
371 372
}

373
func (bs *Bitswap) Close() error {
374
	return bs.process.Close()
375
}
376

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