Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding Health endpoint #836

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/vechain/thor/v2/api/debug"
"github.com/vechain/thor/v2/api/doc"
"github.com/vechain/thor/v2/api/events"
"github.com/vechain/thor/v2/api/health"
"github.com/vechain/thor/v2/api/node"
"github.com/vechain/thor/v2/api/subscriptions"
"github.com/vechain/thor/v2/api/transactions"
Expand All @@ -28,6 +29,8 @@ import (
"github.com/vechain/thor/v2/state"
"github.com/vechain/thor/v2/thor"
"github.com/vechain/thor/v2/txpool"

healthstatus "github.com/vechain/thor/v2/health"
)

var logger = log.WithContext("pkg", "api")
Expand All @@ -40,6 +43,7 @@ func New(
logDB *logdb.LogDB,
bft bft.Committer,
nw node.Network,
healthStatus *healthstatus.Health,
forkConfig thor.ForkConfig,
allowedOrigins string,
backtraceLimit uint32,
Expand Down Expand Up @@ -74,6 +78,8 @@ func New(
accounts.New(repo, stater, callGasLimit, forkConfig, bft).
Mount(router, "/accounts")

health.New(healthStatus).Mount(router, "/health")

if !skipLogs {
events.New(repo, logDB, logsLimit).
Mount(router, "/logs/event")
Expand Down
47 changes: 47 additions & 0 deletions api/health/health.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright (c) 2024 The VeChainThor developers

// Distributed under the GNU Lesser General Public License v3.0 software license, see the accompanying
// file LICENSE or <https://www.gnu.org/licenses/lgpl-3.0.html>

package health

import (
"net/http"

"github.com/gorilla/mux"
"github.com/vechain/thor/v2/api/utils"
"github.com/vechain/thor/v2/health"
)

type Health struct {
healthStatus *health.Health
}

func New(healthStatus *health.Health) *Health {
return &Health{
healthStatus: healthStatus,
}
}

func (h *Health) handleGetHealth(w http.ResponseWriter, _ *http.Request) error {
acc, err := h.healthStatus.Status()
if err != nil {
return err
}

if !acc.Healthy {
w.WriteHeader(http.StatusServiceUnavailable) // Set the status to 503
} else {
w.WriteHeader(http.StatusOK) // Set the status to 200
}
return utils.WriteJSON(w, acc)
}

func (h *Health) Mount(root *mux.Router, pathPrefix string) {
sub := root.PathPrefix(pathPrefix).Subrouter()

sub.Path("/").
Methods(http.MethodGet).
Name("health").
HandlerFunc(utils.WrapHandlerFunc(h.handleGetHealth))
}
10 changes: 10 additions & 0 deletions api/health/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Copyright (c) 2024 The VeChainThor developers

// Distributed under the GNU Lesser General Public License v3.0 software license, see the accompanying
// file LICENSE or <https://www.gnu.org/licenses/lgpl-3.0.html>

package health

type Response struct {
Healthy bool `json:"healthy"`
}
3 changes: 2 additions & 1 deletion api/node/node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/vechain/thor/v2/chain"
"github.com/vechain/thor/v2/comm"
"github.com/vechain/thor/v2/genesis"
"github.com/vechain/thor/v2/health"
"github.com/vechain/thor/v2/muxdb"
"github.com/vechain/thor/v2/state"
"github.com/vechain/thor/v2/thorclient"
Expand Down Expand Up @@ -49,7 +50,7 @@ func initCommServer(t *testing.T) {
Limit: 10000,
LimitPerAccount: 16,
MaxLifetime: 10 * time.Minute,
}))
}), &health.Health{})
router := mux.NewRouter()
node.New(comm).Mount(router, "/node")
ts = httptest.NewServer(router)
Expand Down
13 changes: 11 additions & 2 deletions cmd/thor/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"github.com/vechain/thor/v2/cmd/thor/optimizer"
"github.com/vechain/thor/v2/cmd/thor/solo"
"github.com/vechain/thor/v2/genesis"
"github.com/vechain/thor/v2/health"
"github.com/vechain/thor/v2/log"
"github.com/vechain/thor/v2/logdb"
"github.com/vechain/thor/v2/metrics"
Expand Down Expand Up @@ -220,6 +221,7 @@ func defaultAction(ctx *cli.Context) error {
return err
}

healthStatus := &health.Health{}
printStartupMessage1(gene, repo, master, instanceDir, forkConfig)

