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 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 16 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
62 changes: 0 additions & 62 deletions api/admin.go

This file was deleted.

30 changes: 30 additions & 0 deletions api/admin/admin.go
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The admin endpoints were buckled in this package and reformatted to follow the same pattern as other endpoints

Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// 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 admin

import (
"log/slog"
"net/http"

"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/vechain/thor/v2/api/admin/loglevel"
"github.com/vechain/thor/v2/health"

healthAPI "github.com/vechain/thor/v2/api/admin/health"
)

func New(logLevel *slog.LevelVar, health *health.Health) http.HandlerFunc {
router := mux.NewRouter()
subRouter := router.PathPrefix("/admin").Subrouter()

loglevel.New(logLevel).Mount(subRouter, "/loglevel")
healthAPI.New(health).Mount(subRouter, "/health")

handler := handlers.CompressHandler(router)

return handler.ServeHTTP
}
47 changes: 47 additions & 0 deletions api/admin/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()
otherview marked this conversation as resolved.
Show resolved Hide resolved
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))
}
61 changes: 61 additions & 0 deletions api/admin/health/health_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// 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 (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/vechain/thor/v2/comm"
"github.com/vechain/thor/v2/health"
"github.com/vechain/thor/v2/test/testchain"
"github.com/vechain/thor/v2/txpool"
)

var ts *httptest.Server

func TestHealth(t *testing.T) {
initAPIServer(t)

var healthStatus health.Status
respBody, statusCode := httpGet(t, ts.URL+"/health")
require.NoError(t, json.Unmarshal(respBody, &healthStatus))
assert.False(t, healthStatus.Healthy)
assert.Equal(t, http.StatusServiceUnavailable, statusCode)
}

func initAPIServer(t *testing.T) {
thorChain, err := testchain.NewIntegrationTestChain()
require.NoError(t, err)

router := mux.NewRouter()
New(
health.New(thorChain.Repo(), comm.New(thorChain.Repo(), txpool.New(thorChain.Repo(), nil, txpool.Options{})), time.Second),
).Mount(router, "/health")

ts = httptest.NewServer(router)
}

func httpGet(t *testing.T, url string) ([]byte, int) {
res, err := http.Get(url) //#nosec G107
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()

r, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
return r, res.StatusCode
}
10 changes: 10 additions & 0 deletions api/admin/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"`
}
74 changes: 74 additions & 0 deletions api/admin/loglevel/log_level.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// 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 loglevel

import (
"log/slog"
"net/http"

"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/vechain/thor/v2/api/utils"
"github.com/vechain/thor/v2/log"
)

type LogLevel struct {
logLevel *slog.LevelVar
}

func New(logLevel *slog.LevelVar) *LogLevel {
return &LogLevel{
logLevel: logLevel,
}
}

func (l *LogLevel) Mount(root *mux.Router, pathPrefix string) {
sub := root.PathPrefix(pathPrefix).Subrouter()
sub.Path("").
Methods(http.MethodGet).
Name("get-log-level").
HandlerFunc(utils.WrapHandlerFunc(l.getLogLevelHandler))

sub.Path("").
Methods(http.MethodPost).
Name("post-log-level").
HandlerFunc(utils.WrapHandlerFunc(l.postLogLevelHandler))
}

func (l *LogLevel) getLogLevelHandler(w http.ResponseWriter, _ *http.Request) error {
return utils.WriteJSON(w, Response{
CurrentLevel: l.logLevel.Level().String(),
})
}

func (l *LogLevel) postLogLevelHandler(w http.ResponseWriter, r *http.Request) error {
var req Request

if err := utils.ParseJSON(r.Body, &req); err != nil {
return utils.BadRequest(errors.WithMessage(err, "Invalid request body"))
}

switch req.Level {
case "debug":
l.logLevel.Set(log.LevelDebug)
case "info":
l.logLevel.Set(log.LevelInfo)
case "warn":
l.logLevel.Set(log.LevelWarn)
case "error":
l.logLevel.Set(log.LevelError)
case "trace":
l.logLevel.Set(log.LevelTrace)
case "crit":
l.logLevel.Set(log.LevelCrit)
default:
return utils.BadRequest(errors.New("Invalid verbosity level"))
}

return utils.WriteJSON(w, Response{
CurrentLevel: l.logLevel.Level().String(),
})
}
11 changes: 7 additions & 4 deletions api/admin_test.go → api/admin/loglevel/log_level_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// 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 api
package loglevel

