engine.go 10.9 KB
Newer Older
1
// Package decision implements the decision engine for the bitswap service.
2
package decision
3 4

import (
Jeromy's avatar
Jeromy committed
5
	"context"
6
	"sync"
Jeromy's avatar
Jeromy committed
7
	"time"
8

Jeromy's avatar
Jeromy committed
9 10
	bsmsg "github.com/ipfs/go-bitswap/message"
	wl "github.com/ipfs/go-bitswap/wantlist"
11 12 13
	cid "github.com/ipfs/go-cid"
	"github.com/ipfs/go-peertaskqueue"
	"github.com/ipfs/go-peertaskqueue/peertask"
14

Jeromy's avatar
Jeromy committed
15 16 17 18
	blocks "github.com/ipfs/go-block-format"
	bstore "github.com/ipfs/go-ipfs-blockstore"
	logging "github.com/ipfs/go-log"
	peer "github.com/libp2p/go-libp2p-peer"
19 20
)

21 22 23 24 25 26 27 28
// TODO consider taking responsibility for other types of requests. For
// example, there could be a |cancelQueue| for all of the cancellation
// messages that need to go out. There could also be a |wantlistQueue| for
// the local peer's wantlists. Alternatively, these could all be bundled
// into a single, intelligent global queue that efficiently
// batches/combines and takes all of these into consideration.
//
// Right now, messages go onto the network for four reasons:
29 30
// 1. an initial `sendwantlist` message to a provider of the first key in a
//    request
31 32 33 34 35 36 37 38 39 40 41 42
// 2. a periodic full sweep of `sendwantlist` messages to all providers
// 3. upon receipt of blocks, a `cancel` message to all peers
// 4. draining the priority queue of `blockrequests` from peers
//
// Presently, only `blockrequests` are handled by the decision engine.
// However, there is an opportunity to give it more responsibility! If the
// decision engine is given responsibility for all of the others, it can
// intelligently decide how to combine requests efficiently.
//
// Some examples of what would be possible:
//
// * when sending out the wantlists, include `cancel` requests
43 44
// * when handling `blockrequests`, include `sendwantlist` and `cancel` as
//   appropriate
45
// * when handling `cancel`, if we recently received a wanted block from a
46
//   peer, include a partial wantlist that contains a few other high priority
47 48 49 50 51 52
//   blocks
//
// In a sense, if we treat the decision engine as a black box, it could do
// whatever it sees fit to produce desired outcomes (get wanted keys
// quickly, maintain good relationships with peers, etc).

Jeromy's avatar
Jeromy committed
53
var log = logging.Logger("engine")
54

Brian Tiger Chow's avatar
Brian Tiger Chow committed
55
const (
56 57
	// outboxChanBuffer must be 0 to prevent stale messages from being sent
	outboxChanBuffer = 0
58 59
	// maxMessageSize is the maximum size of the batched payload
	maxMessageSize = 512 * 1024
Brian Tiger Chow's avatar
Brian Tiger Chow committed
60 61
)

62
// Envelope contains a message for a Peer.
63
type Envelope struct {
64
	// Peer is the intended recipient.
65
	Peer peer.ID
66

67
	// Message is the payload.
68
	Message bsmsg.BitSwapMessage
Jeromy's avatar
Jeromy committed
69 70 71

	// A callback to notify the decision queue that the task is complete
	Sent func()
72 73
}

74
// Engine manages sending requested blocks to peers.
75
type Engine struct {
76 77 78
	// peerRequestQueue is a priority queue of requests received from peers.
	// Requests are popped from the queue, packaged up, and placed in the
	// outbox.
79
	peerRequestQueue *peertaskqueue.PeerTaskQueue
80

81 82 83 84 85
	// FIXME it's a bit odd for the client and the worker to both share memory
	// (both modify the peerRequestQueue) and also to communicate over the
	// workSignal channel. consider sending requests over the channel and
	// allowing the worker to have exclusive access to the peerRequestQueue. In
	// that case, no lock would be required.
Jeromy's avatar
Jeromy committed
86
	workSignal chan struct{}
87

88 89
	// outbox contains outgoing messages to peers. This is owned by the
	// taskWorker goroutine
Brian Tiger Chow's avatar
Brian Tiger Chow committed
90
	outbox chan (<-chan *Envelope)
91 92 93

	bs bstore.Blockstore

94
	lock sync.Mutex // protects the fields immediatly below
95
	// ledgerMap lists Ledgers by their Partner key.
96
	ledgerMap map[peer.ID]*ledger
Jeromy's avatar
Jeromy committed
97 98

	ticker *time.Ticker
99 100
}

