Skip to content
Merged
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
2 changes: 1 addition & 1 deletion cdb/db_heartbeat.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (oDb *DB) HBUpdate(ctx context.Context, hb DBHeartbeat) error {
defer logDuration("HBUpdate cluster id:"+hb.ClusterID+" "+hb.Driver, time.Now())
const (
qUpdate = "" +
"INSERT INTO `hbmon` (`cluster_id`, `node_id`, `peer_node_id`, `driver`, `name`, `desc`, `stat e`, `beating`, `last_beating`, `updated`)" +
"INSERT INTO `hbmon` (`cluster_id`, `node_id`, `peer_node_id`, `driver`, `name`, `desc`, `state`, `beating`, `last_beating`, `updated`)" +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())" +
"ON DUPLICATE KEY UPDATE" +
" `cluster_id` = VALUES(`cluster_id`), `driver` = VALUES(`driver`), `desc` = VALUES(`desc`), `state` = VALUES(`state`), `beating`= VALUES(`beating`), `last_beating`= VALUES(`last_beating`), `updated`= VALUES(`updated`)"
Expand Down
59 changes: 30 additions & 29 deletions cmd/feeder.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,54 +14,57 @@ import (
"github.com/spf13/viper"

"github.com/opensvc/oc3/feeder"
feederhandlers "github.com/opensvc/oc3/feeder/handlers"
"github.com/opensvc/oc3/feeder/handlers"
"github.com/opensvc/oc3/xauth"
)

const (
pathApi = "/api"
pathSpec = "openapi.json"
pathPprof = "pprof"
pathMetric = "metrics"
pathVersion = "version"
pathDoc = "docs"
)

func startFeeder() error {
addr := viper.GetString("feeder.addr")
return listenAndServeFeeder(addr)
}

func listenAndServeFeeder(addr string) error {
const (
pathApi = "/api"
pathSpec = "openapi.json"
pathPprof = "/pprof"
pathMetric = "/metrics"
)

db, err := newDatabase()
if err != nil {
return err
}

fromPath := func(p string) string { return fmt.Sprintf("%s/%s", pathApi, p) }
endingSlash := func(s string) string { return strings.TrimSuffix(s, "/") + "/" }
relPath := func(s string) string { return "./" + strings.TrimPrefix(s, "/") }

// get enabled features
enableUI := viper.GetBool("feeder.ui.enable")
enableMetrics := viper.GetBool("feeder.metrics.enable")
enablePprof := viper.GetBool("feeder.pprof.enable")

// define public paths
publics := []string{fromPath(pathVersion)}
publicPath := []string{pathApi + "/version"}
publicPrefix := []string{}
if enableUI {
publics = append(publics, fromPath(pathDoc), fromPath(pathSpec))
publicPath = append(publicPath, pathApi)
for _, p := range []string{"", pathSpec, "swagger-ui.css", "swagger-ui-bundle.js", "swagger-ui-standalone-preset.js"} {
publicPath = append(publicPath, pathApi+"/"+p)
}
}
if enableMetrics {
publics = append(publics, fromPath(pathMetric))
publicPath = append(publicPath, pathMetric)
}
if enablePprof {
publics = append(publics, fromPath(pathPprof))
publicPrefix = append(publicPrefix, pathPprof)
}
slog.Info(fmt.Sprintf("public paths: %s", strings.Join(publics, ", ")))
slog.Info(fmt.Sprintf("public paths: %s", strings.Join(publicPath, ", ")))
slog.Info(fmt.Sprintf("public path prefixes: %s", strings.Join(publicPrefix, ", ")))

// define auth middleware
authMiddleware := feederhandlers.AuthMiddleware(union.New(
xauth.NewPublicStrategy(publics...),
xauth.NewPublicStrategy(publicPath, publicPrefix),
xauth.NewBasicNode(db),
))

Expand All @@ -81,28 +84,26 @@ func listenAndServeFeeder(addr string) error {

if enablePprof {
// TODO: move to authenticated path
s := fromPath(pathPprof)
slog.Info(fmt.Sprintf("add handler for profiling: %s", s))
pprof.Register(e, s)
e.GET(s, func(c echo.Context) error {
return c.Redirect(http.StatusMovedPermanently, endingSlash(pathPprof))
slog.Info(fmt.Sprintf("add handler for profiling: %s", pathPprof))
pprof.Register(e, pathPprof)
e.GET(pathPprof, func(c echo.Context) error {
return c.Redirect(http.StatusMovedPermanently, endingSlash(relPath(pathPprof)))
})
}

if enableMetrics {
// TODO: move to authenticated path
slog.Info(fmt.Sprintf("add handler for metrics: %s", pathMetric))
e.Use(echoprometheus.NewMiddleware("oc3_feeder"))
e.GET(fromPath(pathMetric), echoprometheus.NewHandler())
e.GET(pathMetric, echoprometheus.NewHandler())
}

if enableUI {
s := fromPath(pathDoc)
slog.Info(fmt.Sprintf("add handler for documentation ui: %s", s))
g := e.Group(s)
g.Use(feederhandlers.UIMiddleware(context.Background(), s, "../"+pathSpec))
e.GET(s, func(c echo.Context) error {
return c.Redirect(http.StatusMovedPermanently, endingSlash(pathDoc))
slog.Info(fmt.Sprintf("add handler for documentation ui: %s", pathApi))
g := e.Group(pathApi)
g.Use(feederhandlers.UIMiddleware(context.Background(), pathApi, pathSpec))
e.GET(pathApi, func(c echo.Context) error {
return c.Redirect(http.StatusMovedPermanently, endingSlash(relPath(pathApi)))
})
}

Expand Down
95 changes: 68 additions & 27 deletions cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ package cmd

import (
"context"
"fmt"
"log/slog"
"net/http"
"strings"

"github.com/labstack/echo-contrib/echoprometheus"
"github.com/labstack/echo-contrib/pprof"
Expand All @@ -11,7 +14,7 @@ import (
"github.com/spf13/viper"

"github.com/opensvc/oc3/server"
serverhandlers "github.com/opensvc/oc3/server/handlers"
"github.com/opensvc/oc3/server/handlers"
"github.com/opensvc/oc3/xauth"
)

Expand All @@ -21,50 +24,88 @@ func startServer() error {
}

func listenAndServeServer(addr string) error {
enableUI := viper.GetBool("server.ui.enable")
const (
pathApi = "/api"
pathSpec = "openapi.json"
pathPprof = "/pprof"
pathMetric = "/metrics"
)

db, err := newDatabase()
if err != nil {
return err
}

redisClient := newRedis()
endingSlash := func(s string) string { return strings.TrimSuffix(s, "/") + "/" }
relPath := func(s string) string { return "./" + strings.TrimPrefix(s, "/") }

// get enabled features
enableUI := viper.GetBool("server.ui.enable")
enableMetrics := viper.GetBool("server.metrics.enable")
enablePprof := viper.GetBool("server.pprof.enable")
// define public paths
publicPath := []string{pathApi + "/version"}
publicPrefix := []string{}
if enableUI {
publicPath = append(publicPath, pathApi)
for _, p := range []string{"", pathSpec, "swagger-ui.css", "swagger-ui-bundle.js", "swagger-ui-standalone-preset.js"} {
publicPath = append(publicPath, pathApi+"/"+p)
}
}
if enableMetrics {
publicPath = append(publicPath, pathMetric)
}
if enablePprof {
publicPrefix = append(publicPrefix, pathPprof)
}
slog.Info(fmt.Sprintf("public paths: %s", strings.Join(publicPath, ", ")))
slog.Info(fmt.Sprintf("public path prefixes: %s", strings.Join(publicPrefix, ", ")))

// define auth middleware
authMiddleware := serverhandlers.AuthMiddleware(union.New(
xauth.NewPublicStrategy(publicPath, publicPrefix),
xauth.NewBasicNode(db),
))

e := echo.New()
e.HideBanner = true
e.HidePort = true

if viper.GetBool("server.pprof.enable") {
slog.Info("add handler /oc3/api/public/pprof")
pprof.Register(e, "/oc3/api/public/pprof")
}
e.Use(authMiddleware)

strategy := union.New(
xauth.NewPublicStrategy("/oc3/api/public/", "/oc3/api/docs", "/oc3/api/version", "/oc3/api/openapi"),
xauth.NewBasicNode(db),
)
if viper.GetBool("server.metrics.enable") {
slog.Info("add handler /oc3/api/public/metrics")
e.Use(echoprometheus.NewMiddleware("oc3_api"))
e.GET("/oc3/api/public/metrics", echoprometheus.NewHandler())
}
e.Use(serverhandlers.AuthMiddleware(strategy))
slog.Info("register openapi handlers with base url: /oc3/api")
slog.Info(fmt.Sprintf("add handler for openapi: %s", pathApi))
server.RegisterHandlersWithBaseURL(e, &serverhandlers.Api{
DB: db,
Redis: redisClient,
Redis: newRedis(),
UI: enableUI,
SyncTimeout: viper.GetDuration("server.sync.timeout"),
}, "/oc3/api")
}, pathApi)

if enablePprof {
// TODO: move to authenticated path
slog.Info(fmt.Sprintf("add handler for profiling: %s", pathPprof))
pprof.Register(e, pathPprof)
e.GET(pathPprof, func(c echo.Context) error {
return c.Redirect(http.StatusMovedPermanently, endingSlash(relPath(pathPprof)))
})
}

if enableMetrics {
// TODO: move to authenticated path
slog.Info(fmt.Sprintf("add handler for metrics: %s", pathMetric))
e.Use(echoprometheus.NewMiddleware("oc3_feeder"))
e.GET(pathMetric, echoprometheus.NewHandler())
}

if enableUI {
registerServerUI(e)
slog.Info(fmt.Sprintf("add handler for documentation ui: %s", pathApi))
g := e.Group(pathApi)
g.Use(serverhandlers.UIMiddleware(context.Background(), pathApi, pathSpec))
e.GET(pathApi, func(c echo.Context) error {
return c.Redirect(http.StatusMovedPermanently, endingSlash(relPath(pathApi)))
})
}

slog.Info("listen on " + addr)
return e.Start(addr)
}

func registerServerUI(e *echo.Echo) {
slog.Info("add handler /oc3/api/docs/")
g := e.Group("/oc3/api/docs")
g.Use(serverhandlers.UIMiddleware(context.Background()))
}
2 changes: 1 addition & 1 deletion feeder/api.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
openapi: 3.0.0

servers:
- url: /api
- url: ./

info:
title: opensvc feeder api
Expand Down
68 changes: 34 additions & 34 deletions feeder/codegen_server_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions feeder/handlers/middleware-ui.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,12 @@ import (

"github.com/allenai/go-swaggerui"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)

func UIMiddleware(_ context.Context, prefix, specUrl string) echo.MiddlewareFunc {
uiHandler := http.StripPrefix(prefix, swaggerui.Handler(specUrl))
echoUI := echo.WrapHandler(uiHandler)

middleware.WWWRedirect()

return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
return echoUI(c)
Expand Down
4 changes: 3 additions & 1 deletion feeder/handlers/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@ const (
XNodename = "XNodename"
)

// AuthMiddleware returns auth middleware that authenticate requests from strategies.
// AuthMiddleware returns auth middleware that authenticates requests from strategies.
func AuthMiddleware(strategies union.Union) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
_, user, err := strategies.AuthenticateRequest(c.Request())
if err != nil {
code := http.StatusUnauthorized
return JSONProblem(c, code, http.StatusText(code), err.Error())
} else if user == nil {
return next(c)
}
ext := user.GetExtensions()
if nodeID := ext.Get(xauth.XNodeID); nodeID != "" {
Expand Down
4 changes: 2 additions & 2 deletions server/api.yaml
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
openapi: 3.0.0

servers:
- url: /oc3/api
- url: ./

info:
title: opensvc collector api
version: 1.0.0

paths:
/docs/openapi:
/openapi.json:
get:
operationId: GetSwagger
tags:
Expand Down
Loading
Loading