import (
"bytes"
Expand All @@ -14,6 +14,8 @@ import (
"strings"
"testing"

"github.com/gorilla/mux"

otherview marked this conversation as resolved.
Show resolved Hide resolved
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -76,15 +78,16 @@ func TestLogLevelHandler(t *testing.T) {
}

rr := httptest.NewRecorder()
handler := http.HandlerFunc(HTTPHandler(&logLevel).ServeHTTP)
handler.ServeHTTP(rr, req)
router := mux.NewRouter()
New(&logLevel).Mount(router, "/admin/loglevel")
router.ServeHTTP(rr, req)

if status := rr.Code; status != tt.expectedStatus {
t.Errorf("handler returned wrong status code: got %v want %v", status, tt.expectedStatus)
}

if tt.expectedLevel != "" {
var response logLevelResponse
var response Response
if err := json.NewDecoder(rr.Body).Decode(&response); err != nil {
t.Fatalf("could not decode response: %v", err)
}
Expand Down
14 changes: 14 additions & 0 deletions api/admin/loglevel/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// 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 loglevel

type Request struct {
Level string `json:"level"`
}

type Response struct {
CurrentLevel string `json:"currentLevel"`
}
29 changes: 5 additions & 24 deletions api/admin_server.go
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Potentially, this can live in the init functions of the thor and thor-solo ?

Original file line number Diff line number Diff line change
Expand Up @@ -11,40 +11,21 @@ import (
"net/http"
"time"

"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/vechain/thor/v2/api/utils"
"github.com/vechain/thor/v2/api/admin"
"github.com/vechain/thor/v2/co"
"github.com/vechain/thor/v2/health"
)

func HTTPHandler(logLevel *slog.LevelVar) http.Handler {
router := mux.NewRouter()
sub := router.PathPrefix("/admin").Subrouter()
sub.Path("/loglevel").
Methods(http.MethodGet).
Name("get-log-level").
HandlerFunc(utils.WrapHandlerFunc(getLogLevelHandler(logLevel)))

sub.Path("/loglevel").
Methods(http.MethodPost).
Name("post-log-level").
HandlerFunc(utils.WrapHandlerFunc(postLogLevelHandler(logLevel)))

return handlers.CompressHandler(router)
}

func StartAdminServer(addr string, logLevel *slog.LevelVar) (string, func(), error) {
func StartAdminServer(addr string, logLevel *slog.LevelVar, health *health.Health) (string, func(), error) {
listener, err := net.Listen("tcp", addr)
if err != nil {
return "", nil, errors.Wrapf(err, "listen admin API addr [%v]", addr)
}

router := mux.NewRouter()
router.PathPrefix("/admin").Handler(HTTPHandler(logLevel))
handler := handlers.CompressHandler(router)
adminHandler := admin.New(logLevel, health)

srv := &http.Server{Handler: handler, ReadHeaderTimeout: time.Second, ReadTimeout: 5 * time.Second}
srv := &http.Server{Handler: adminHandler, ReadHeaderTimeout: time.Second, ReadTimeout: 5 * time.Second}
var goes co.Goes
goes.Go(func() {
srv.Serve(listener)
Expand Down
3 changes: 2 additions & 1 deletion api/node/node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ func initCommServer(t *testing.T) {
Limit: 10000,
LimitPerAccount: 16,
MaxLifetime: 10 * time.Minute,
}))
}),
)

router := mux.NewRouter()
node.New(communicator).Mount(router, "/node")
Expand Down
Loading
Loading