101
// NewEngine creates a new block sending engine for the given block store
102 103
func NewEngine(ctx context.Context, bs bstore.Blockstore) *Engine {
	e := &Engine{
104
		ledgerMap:        make(map[peer.ID]*ledger),
Brian Tiger Chow's avatar
Brian Tiger Chow committed
105
		bs:               bs,
106
		peerRequestQueue: peertaskqueue.New(),
Brian Tiger Chow's avatar
Brian Tiger Chow committed
107
		outbox:           make(chan (<-chan *Envelope), outboxChanBuffer),
108
		workSignal:       make(chan struct{}, 1),
Jeromy's avatar
Jeromy committed
109
		ticker:           time.NewTicker(time.Millisecond * 100),
110
	}
111 112
	go e.taskWorker(ctx)
	return e
Jeromy's avatar
Jeromy committed
113 114
}

115
// WantlistForPeer returns the currently understood want list for a given peer
116
func (e *Engine) WantlistForPeer(p peer.ID) (out []wl.Entry) {
117 118 119 120
	partner := e.findOrCreate(p)
	partner.lk.Lock()
	defer partner.lk.Unlock()
	return partner.wantList.SortedEntries()
121 122
}

123 124
// LedgerForPeer returns aggregated data about blocks swapped and communication
// with a given peer.
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
func (e *Engine) LedgerForPeer(p peer.ID) *Receipt {
	ledger := e.findOrCreate(p)

	ledger.lk.Lock()
	defer ledger.lk.Unlock()

	return &Receipt{
		Peer:      ledger.Partner.String(),
		Value:     ledger.Accounting.Value(),
		Sent:      ledger.Accounting.BytesSent,
		Recv:      ledger.Accounting.BytesRecv,
		Exchanged: ledger.ExchangeCount(),
	}
}

