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

Darren/chore/admin req logger #857

Open
wants to merge 2 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
156 changes: 126 additions & 30 deletions api/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,82 @@
package api

import (
"fmt"
"log/slog"
"net"
"net/http"
"sync/atomic"
"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/co"
"github.com/vechain/thor/v2/log"
)

type Admin struct {
address string
logLevel *slog.LevelVar
logRequests *atomic.Bool
}

func NewAdmin(addr string, logLevel *slog.LevelVar, logRequests *atomic.Bool) *Admin {
return &Admin{
address: addr,
logLevel: logLevel,
logRequests: logRequests,
}
}

// Start the admin server.
func (a *Admin) Start() (string, func(), error) {
listener, err := net.Listen("tcp", a.address)
if err != nil {
return "", nil, errors.Wrapf(err, "listen admin API addr [%v]", a.address)
}

router := mux.NewRouter()
handler := handlers.CompressHandler(router)
sub := router.PathPrefix("/admin").Subrouter()

// GET /admin/loglevel
sub.Path("/loglevel").
Methods(http.MethodGet).
Name("get-log-level").
HandlerFunc(utils.WrapHandlerFunc(a.getLogLevelHandler))
// POST /admin/loglevel
sub.Path("/loglevel").
Methods(http.MethodPost).
Name("post-log-level").
HandlerFunc(utils.WrapHandlerFunc(a.postLogLevelHandler))

// GET /admin/apilogs
sub.Path("/apilogs").
Methods(http.MethodGet).
Name("get-api-logs-enabled").
Handler(utils.WrapHandlerFunc(a.getRequestLoggerEnabled))
// POST /admin/apilogs
sub.Path("/apilogs").
Methods(http.MethodPost).
Name("post-api-logs-enabled").
Handler(utils.WrapHandlerFunc(a.postRequestLogger))

server := &http.Server{Handler: handler, ReadHeaderTimeout: time.Second, ReadTimeout: 5 * time.Second}
var goes co.Goes
goes.Go(func() {
server.Serve(listener)
})

cancel := func() {
server.Close()
goes.Wait()
}

return "http://" + listener.Addr().String() + "/admin", cancel, nil
}

type logLevelRequest struct {
Level string `json:"level"`
}
Expand All @@ -22,41 +90,69 @@ type logLevelResponse struct {
CurrentLevel string `json:"currentLevel"`
}

func getLogLevelHandler(logLevel *slog.LevelVar) utils.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
return utils.WriteJSON(w, logLevelResponse{
CurrentLevel: logLevel.Level().String(),
})
func (a *Admin) getLogLevelHandler(w http.ResponseWriter, r *http.Request) error {
return utils.WriteJSON(w, logLevelResponse{
CurrentLevel: a.logLevel.Level().String(),
})
}

func (a *Admin) postLogLevelHandler(w http.ResponseWriter, r *http.Request) error {
var req logLevelRequest

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

switch req.Level {
case "debug":
a.logLevel.Set(log.LevelDebug)
case "info":
a.logLevel.Set(log.LevelInfo)
case "warn":
a.logLevel.Set(log.LevelWarn)
case "error":
a.logLevel.Set(log.LevelError)
case "trace":
a.logLevel.Set(log.LevelTrace)
case "crit":
a.logLevel.Set(log.LevelCrit)
default:
return utils.BadRequest(fmt.Errorf("invalid verbosity level: %s", req.Level))
}

log.Warn("admin changed the log level", "level", log.LevelString(a.logLevel.Level()))

return utils.WriteJSON(w, logLevelResponse{
CurrentLevel: a.logLevel.Level().String(),
})
}

func postLogLevelHandler(logLevel *slog.LevelVar) utils.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
var req logLevelRequest
type apiLogRequests struct {
Enabled *bool `json:"enabled"`
}

if err := utils.ParseJSON(r.Body, &req); err != nil {
return utils.BadRequest(errors.WithMessage(err, "Invalid request body"))
}
func (a *Admin) getRequestLoggerEnabled(w http.ResponseWriter, r *http.Request) error {
enabled := a.logRequests.Load()
res := apiLogRequests{
Enabled: &enabled,
}
return utils.WriteJSON(w, res)
}

switch req.Level {
case "debug":
logLevel.Set(log.LevelDebug)
case "info":
logLevel.Set(log.LevelInfo)
case "warn":
logLevel.Set(log.LevelWarn)
case "error":
logLevel.Set(log.LevelError)
case "trace":
logLevel.Set(log.LevelTrace)
case "crit":
logLevel.Set(log.LevelCrit)
default:
return utils.BadRequest(errors.New("Invalid verbosity level"))
}
func (a *Admin) postRequestLogger(w http.ResponseWriter, r *http.Request) error {
var req apiLogRequests

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

return utils.WriteJSON(w, logLevelResponse{
CurrentLevel: logLevel.Level().String(),
})
if req.Enabled == nil {
return utils.BadRequest(errors.New("missing 'enabled' field"))
}

log.Warn("admin changed the request logger", "enabled", *req.Enabled)

a.logRequests.Store(*req.Enabled)

return utils.WriteJSON(w, req)
}
56 changes: 0 additions & 56 deletions api/admin_server.go

This file was deleted.

Loading
Loading