tendermint/blockchain/pool.go

513 lines
12 KiB
Go
Raw Normal View History

package blockchain
2015-03-22 03:30:22 -07:00
import (
"math"
2015-03-24 11:02:30 -07:00
"sync"
2015-03-22 03:30:22 -07:00
"time"
. "github.com/tendermint/go-common"
2016-11-04 06:46:34 -07:00
flow "github.com/tendermint/go-flowrate/flowrate"
2015-04-01 17:30:16 -07:00
"github.com/tendermint/tendermint/types"
2015-03-22 03:30:22 -07:00
)
const (
2015-09-12 08:47:59 -07:00
requestIntervalMS = 250
maxTotalRequesters = 300
maxPendingRequests = maxTotalRequesters
2015-09-12 08:47:59 -07:00
maxPendingRequestsPerPeer = 75
minRecvRate = 10240 // 10Kb/s
2015-03-22 19:20:54 -07:00
)
var peerTimeoutSeconds = time.Duration(15) // not const so we can override with tests
/*
2015-07-10 08:39:49 -07:00
Peers self report their heights when we join the block pool.
Starting from our latest pool.height, we request blocks
in sequence from peers that reported higher heights than ours.
Every so often we ask peers what height they're on so we can keep going.
2017-01-13 01:16:50 -08:00
Requests are continuously made for blocks of higher heights until
the limits. If most of the requests have no available peers, and we
are not at peer limits, we can probably switch to consensus reactor
*/
2015-03-22 03:30:22 -07:00
type BlockPool struct {
2016-10-28 12:14:24 -07:00
BaseService
2015-09-11 19:00:27 -07:00
startTime time.Time
2016-06-28 18:02:27 -07:00
mtx sync.Mutex
2015-03-24 11:02:30 -07:00
// block requests
requesters map[int]*bpRequester
height int // the lowest key in requesters.
numPending int32 // number of requests pending assignment or block response
2015-03-24 11:02:30 -07:00
// peers
2016-06-28 18:02:27 -07:00
peers map[string]*bpPeer
2015-03-24 11:02:30 -07:00
requestsCh chan<- BlockRequest
timeoutsCh chan<- string
2015-03-22 03:30:22 -07:00
}
func NewBlockPool(start int, requestsCh chan<- BlockRequest, timeoutsCh chan<- string) *BlockPool {
bp := &BlockPool{
2015-03-24 11:02:30 -07:00
peers: make(map[string]*bpPeer),
requesters: make(map[int]*bpRequester),
height: start,
numPending: 0,
2015-03-22 03:30:22 -07:00
requestsCh: requestsCh,
timeoutsCh: timeoutsCh,
}
2016-10-28 12:14:24 -07:00
bp.BaseService = *NewBaseService(log, "BlockPool", bp)
return bp
2015-03-22 03:30:22 -07:00
}
func (pool *BlockPool) OnStart() error {
go pool.makeRequestersRoutine()
2015-09-11 19:00:27 -07:00
pool.startTime = time.Now()
return nil
2015-03-22 03:30:22 -07:00
}
2015-07-21 18:31:01 -07:00
func (pool *BlockPool) OnStop() {
2016-10-28 12:14:24 -07:00
pool.BaseService.OnStop()
2015-03-22 03:30:22 -07:00
}
// Run spawns requesters as needed.
func (pool *BlockPool) makeRequestersRoutine() {
2015-03-22 03:30:22 -07:00
for {
if !pool.IsRunning() {
break
2015-03-24 11:02:30 -07:00
}
2016-06-24 17:21:44 -07:00
_, numPending, lenRequesters := pool.GetStatus()
2015-05-28 03:18:13 -07:00
if numPending >= maxPendingRequests {
2015-03-24 11:02:30 -07:00
// sleep for a bit.
time.Sleep(requestIntervalMS * time.Millisecond)
2015-09-09 21:44:48 -07:00
// check for timed out peers
pool.removeTimedoutPeers()
2016-06-24 17:21:44 -07:00
} else if lenRequesters >= maxTotalRequesters {
2015-03-24 11:02:30 -07:00
// sleep for a bit.
time.Sleep(requestIntervalMS * time.Millisecond)
2015-09-09 21:44:48 -07:00
// check for timed out peers
pool.removeTimedoutPeers()
2015-03-24 11:02:30 -07:00
} else {
// request for more blocks.
pool.makeNextRequester()
2015-03-22 03:30:22 -07:00
}
}
}
2015-09-09 21:44:48 -07:00
func (pool *BlockPool) removeTimedoutPeers() {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-09-09 21:44:48 -07:00
for _, peer := range pool.peers {
if !peer.didTimeout && peer.numPending > 0 {
curRate := peer.recvMonitor.Status().CurRate
// XXX remove curRate != 0
if curRate != 0 && curRate < minRecvRate {
pool.sendTimeout(peer.id)
2015-09-11 18:17:19 -07:00
log.Warn("SendTimeout", "peer", peer.id, "reason", "curRate too low")
2015-09-09 21:44:48 -07:00
peer.didTimeout = true
}
}
if peer.didTimeout {
pool.removePeer(peer.id)
}
}
}
2016-06-24 17:21:44 -07:00
func (pool *BlockPool) GetStatus() (height int, numPending int32, lenRequesters int) {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2016-06-24 17:21:44 -07:00
return pool.height, pool.numPending, len(pool.requesters)
}
// TODO: relax conditions, prevent abuse.
func (pool *BlockPool) IsCaughtUp() bool {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2016-06-24 17:21:44 -07:00
2016-06-28 18:02:27 -07:00
height := pool.height
2016-01-02 16:21:40 -08:00
// Need at least 1 peer to be considered caught up.
if len(pool.peers) == 0 {
2016-02-07 16:56:59 -08:00
log.Debug("Blockpool has no peers")
2016-01-02 16:21:40 -08:00
return false
}
maxPeerHeight := 0
for _, peer := range pool.peers {
maxPeerHeight = MaxInt(maxPeerHeight, peer.height)
}
2015-03-22 16:23:24 -07:00
2016-02-07 16:56:59 -08:00
isCaughtUp := (height > 0 || time.Now().Sub(pool.startTime) > 5*time.Second) && (maxPeerHeight == 0 || height >= maxPeerHeight)
log.Notice(Fmt("IsCaughtUp: %v", isCaughtUp), "height", height, "maxPeerHeight", maxPeerHeight)
return isCaughtUp
2015-03-24 11:02:30 -07:00
}
2015-03-22 16:23:24 -07:00
2016-04-02 09:10:16 -07:00
// We need to see the second block's Commit to validate the first block.
2015-03-24 11:02:30 -07:00
// So we peek two blocks at a time.
2016-04-02 09:10:16 -07:00
// The caller will verify the commit.
func (pool *BlockPool) PeekTwoBlocks() (first *types.Block, second *types.Block) {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
if r := pool.requesters[pool.height]; r != nil {
2015-09-12 08:47:59 -07:00
first = r.getBlock()
2015-03-24 11:02:30 -07:00
}
if r := pool.requesters[pool.height+1]; r != nil {
2015-09-12 08:47:59 -07:00
second = r.getBlock()
2015-03-22 03:30:22 -07:00
}
2015-03-24 11:02:30 -07:00
return
2015-03-22 03:30:22 -07:00
}
// Pop the first block at pool.height
2016-04-02 09:10:16 -07:00
// It must have been validated by 'second'.Commit from PeekTwoBlocks().
func (pool *BlockPool) PopRequest() {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
if r := pool.requesters[pool.height]; r != nil {
/* The block can disappear at any time, due to removePeer().
if r := pool.requesters[pool.height]; r == nil || r.block == nil {
PanicSanity("PopRequest() requires a valid block")
}
*/
r.Stop()
delete(pool.requesters, pool.height)
pool.height++
} else {
PanicSanity(Fmt("Expected requester to pop, got nothing at height %v", pool.height))
2015-03-22 03:30:22 -07:00
}
2015-03-22 12:46:53 -07:00
}
// Invalidates the block at pool.height,
// Remove the peer and redo request from others.
func (pool *BlockPool) RedoRequest(height int) {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
request := pool.requesters[height]
2016-06-24 17:21:44 -07:00
pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
if request.block == nil {
2015-07-19 16:42:52 -07:00
PanicSanity("Expected block to be non-nil")
2015-03-22 03:30:22 -07:00
}
// RemovePeer will redo all requesters associated with this peer.
// TODO: record this malfeasance
2016-06-28 18:02:27 -07:00
pool.RemovePeer(request.peerID)
2015-03-22 03:30:22 -07:00
}
// TODO: ensure that blocks come in order for each peer.
func (pool *BlockPool) AddBlock(peerID string, block *types.Block, blockSize int) {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
requester := pool.requesters[block.Height]
if requester == nil {
2015-03-24 11:02:30 -07:00
return
2015-03-22 12:46:53 -07:00
}
if requester.setBlock(block, peerID) {
pool.numPending--
2016-06-28 18:02:27 -07:00
peer := pool.peers[peerID]
peer.decrPending(blockSize)
} else {
// Bad peer?
}
}
// Sets the peer's alleged blockchain height.
func (pool *BlockPool) SetPeerHeight(peerID string, height int) {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
peer := pool.peers[peerID]
if peer != nil {
peer.height = height
} else {
peer = newBPPeer(pool, peerID, height)
pool.peers[peerID] = peer
2015-03-24 11:02:30 -07:00
}
}
func (pool *BlockPool) RemovePeer(peerID string) {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
pool.removePeer(peerID)
2015-03-22 12:46:53 -07:00
}
func (pool *BlockPool) removePeer(peerID string) {
for _, requester := range pool.requesters {
if requester.getPeerID() == peerID {
2017-04-14 23:22:03 -07:00
if requester.getBlock() != nil {
pool.numPending++
}
go requester.redo() // pick another peer and ...
2015-03-22 12:46:53 -07:00
}
}
delete(pool.peers, peerID)
2015-03-22 12:46:53 -07:00
}
2015-03-24 11:02:30 -07:00
// Pick an available peer with at least the given minHeight.
// If no peers are available, returns nil.
func (pool *BlockPool) pickIncrAvailablePeer(minHeight int) *bpPeer {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
for _, peer := range pool.peers {
2016-06-28 18:02:27 -07:00
if peer.didTimeout {
pool.removePeer(peer.id)
continue
2015-09-09 21:44:48 -07:00
} else {
}
if peer.numPending >= maxPendingRequestsPerPeer {
2015-03-24 11:02:30 -07:00
continue
}
if peer.height < minHeight {
continue
}
2016-06-28 18:02:27 -07:00
peer.incrPending()
2015-03-24 11:02:30 -07:00
return peer
2015-03-22 03:30:22 -07:00
}
2015-03-24 11:02:30 -07:00
return nil
2015-03-22 03:30:22 -07:00
}
func (pool *BlockPool) makeNextRequester() {
2016-06-28 18:02:27 -07:00
pool.mtx.Lock()
defer pool.mtx.Unlock()
2015-03-22 03:30:22 -07:00
nextHeight := pool.height + len(pool.requesters)
request := newBPRequester(pool, nextHeight)
2015-03-24 11:02:30 -07:00
pool.requesters[nextHeight] = request
2015-05-28 03:18:13 -07:00
pool.numPending++
request.Start()
2015-03-22 03:30:22 -07:00
}
func (pool *BlockPool) sendRequest(height int, peerID string) {
if !pool.IsRunning() {
2015-03-24 11:02:30 -07:00
return
2015-03-22 03:30:22 -07:00
}
pool.requestsCh <- BlockRequest{height, peerID}
2015-03-22 03:30:22 -07:00
}
func (pool *BlockPool) sendTimeout(peerID string) {
if !pool.IsRunning() {
2015-03-24 11:02:30 -07:00
return
}
pool.timeoutsCh <- peerID
2015-03-24 11:02:30 -07:00
}
func (pool *BlockPool) debug() string {
pool.mtx.Lock() // Lock
defer pool.mtx.Unlock()
2015-03-24 11:02:30 -07:00
str := ""
for h := pool.height; h < pool.height+len(pool.requesters); h++ {
if pool.requesters[h] == nil {
2015-03-24 11:02:30 -07:00
str += Fmt("H(%v):X ", h)
} else {
str += Fmt("H(%v):", h)
str += Fmt("B?(%v) ", pool.requesters[h].block != nil)
2015-03-24 11:02:30 -07:00
}
}
return str
2015-03-22 03:30:22 -07:00
}
//-------------------------------------
2015-03-24 11:02:30 -07:00
type bpPeer struct {
pool *BlockPool
2015-03-24 11:02:30 -07:00
id string
recvMonitor *flow.Monitor
2016-06-28 18:02:27 -07:00
mtx sync.Mutex
height int
numPending int32
timeout *time.Timer
didTimeout bool
2015-03-22 03:30:22 -07:00
}
func newBPPeer(pool *BlockPool, peerID string, height int) *bpPeer {
peer := &bpPeer{
pool: pool,
id: peerID,
height: height,
numPending: 0,
}
return peer
}
2015-09-12 08:47:59 -07:00
func (peer *bpPeer) resetMonitor() {
peer.recvMonitor = flow.New(time.Second, time.Second*40)
var initialValue = float64(minRecvRate) * math.E
2015-09-12 08:47:59 -07:00
peer.recvMonitor.SetREMA(initialValue)
}
2016-06-28 18:02:27 -07:00
func (peer *bpPeer) resetTimeout() {
2015-09-12 08:47:59 -07:00
if peer.timeout == nil {
2016-06-28 18:02:27 -07:00
peer.timeout = time.AfterFunc(time.Second*peerTimeoutSeconds, peer.onTimeout)
} else {
2015-09-12 08:47:59 -07:00
peer.timeout.Reset(time.Second * peerTimeoutSeconds)
}
}
2016-06-28 18:02:27 -07:00
func (peer *bpPeer) incrPending() {
2015-09-12 08:47:59 -07:00
if peer.numPending == 0 {
peer.resetMonitor()
2016-06-28 18:02:27 -07:00
peer.resetTimeout()
}
2015-09-12 08:47:59 -07:00
peer.numPending++
}
2016-06-28 18:02:27 -07:00
func (peer *bpPeer) decrPending(recvSize int) {
2015-09-12 08:47:59 -07:00
peer.numPending--
if peer.numPending == 0 {
peer.timeout.Stop()
} else {
2015-09-12 08:47:59 -07:00
peer.recvMonitor.Update(recvSize)
2016-06-28 18:02:27 -07:00
peer.resetTimeout()
}
}
2015-09-12 08:47:59 -07:00
func (peer *bpPeer) onTimeout() {
2016-06-28 18:02:27 -07:00
peer.pool.mtx.Lock()
defer peer.pool.mtx.Unlock()
2015-09-12 08:47:59 -07:00
peer.pool.sendTimeout(peer.id)
log.Warn("SendTimeout", "peer", peer.id, "reason", "onTimeout")
peer.didTimeout = true
}
2015-03-24 11:02:30 -07:00
//-------------------------------------
type bpRequester struct {
2016-10-28 12:14:24 -07:00
BaseService
pool *BlockPool
height int
gotBlockCh chan struct{}
redoCh chan struct{}
mtx sync.Mutex
peerID string
block *types.Block
}
func newBPRequester(pool *BlockPool, height int) *bpRequester {
bpr := &bpRequester{
pool: pool,
height: height,
gotBlockCh: make(chan struct{}),
redoCh: make(chan struct{}),
peerID: "",
block: nil,
}
2016-10-28 12:14:24 -07:00
bpr.BaseService = *NewBaseService(nil, "bpRequester", bpr)
return bpr
}
func (bpr *bpRequester) OnStart() error {
go bpr.requestRoutine()
return nil
}
// Returns true if the peer matches
func (bpr *bpRequester) setBlock(block *types.Block, peerID string) bool {
bpr.mtx.Lock()
if bpr.block != nil || bpr.peerID != peerID {
bpr.mtx.Unlock()
return false
}
bpr.block = block
bpr.mtx.Unlock()
bpr.gotBlockCh <- struct{}{}
return true
}
2015-09-12 08:47:59 -07:00
func (bpr *bpRequester) getBlock() *types.Block {
bpr.mtx.Lock()
defer bpr.mtx.Unlock()
return bpr.block
}
func (bpr *bpRequester) getPeerID() string {
bpr.mtx.Lock()
defer bpr.mtx.Unlock()
return bpr.peerID
}
func (bpr *bpRequester) reset() {
bpr.mtx.Lock()
bpr.peerID = ""
bpr.block = nil
bpr.mtx.Unlock()
}
// Tells bpRequester to pick another peer and try again.
2015-09-11 08:12:48 -07:00
// NOTE: blocking
func (bpr *bpRequester) redo() {
bpr.redoCh <- struct{}{}
}
2015-03-24 11:02:30 -07:00
// Responsible for making more requests as necessary
// Returns only when a block is found (e.g. AddBlock() is called)
func (bpr *bpRequester) requestRoutine() {
OUTER_LOOP:
2015-03-24 11:02:30 -07:00
for {
// Pick a peer to send request to.
2015-03-24 11:02:30 -07:00
var peer *bpPeer = nil
PICK_PEER_LOOP:
2015-03-24 11:02:30 -07:00
for {
if !bpr.IsRunning() || !bpr.pool.IsRunning() {
2015-03-24 11:02:30 -07:00
return
}
peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
2015-03-24 11:02:30 -07:00
if peer == nil {
2015-07-19 14:49:13 -07:00
//log.Info("No peers available", "height", height)
2015-03-24 11:02:30 -07:00
time.Sleep(requestIntervalMS * time.Millisecond)
continue PICK_PEER_LOOP
2015-03-24 11:02:30 -07:00
}
break PICK_PEER_LOOP
2015-03-24 11:02:30 -07:00
}
bpr.mtx.Lock()
bpr.peerID = peer.id
bpr.mtx.Unlock()
// Send request and wait.
bpr.pool.sendRequest(bpr.height, peer.id)
select {
case <-bpr.pool.Quit:
bpr.Stop()
return
case <-bpr.Quit:
return
case <-bpr.redoCh:
bpr.reset()
continue OUTER_LOOP // When peer is removed
case <-bpr.gotBlockCh:
// We got the block, now see if it's good.
select {
case <-bpr.pool.Quit:
bpr.Stop()
2015-03-24 11:02:30 -07:00
return
case <-bpr.Quit:
2015-03-24 11:02:30 -07:00
return
case <-bpr.redoCh:
bpr.reset()
continue OUTER_LOOP
2015-03-24 11:02:30 -07:00
}
}
}
}
//-------------------------------------
type BlockRequest struct {
Height int
PeerID string
2015-03-22 03:30:22 -07:00
}