skipLogs := ctx.Bool(skipLogsFlag.Name)
Expand All @@ -237,7 +239,7 @@ func defaultAction(ctx *cli.Context) error {
txPool := txpool.New(repo, state.NewStater(mainDB), txpoolOpt)
defer func() { log.Info("closing tx pool..."); txPool.Close() }()

p2pCommunicator, err := newP2PCommunicator(ctx, repo, txPool, instanceDir)
p2pCommunicator, err := newP2PCommunicator(ctx, repo, txPool, instanceDir, healthStatus)
if err != nil {
return err
}
Expand All @@ -254,6 +256,7 @@ func defaultAction(ctx *cli.Context) error {
logDB,
bftEngine,
p2pCommunicator.Communicator(),
healthStatus,
forkConfig,
ctx.String(apiCorsFlag.Name),
uint32(ctx.Uint64(apiBacktraceLimitFlag.Name)),
Expand Down Expand Up @@ -296,7 +299,9 @@ func defaultAction(ctx *cli.Context) error {
p2pCommunicator.Communicator(),
ctx.Uint64(targetGasLimitFlag.Name),
skipLogs,
forkConfig).Run(exitSignal)
forkConfig,
healthStatus,
).Run(exitSignal)
}

func soloAction(ctx *cli.Context) error {
Expand Down Expand Up @@ -399,13 +404,16 @@ func soloAction(ctx *cli.Context) error {
defer func() { log.Info("closing tx pool..."); txPool.Close() }()

bftEngine := solo.NewBFTEngine(repo)
healthStatus := &health.Health{}

apiHandler, apiCloser := api.New(
repo,
state.NewStater(mainDB),
txPool,
logDB,
bftEngine,
&solo.Communicator{},
healthStatus,
forkConfig,
ctx.String(apiCorsFlag.Name),
uint32(ctx.Uint64(apiBacktraceLimitFlag.Name)),
Expand Down Expand Up @@ -443,6 +451,7 @@ func soloAction(ctx *cli.Context) error {
return solo.New(repo,
state.NewStater(mainDB),
logDB,
healthStatus,
txPool,
ctx.Uint64(gasLimitFlag.Name),
ctx.Bool(onDemandFlag.Name),
Expand Down
6 changes: 6 additions & 0 deletions cmd/thor/node/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"github.com/vechain/thor/v2/co"
"github.com/vechain/thor/v2/comm"
"github.com/vechain/thor/v2/consensus"
"github.com/vechain/thor/v2/health"
"github.com/vechain/thor/v2/log"
"github.com/vechain/thor/v2/logdb"
"github.com/vechain/thor/v2/packer"
Expand Down Expand Up @@ -64,6 +65,8 @@ type Node struct {
maxBlockNum uint32
processLock sync.Mutex
logWorker *worker

health *health.Health
}

func New(
Expand All @@ -78,6 +81,7 @@ func New(
targetGasLimit uint64,
skipLogs bool,
forkConfig thor.ForkConfig,
health *health.Health,
) *Node {
return &Node{
packer: packer.New(repo, stater, master.Address(), master.Beneficiary, forkConfig),
Expand All @@ -92,6 +96,7 @@ func New(
targetGasLimit: targetGasLimit,
skipLogs: skipLogs,
forkConfig: forkConfig,
health: health,
}
}

Expand Down Expand Up @@ -387,6 +392,7 @@ func (n *Node) processBlock(newBlock *block.Block, stats *blockStats) (bool, err
return err
}
n.processFork(newBlock, oldBest.Header.ID())
n.health.NewBestBlock(newBlock.Header().ID())
}

commitElapsed := mclock.Now() - startTime - execElapsed
Expand Down
6 changes: 6 additions & 0 deletions cmd/thor/solo/solo.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/vechain/thor/v2/cmd/thor/bandwidth"
"github.com/vechain/thor/v2/co"
"github.com/vechain/thor/v2/genesis"
"github.com/vechain/thor/v2/health"
"github.com/vechain/thor/v2/log"
"github.com/vechain/thor/v2/logdb"
"github.com/vechain/thor/v2/packer"
Expand All @@ -43,6 +44,7 @@ type Solo struct {
txPool *txpool.TxPool
packer *packer.Packer
logDB *logdb.LogDB
health *health.Health
gasLimit uint64
bandwidth bandwidth.Bandwidth
blockInterval uint64
Expand All @@ -55,6 +57,7 @@ func New(
repo *chain.Repository,
stater *state.Stater,
logDB *logdb.LogDB,
health *health.Health,
txPool *txpool.TxPool,
gasLimit uint64,
onDemand bool,
Expand All @@ -73,6 +76,7 @@ func New(
&genesis.DevAccounts()[0].Address,
forkConfig),
logDB: logDB,
health: health,
gasLimit: gasLimit,
blockInterval: blockInterval,
skipLogs: skipLogs,
Expand Down Expand Up @@ -210,6 +214,8 @@ func (s *Solo) packing(pendingTxs tx.Transactions, onDemand bool) error {
)
logger.Debug(b.String())

s.health.NewBestBlock(b.Header().ID())

return nil
}

Expand Down
3 changes: 2 additions & 1 deletion cmd/thor/solo/solo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/vechain/thor/v2/builtin"
"github.com/vechain/thor/v2/chain"
"github.com/vechain/thor/v2/genesis"
"github.com/vechain/thor/v2/health"
"github.com/vechain/thor/v2/logdb"
"github.com/vechain/thor/v2/muxdb"
"github.com/vechain/thor/v2/state"
Expand All @@ -30,7 +31,7 @@ func newSolo() *Solo {
repo, _ := chain.NewRepository(db, b)
mempool := txpool.New(repo, stater, txpool.Options{Limit: 10000, LimitPerAccount: 16, MaxLifetime: 10 * time.Minute})

return New(repo, stater, logDb, mempool, 0, true, false, thor.BlockInterval, thor.ForkConfig{})
return New(repo, stater, logDb, &health.Health{}, mempool, 0, true, false, thor.BlockInterval, thor.ForkConfig{})
}

func TestInitSolo(t *testing.T) {
Expand Down
5 changes: 3 additions & 2 deletions cmd/thor/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import (
"github.com/vechain/thor/v2/co"
"github.com/vechain/thor/v2/comm"
"github.com/vechain/thor/v2/genesis"
"github.com/vechain/thor/v2/health"
"github.com/vechain/thor/v2/log"
"github.com/vechain/thor/v2/logdb"
"github.com/vechain/thor/v2/muxdb"
Expand Down Expand Up @@ -489,7 +490,7 @@ func loadNodeMaster(ctx *cli.Context) (*node.Master, error) {
return master, nil
}

func newP2PCommunicator(ctx *cli.Context, repo *chain.Repository, txPool *txpool.TxPool, instanceDir string) (*p2p.P2P, error) {
func newP2PCommunicator(ctx *cli.Context, repo *chain.Repository, txPool *txpool.TxPool, instanceDir string, health *health.Health) (*p2p.P2P, error) {
// known peers will be loaded/stored from/in this file
peersCachePath := filepath.Join(instanceDir, "peers.cache")

Expand Down Expand Up @@ -529,7 +530,7 @@ func newP2PCommunicator(ctx *cli.Context, repo *chain.Repository, txPool *txpool
}

return p2p.New(
comm.New(repo, txPool),
comm.New(repo, txPool, health),
key,
instanceDir,
userNAT,
Expand Down
7 changes: 6 additions & 1 deletion comm/communicator.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/vechain/thor/v2/chain"
"github.com/vechain/thor/v2/co"
"github.com/vechain/thor/v2/comm/proto"
"github.com/vechain/thor/v2/health"
"github.com/vechain/thor/v2/log"
"github.com/vechain/thor/v2/thor"
"github.com/vechain/thor/v2/tx"
Expand All @@ -39,19 +40,21 @@ type Communicator struct {
newBlockFeed event.Feed
announcementCh chan *announcement
feedScope event.SubscriptionScope
health *health.Health
goes co.Goes
onceSynced sync.Once
}

// New create a new Communicator instance.
func New(repo *chain.Repository, txPool *txpool.TxPool) *Communicator {
func New(repo *chain.Repository, txPool *txpool.TxPool, health *health.Health) *Communicator {
ctx, cancel := context.WithCancel(context.Background())
return &Communicator{
repo: repo,
txPool: txPool,
ctx: ctx,
cancel: cancel,
peerSet: newPeerSet(),
health: health,
syncedCh: make(chan struct{}),
announcementCh: make(chan *announcement),
}
Expand Down Expand Up @@ -116,8 +119,10 @@ func (c *Communicator) Sync(ctx context.Context, handler HandleBlockStream) {
syncCount++

if shouldSynced() {
c.health.ChainSyncStatus(false)
delay = syncInterval
c.onceSynced.Do(func() {
c.health.ChainSyncStatus(true)
close(c.syncedCh)
})
}
Expand Down
Loading
Loading