engine.go 10.6 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

Jeromy's avatar
Jeromy committed
12 13 14 15
	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"
16 17
)

18 19 20 21 22 23 24 25
// 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:
26 27
// 1. an initial `sendwantlist` message to a provider of the first key in a
//    request
28 29 30 31 32 33 34 35 36 37 38 39
// 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
40 41
// * when handling `blockrequests`, include `sendwantlist` and `cancel` as
//   appropriate
42
// * when handling `cancel`, if we recently received a wanted block from a
43
//   peer, include a partial wantlist that contains a few other high priority
44 45 46 47 48 49
//   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
50
var log = logging.Logger("engine")
51

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

59
// Envelope contains a message for a Peer.
60
type Envelope struct {
61
	// Peer is the intended recipient.
62
	Peer peer.ID
63

64
	// Message is the payload.
65
	Message bsmsg.BitSwapMessage
Jeromy's avatar
Jeromy committed
66 67 68

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

71
// Engine manages sending requested blocks to peers.
72
type Engine struct {
73 74 75
	// peerRequestQueue is a priority queue of requests received from peers.
	// Requests are popped from the queue, packaged up, and placed in the
	// outbox.
Jeromy's avatar
Jeromy committed
76
	peerRequestQueue *prq
77

78 79 80 81 82
	// 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
83
	workSignal chan struct{}
84

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

	bs bstore.Blockstore

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

	ticker *time.Ticker
96 97
}

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

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

120 121
// LedgerForPeer returns aggregated data about blocks swapped and communication
// with a given peer.
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
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(),
	}
}

137
func (e *Engine) taskWorker(ctx context.Context) {
138 139
	defer close(e.outbox) // because taskWorker uses the channel exclusively
	for {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
140
		oneTimeUse := make(chan *Envelope, 1) // buffer to prevent blocking
141 142 143 144 145 146 147 148 149 150 151 152
		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
153
		oneTimeUse <- envelope // buffered. won't block
154 155 156 157 158 159 160
		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
161
	for {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
162
		nextTask := e.peerRequestQueue.Pop()
163
		for nextTask == nil {
Jeromy's avatar
Jeromy committed
164
			select {
165
			case <-ctx.Done():
166
				return nil, ctx.Err()
167
			case <-e.workSignal:
168
				nextTask = e.peerRequestQueue.Pop()
Jeromy's avatar
Jeromy committed
169 170 171
			case <-e.ticker.C:
				e.peerRequestQueue.thawRound()
				nextTask = e.peerRequestQueue.Pop()
Jeromy's avatar
Jeromy committed
172 173
			}
		}
174 175

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

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

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

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

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

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

221
	for _, ledger := range e.ledgerMap {
222 223 224 225 226 227 228
		response = append(response, ledger.Partner)
	}
	return response
}

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

234 235 236
	newWorkExists := false
	defer func() {
		if newWorkExists {
237
			e.signalNewWork()
238 239
		}
	}()
240

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

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

286
func (e *Engine) addBlock(block blocks.Block) {
287 288 289
	work := false

	for _, l := range e.ledgerMap {
Jeromy's avatar
Jeromy committed
290
		l.lk.Lock()
291
		if entry, ok := l.WantListContains(block.Cid()); ok {
292
			e.peerRequestQueue.Push(l.Partner, entry)
293 294
			work = true
		}
Jeromy's avatar
Jeromy committed
295
		l.lk.Unlock()
296 297 298 299 300 301 302
	}

	if work {
		e.signalNewWork()
	}
}

303 304
// 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.
305
func (e *Engine) AddBlock(block blocks.Block) {
306 307 308 309 310 311
	e.lock.Lock()
	defer e.lock.Unlock()

	e.addBlock(block)
}

312 313 314 315 316 317
// 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

318 319
// MessageSent is called when a message has successfully been sent out, to record
// changes.
320
func (e *Engine) MessageSent(p peer.ID, m bsmsg.BitSwapMessage) {
321
	l := e.findOrCreate(p)
322 323 324
	l.lk.Lock()
	defer l.lk.Unlock()

325
	for _, block := range m.Blocks() {
Jeromy's avatar
Jeromy committed
326
		l.SentBytes(len(block.RawData()))
327 328
		l.wantList.Remove(block.Cid())
		e.peerRequestQueue.Remove(block.Cid(), p)
329 330 331 332
	}

}

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

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

364
func (e *Engine) numBytesSentTo(p peer.ID) uint64 {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
365
	// NB not threadsafe
366
	return e.findOrCreate(p).Accounting.BytesSent
367 368
}

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

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

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