bitswap.go 9.13 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 15 16 17 18 19 20 21 22 23 24
	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"
	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"
	u "github.com/ipfs/go-ipfs/util"
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,
85
		batchRequests: make(chan *blockRequest, sizeBatchRequestChan),
86
		process:       px,
Jeromy's avatar
Jeromy committed
87
		newBlocks:     make(chan *blocks.Block, HasBlockBufferSize),
88
		provideKeys:   make(chan u.Key),
89
		wm:            NewWantManager(network),
90
	}
91
	go bs.wm.Run(ctx)
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

118 119 120
	// Requests for a set of related blocks
	// the assumption is made that the same peer is likely to
	// have more than a single block in the set
121
	batchRequests 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 u.Key
130

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

136 137 138 139 140
type blockRequest struct {
	keys []u.Key
	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 u.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"))
Jeromy's avatar
Jeromy committed
155
	defer log.EventBegin(ctx, "GetBlockRequest", &k).Done()
156 157 158 159

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

161
	promise, err := bs.GetBlocks(ctx, []u.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 184 185 186 187 188 189
func (bs *Bitswap) WantlistForPeer(p peer.ID) []u.Key {
	var out []u.Key
	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 []u.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

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

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

226 227 228
	if err := bs.blockstore.Put(blk); err != nil {
		return err
	}
229

230
	bs.notifications.Publish(blk)
231 232
	select {
	case bs.newBlocks <- blk:
233
		// send block off to be reprovided
234 235 236 237
	case <-ctx.Done():
		return ctx.Err()
	}
	return nil
238 239
}

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

242 243 244
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

245
	// Get providers for all entries in wantlist (could take a while)
Jeromy's avatar
Jeromy committed
246
	wg := sync.WaitGroup{}
Jeromy's avatar
Jeromy committed
247
	for _, e := range entries {
248
		wg.Add(1)
Jeromy's avatar
Jeromy committed
249
		go func(k u.Key) {
Jeromy's avatar
Jeromy committed
250
			defer wg.Done()
251

252 253
			child, cancel := context.WithTimeout(ctx, providerRequestTimeout)
			defer cancel()
254
			providers := bs.network.FindProvidersAsync(child, k, maxProvidersPerRequest)
255
			for prov := range providers {
256 257 258
				go func(p peer.ID) {
					bs.network.ConnectTo(ctx, p)
				}(prov)
Jeromy's avatar
Jeromy committed
259
			}
260
		}(e.Key)
Jeromy's avatar
Jeromy committed
261
	}
262

263
	wg.Wait() // make sure all our children do finish.
Jeromy's avatar
Jeromy committed
264 265
}

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

273 274 275 276 277
	if len(incoming.Blocks()) == 0 {
		return
	}

	// quickly send out cancels, reduces chances of duplicate block receives
Jeromy Johnson's avatar
Jeromy Johnson committed
278
	var keys []u.Key
279 280 281 282 283
	for _, block := range incoming.Blocks() {
		keys = append(keys, block.Key())
	}
	bs.wm.CancelWants(keys)

Brian Tiger Chow's avatar
Brian Tiger Chow committed
284
	for _, block := range incoming.Blocks() {
Jeromy's avatar
Jeromy committed
285
		bs.counterLk.Lock()
286 287 288 289
		bs.blocksRecvd++
		if has, err := bs.blockstore.Has(block.Key()); err == nil && has {
			bs.dupBlocksRecvd++
		}
Jeromy's avatar
Jeromy committed
290
		bs.counterLk.Unlock()
Jeromy Johnson's avatar
Jeromy Johnson committed
291
		log.Debugf("got block %s from %s", block, p)
292

293
		hasBlockCtx, cancel := context.WithTimeout(ctx, hasBlockTimeout)
294
		if err := bs.HasBlock(hasBlockCtx, block); err != nil {
295
			log.Warningf("ReceiveMessage HasBlock error: %s", err)
Jeromy's avatar
Jeromy committed
296
		}
297
		cancel()
298
	}
299 300
}

301
// Connected/Disconnected warns bitswap about peer connections
302
func (bs *Bitswap) PeerConnected(p peer.ID) {
303
	// TODO: add to clientWorker??
304
	bs.wm.Connected(p)
305 306 307
}

// Connected/Disconnected warns bitswap about peer connections
308
func (bs *Bitswap) PeerDisconnected(p peer.ID) {
309
	bs.wm.Disconnected(p)
310
	bs.engine.PeerDisconnected(p)
311 312
}

313
func (bs *Bitswap) ReceiveError(err error) {
314
	log.Debugf("Bitswap ReceiveError: %s", err)
315 316
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
317 318
}

319
func (bs *Bitswap) Close() error {
320
	return bs.process.Close()
321
}
322

323
func (bs *Bitswap) GetWantlist() []u.Key {
324
	var out []u.Key
325
	for _, e := range bs.wm.wl.Entries() {
326 327 328 329
		out = append(out, e.Key)
	}
	return out
}