bitswap.go 9.15 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,
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 u.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 u.Key
128

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

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

	defer func() {
		cancelFunc()
	}()
158

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

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

180 181 182 183 184 185 186 187
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
}

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

203 204
	bs.wm.WantBlocks(keys)

205 206 207 208
	req := &blockRequest{
		keys: keys,
		ctx:  ctx,
	}
209
	select {
Jeromy's avatar
Jeromy committed
210
	case bs.findKeys <- 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 291
		brecvd := bs.blocksRecvd
		bdup := bs.dupBlocksRecvd
Jeromy's avatar
Jeromy committed
292
		bs.counterLk.Unlock()
Jeromy's avatar
Jeromy committed
293
		log.Infof("got block %s from %s (%d,%d)", block, p, brecvd, bdup)
294

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

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

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

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

321
func (bs *Bitswap) Close() error {
322
	return bs.process.Close()
323
}
324

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