bitswap.go 10.2 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

Jeromy's avatar
Jeromy committed
42
	HasBlockBufferSize = 256
43
	provideWorkers     = 4
Brian Tiger Chow's avatar
Brian Tiger Chow committed
44
)
Jeromy's avatar
Jeromy committed
45

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

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

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

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

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

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

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

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

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

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

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

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

	notifications notifications.PubSub

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

121
	engine *decision.Engine
122

123
	process process.Process
124 125

	newBlocks chan *blocks.Block
126

127
	provideKeys chan key.Key
128

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

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

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

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

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

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

	defer func() {
		cancelFunc()
	}()
159

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

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

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

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

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

208 209
	bs.wm.WantBlocks(keys)

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

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

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

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

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

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

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

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

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

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

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

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

293 294 295
	iblocks := incoming.Blocks()

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

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

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

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

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

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

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

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

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

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

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

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