engine.go 8.46 KB
Newer Older
Jeromy's avatar
Jeromy committed
1
// package decision implements the decision engine for the bitswap service.
2
package decision
3 4 5 6

import (
	"sync"

7
	blocks "github.com/ipfs/go-ipfs/blocks"
8 9 10
	bstore "github.com/ipfs/go-ipfs/blocks/blockstore"
	bsmsg "github.com/ipfs/go-ipfs/exchange/bitswap/message"
	wl "github.com/ipfs/go-ipfs/exchange/bitswap/wantlist"
11
	peer "gx/ipfs/QmZpD74pUj6vuxTp1o6LhA3JavC2Bvh9fsWPPVvHnD9sE7/go-libp2p-peer"
Jeromy's avatar
Jeromy committed
12
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
13
	logging "gx/ipfs/QmaDNZ4QMdBdku1YZWBysufYyoQt1negQGNav6PLYarbY8/go-log"
14 15
)

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
50
const (
51 52
	// outboxChanBuffer must be 0 to prevent stale messages from being sent
	outboxChanBuffer = 0
Brian Tiger Chow's avatar
Brian Tiger Chow committed
53 54
)

55
// Envelope contains a message for a Peer
56
type Envelope struct {
57
	// Peer is the intended recipient
58
	Peer peer.ID
59 60

	// Block is the payload
61
	Block blocks.Block
Jeromy's avatar
Jeromy committed
62 63 64

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

67
type Engine struct {
68 69 70
	// peerRequestQueue is a priority queue of requests received from peers.
	// Requests are popped from the queue, packaged up, and placed in the
	// outbox.
Brian Tiger Chow's avatar
Brian Tiger Chow committed
71
	peerRequestQueue peerRequestQueue
72

73 74 75 76 77
	// 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
78
	workSignal chan struct{}
79

80 81
	// outbox contains outgoing messages to peers. This is owned by the
	// taskWorker goroutine
Brian Tiger Chow's avatar
Brian Tiger Chow committed
82
	outbox chan (<-chan *Envelope)
83 84 85

	bs bstore.Blockstore

86
	lock sync.Mutex // protects the fields immediatly below
87
	// ledgerMap lists Ledgers by their Partner key.
88
	ledgerMap map[peer.ID]*ledger
89 90
}

91 92
func NewEngine(ctx context.Context, bs bstore.Blockstore) *Engine {
	e := &Engine{
93
		ledgerMap:        make(map[peer.ID]*ledger),
Brian Tiger Chow's avatar
Brian Tiger Chow committed
94
		bs:               bs,
Brian Tiger Chow's avatar
Brian Tiger Chow committed
95
		peerRequestQueue: newPRQ(),
Brian Tiger Chow's avatar
Brian Tiger Chow committed
96
		outbox:           make(chan (<-chan *Envelope), outboxChanBuffer),
97
		workSignal:       make(chan struct{}, 1),
98
	}
99 100
	go e.taskWorker(ctx)
	return e
Jeromy's avatar
Jeromy committed
101 102
}

103 104 105 106 107 108 109 110 111 112
func (e *Engine) WantlistForPeer(p peer.ID) (out []wl.Entry) {
	e.lock.Lock()
	partner, ok := e.ledgerMap[p]
	if ok {
		out = partner.wantList.SortedEntries()
	}
	e.lock.Unlock()
	return out
}

113
func (e *Engine) taskWorker(ctx context.Context) {
114 115
	defer close(e.outbox) // because taskWorker uses the channel exclusively
	for {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
116
		oneTimeUse := make(chan *Envelope, 1) // buffer to prevent blocking
117 118 119 120 121 122 123 124 125 126 127 128
		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
129
		oneTimeUse <- envelope // buffered. won't block
130 131 132 133 134 135 136
		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
137
	for {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
138
		nextTask := e.peerRequestQueue.Pop()
139
		for nextTask == nil {
Jeromy's avatar
Jeromy committed
140
			select {
141
			case <-ctx.Done():
142
				return nil, ctx.Err()
143
			case <-e.workSignal:
144
				nextTask = e.peerRequestQueue.Pop()
Jeromy's avatar
Jeromy committed
145 146
			}
		}
147 148

		// with a task in hand, we're ready to prepare the envelope...
149

150
		block, err := e.bs.Get(nextTask.Entry.Key)
151
		if err != nil {
Jeromy's avatar
Jeromy committed
152 153 154
			// If we don't have the block, don't hold that against the peer
			// make sure to update that the task has been 'completed'
			nextTask.Done()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
155
			continue
156
		}
157

158
		return &Envelope{
159 160
			Peer:  nextTask.Target,
			Block: block,
161 162 163 164 165 166 167 168 169
			Sent: func() {
				nextTask.Done()
				select {
				case e.workSignal <- struct{}{}:
					// work completing may mean that our queue will provide new
					// work to be done.
				default:
				}
			},
170
		}, nil
Jeromy's avatar
Jeromy committed
171 172 173
	}
}

174
// Outbox returns a channel of one-time use Envelope channels.
Brian Tiger Chow's avatar
Brian Tiger Chow committed
175
func (e *Engine) Outbox() <-chan (<-chan *Envelope) {
176
	return e.outbox
177 178 179
}

// Returns a slice of Peers with whom the local node has active sessions
180
func (e *Engine) Peers() []peer.ID {
181 182
	e.lock.Lock()
	defer e.lock.Unlock()
183

184
	response := make([]peer.ID, 0)
185
	for _, ledger := range e.ledgerMap {
186 187 188 189 190 191 192
		response = append(response, ledger.Partner)
	}
	return response
}

// MessageReceived performs book-keeping. Returns error if passed invalid
// arguments.
193
func (e *Engine) MessageReceived(p peer.ID, m bsmsg.BitSwapMessage) error {
194 195 196
	e.lock.Lock()
	defer e.lock.Unlock()

197
	if len(m.Wantlist()) == 0 && len(m.Blocks()) == 0 {
198
		log.Debugf("received empty message from %s", p)
199 200
	}

201 202 203
	newWorkExists := false
	defer func() {
		if newWorkExists {
204
			e.signalNewWork()
205 206
		}
	}()
207

208
	l := e.findOrCreate(p)
209 210 211
	if m.Full() {
		l.wantList = wl.New()
	}
212

213 214
	for _, entry := range m.Wantlist() {
		if entry.Cancel {
Jeromy's avatar
Jeromy committed
215
			log.Debugf("cancel %s", entry.Key)
216
			l.CancelWant(entry.Key)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
217
			e.peerRequestQueue.Remove(entry.Key, p)
218
		} else {
Jeromy's avatar
Jeromy committed
219
			log.Debugf("wants %s - %d", entry.Key, entry.Priority)
220
			l.Wants(entry.Key, entry.Priority)
221
			if exists, err := e.bs.Has(entry.Key); err == nil && exists {
222
				e.peerRequestQueue.Push(entry.Entry, p)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
223
				newWorkExists = true
224
			}
225 226
		}
	}
Jeromy's avatar
Jeromy committed
227

228
	for _, block := range m.Blocks() {
229 230
		log.Debugf("got block %s %d bytes", block.Key(), len(block.Data()))
		l.ReceivedBytes(len(block.Data()))
231 232 233 234
	}
	return nil
}

235
func (e *Engine) addBlock(block blocks.Block) {
236 237 238 239 240 241 242 243 244 245 246 247 248 249
	work := false

	for _, l := range e.ledgerMap {
		if entry, ok := l.WantListContains(block.Key()); ok {
			e.peerRequestQueue.Push(entry, l.Partner)
			work = true
		}
	}

	if work {
		e.signalNewWork()
	}
}

250
func (e *Engine) AddBlock(block blocks.Block) {
251 252 253 254 255 256
	e.lock.Lock()
	defer e.lock.Unlock()

	e.addBlock(block)
}

257 258 259 260 261 262
// 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

263
func (e *Engine) MessageSent(p peer.ID, m bsmsg.BitSwapMessage) error {
264 265
	e.lock.Lock()
	defer e.lock.Unlock()
266

267
	l := e.findOrCreate(p)
268
	for _, block := range m.Blocks() {
269
		l.SentBytes(len(block.Data()))
270
		l.wantList.Remove(block.Key())
Brian Tiger Chow's avatar
Brian Tiger Chow committed
271
		e.peerRequestQueue.Remove(block.Key(), p)
272 273 274 275 276
	}

	return nil
}

277 278 279 280
func (e *Engine) PeerDisconnected(p peer.ID) {
	// TODO: release ledger
}

281
func (e *Engine) numBytesSentTo(p peer.ID) uint64 {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
282
	// NB not threadsafe
283
	return e.findOrCreate(p).Accounting.BytesSent
284 285
}

286
func (e *Engine) numBytesReceivedFrom(p peer.ID) uint64 {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
287
	// NB not threadsafe
288
	return e.findOrCreate(p).Accounting.BytesRecv
289 290 291
}

// ledger lazily instantiates a ledger
292 293
func (e *Engine) findOrCreate(p peer.ID) *ledger {
	l, ok := e.ledgerMap[p]
294 295
	if !ok {
		l = newLedger(p)
296
		e.ledgerMap[p] = l
297 298 299
	}
	return l
}
300 301 302 303 304 305 306 307

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