140
func (e *Engine) taskWorker(ctx context.Context) {
141 142
	defer close(e.outbox) // because taskWorker uses the channel exclusively
	for {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
143
		oneTimeUse := make(chan *Envelope, 1) // buffer to prevent blocking
144 145 146 147 148 149 150 151 152 153 154 155
		select {
		case <-ctx.Done():
			return
		case e.outbox <- oneTimeUse:
		}
		// receiver is ready for an outoing envelope. let's prepare one. first,
		// we must acquire a task from the PQ...
		envelope, err := e.nextEnvelope(ctx)
		if err != nil {
			close(oneTimeUse)
			return // ctx cancelled
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
156
		oneTimeUse <- envelope // buffered. won't block
157 158 159 160 161 162 163
		close(oneTimeUse)
	}
}

// nextEnvelope runs in the taskWorker goroutine. Returns an error if the
// context is cancelled before the next Envelope can be created.
func (e *Engine) nextEnvelope(ctx context.Context) (*Envelope, error) {
Jeromy's avatar
Jeromy committed
164
	for {
165
		nextTask := e.peerRequestQueue.PopBlock()
166
		for nextTask == nil {
Jeromy's avatar
Jeromy committed
167
			select {
168
			case <-ctx.Done():
169
				return nil, ctx.Err()
170
			case <-e.workSignal:
171
				nextTask = e.peerRequestQueue.PopBlock()
Jeromy's avatar
Jeromy committed
172
			case <-e.ticker.C:
173 174
				e.peerRequestQueue.ThawRound()
				nextTask = e.peerRequestQueue.PopBlock()
Jeromy's avatar
Jeromy committed
175 176
			}
		}
177 178

		// with a task in hand, we're ready to prepare the envelope...
179
		msg := bsmsg.New(true)
180 181
		for _, entry := range nextTask.Tasks {
			block, err := e.bs.Get(entry.Identifier.(cid.Cid))
182 183 184 185 186 187
			if err != nil {
				log.Errorf("tried to execute a task and errored fetching block: %s", err)
				continue
			}
			msg.AddBlock(block)
		}
188

189
		if msg.Empty() {
Jeromy's avatar
Jeromy committed
190 191
			// If we don't have the block, don't hold that against the peer
			// make sure to update that the task has been 'completed'
192
			nextTask.Done(nextTask.Tasks)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
193
			continue
194
		}
195

196
		return &Envelope{
197 198
			Peer:    nextTask.Target,
			Message: msg,
199
			Sent: func() {
200
				nextTask.Done(nextTask.Tasks)
201 202 203 204 205 206 207
				select {
				case e.workSignal <- struct{}{}:
					// work completing may mean that our queue will provide new
					// work to be done.
				default:
				}
			},
208
		}, nil
Jeromy's avatar
Jeromy committed
209 210 211
	}
}

212
// Outbox returns a channel of one-time use Envelope channels.
Brian Tiger Chow's avatar
Brian Tiger Chow committed
213
func (e *Engine) Outbox() <-chan (<-chan *Envelope) {
214
	return e.outbox
215 216
}

217
// Peers returns a slice of Peers with whom the local node has active sessions.
218
func (e *Engine) Peers() []peer.ID {
219 220
	e.lock.Lock()
	defer e.lock.Unlock()
221

222 223
	response := make([]peer.ID, 0, len(e.ledgerMap))

224
	for _, ledger := range e.ledgerMap {
225 226 227 228 229 230 231
		response = append(response, ledger.Partner)
	}
	return response
}

// MessageReceived performs book-keeping. Returns error if passed invalid
// arguments.
232
func (e *Engine) MessageReceived(p peer.ID, m bsmsg.BitSwapMessage) {
233
	if m.Empty() {
234
		log.Debugf("received empty message from %s", p)
235 236
	}

237 238 239
	newWorkExists := false
	defer func() {
		if newWorkExists {
240
			e.signalNewWork()
241 242
		}
	}()
243

244
	l := e.findOrCreate(p)
Jeromy's avatar
Jeromy committed
245 246
	l.lk.Lock()
	defer l.lk.Unlock()
247 248 249
	if m.Full() {
		l.wantList = wl.New()
	}
250

251
	var msgSize int
252
	var activeEntries []peertask.Task
253 254
	for _, entry := range m.Wantlist() {
		if entry.Cancel {
255 256 257
			log.Debugf("%s cancel %s", p, entry.Cid)
			l.CancelWant(entry.Cid)
			e.peerRequestQueue.Remove(entry.Cid, p)
258
		} else {
259 260
			log.Debugf("wants %s - %d", entry.Cid, entry.Priority)
			l.Wants(entry.Cid, entry.Priority)
261 262 263 264 265 266 267
			blockSize, err := e.bs.GetSize(entry.Cid)
			if err != nil {
				if err == bstore.ErrNotFound {
					continue
				}
				log.Error(err)
			} else {
268
				// we have the block
Brian Tiger Chow's avatar
Brian Tiger Chow committed
269
				newWorkExists = true
270
				if msgSize+blockSize > maxMessageSize {
271 272
					e.peerRequestQueue.PushBlock(p, activeEntries...)
					activeEntries = []peertask.Task{}
273 274
					msgSize = 0
				}
275
				activeEntries = append(activeEntries, peertask.Task{Identifier: entry.Cid, Priority: entry.Priority})
276
				msgSize += blockSize
277
			}
278 279
		}
	}
280
	if len(activeEntries) > 0 {
281
		e.peerRequestQueue.PushBlock(p, activeEntries...)
282
	}
283
	for _, block := range m.Blocks() {
Jeromy's avatar
Jeromy committed
284 285
		log.Debugf("got block %s %d bytes", block, len(block.RawData()))
		l.ReceivedBytes(len(block.RawData()))
286 287 288
	}
}

289
func (e *Engine) addBlock(block blocks.Block) {
290 291 292
	work := false

	for _, l := range e.ledgerMap {
Jeromy's avatar
Jeromy committed
293
		l.lk.Lock()
294
		if entry, ok := l.WantListContains(block.Cid()); ok {
295 296 297 298
			e.peerRequestQueue.PushBlock(l.Partner, peertask.Task{
				Identifier: entry.Cid,
				Priority:   entry.Priority,
			})
299 300
			work = true
		}
Jeromy's avatar
Jeromy committed
301
		l.lk.Unlock()
302 303 304 305 306 307 308
	}

	if work {
		e.signalNewWork()
	}
}

309 310
// AddBlock is called to when a new block is received and added to a block store
// meaning there may be peers who want that block that we should send it to.
311
func (e *Engine) AddBlock(block blocks.Block) {
312 313 314 315 316 317
	e.lock.Lock()
	defer e.lock.Unlock()

	e.addBlock(block)
}

318 319 320 321 322 323
// TODO add contents of m.WantList() to my local wantlist? NB: could introduce
// race conditions where I send a message, but MessageSent gets handled after
// MessageReceived. The information in the local wantlist could become
// inconsistent. Would need to ensure that Sends and acknowledgement of the
// send happen atomically

324 325
// MessageSent is called when a message has successfully been sent out, to record
// changes.
326
func (e *Engine) MessageSent(p peer.ID, m bsmsg.BitSwapMessage) {
327
	l := e.findOrCreate(p)
328 329 330
	l.lk.Lock()
	defer l.lk.Unlock()

331
	for _, block := range m.Blocks() {
Jeromy's avatar
Jeromy committed
332
		l.SentBytes(len(block.RawData()))
333 334
		l.wantList.Remove(block.Cid())
		e.peerRequestQueue.Remove(block.Cid(), p)
335 336 337 338
	}

}

339 340
// PeerConnected is called when a new peer connects, meaning we should start
// sending blocks.
341 342
func (e *Engine) PeerConnected(p peer.ID) {
	e.lock.Lock()
343
	defer e.lock.Unlock()
344 345 346 347 348 349
	l, ok := e.ledgerMap[p]
	if !ok {
		l = newLedger(p)
		e.ledgerMap[p] = l
	}
	l.lk.Lock()
350
	defer l.lk.Unlock()
351 352 353
	l.ref++
}

354
// PeerDisconnected is called when a peer disconnects.
355
func (e *Engine) PeerDisconnected(p peer.ID) {
356 357 358 359 360 361 362
	e.lock.Lock()
	defer e.lock.Unlock()
	l, ok := e.ledgerMap[p]
	if !ok {
		return
	}
	l.lk.Lock()
363
	defer l.lk.Unlock()
364 365 366 367
	l.ref--
	if l.ref <= 0 {
		delete(e.ledgerMap, p)
	}
368 369
}

370
func (e *Engine) numBytesSentTo(p peer.ID) uint64 {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
371
	// NB not threadsafe
372
	return e.findOrCreate(p).Accounting.BytesSent
373 374
}

375
func (e *Engine) numBytesReceivedFrom(p peer.ID) uint64 {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
376
	// NB not threadsafe
377
	return e.findOrCreate(p).Accounting.BytesRecv
378 379 380
}

// ledger lazily instantiates a ledger
381
func (e *Engine) findOrCreate(p peer.ID) *ledger {
Jeromy's avatar
Jeromy committed
382
	e.lock.Lock()
383
	defer e.lock.Unlock()
384
	l, ok := e.ledgerMap[p]
385 386
	if !ok {
		l = newLedger(p)
387
		e.ledgerMap[p] = l
388 389 390
	}
	return l
}
391 392 393 394 395 396 397 398

func (e *Engine) signalNewWork() {
	// Signal task generation to restart (if stopped!)
	select {
	case e.workSignal <- struct{}{}:
	default:
	}
}