Skip to content
Closed
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
52 changes: 50 additions & 2 deletions apps/manager-server/internal/http/controller/health/handler.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,67 @@
package health

import (
"net"
"net/http"
"strings"

"github.com/seakee/cpa-manager-plus/apps/manager-server/internal/app"
"github.com/seakee/cpa-manager-plus/apps/manager-server/internal/http/response"
)

type Handler struct {
ServiceID string
App *app.Context
}

func (h *Handler) Health(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
response.MethodNotAllowed(w)
return
}
response.JSON(w, http.StatusOK, map[string]any{"ok": true, "service": h.ServiceID})
response.JSON(w, http.StatusOK, map[string]any{"ok": true, "service": h.App.ServiceID})
}

func (h *Handler) Ready(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
response.MethodNotAllowed(w)
return
}
if !isLoopbackRequest(r) {
response.Error(w, http.StatusForbidden, http.ErrNotSupported)
return
}

events, _, err := h.App.UsageService.Counts(r.Context())
if err != nil {
response.Error(w, http.StatusServiceUnavailable, err)
return
}
status := h.App.CollectorService.Status()
lastError := strings.TrimSpace(status.LastError)
ready := status.Collector == "running" && lastError == ""
httpStatus := http.StatusOK
if !ready {
httpStatus = http.StatusServiceUnavailable
}

response.JSON(w, httpStatus, map[string]any{
"ok": ready,
"service": h.App.ServiceID,
"collector": status.Collector,
"events": events,
"lastConsumedAt": status.LastConsumedAt,
"lastInsertedAt": status.LastInsertedAt,
"totalInserted": status.TotalInserted,
"totalSkipped": status.TotalSkipped,
"lastErrorPresent": lastError != "",
})
}

func isLoopbackRequest(r *http.Request) bool {
host, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
if err != nil {
host = strings.Trim(strings.TrimSpace(r.RemoteAddr), "[]")
}
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package health_test

import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/seakee/cpa-manager-plus/apps/manager-server/internal/app"
"github.com/seakee/cpa-manager-plus/apps/manager-server/internal/collector"
healthcontroller "github.com/seakee/cpa-manager-plus/apps/manager-server/internal/http/controller/health"
"github.com/seakee/cpa-manager-plus/apps/manager-server/internal/testutil"
)

func TestReadyReportsCollectorAndStorageState(t *testing.T) {
cfg := testutil.NewConfig(t)
store := testutil.NewStore(t, cfg)
cpa := testutil.NewCPAMock(t)
manager := collector.NewManager(cfg, store)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
manager.Start(ctx, collector.RuntimeConfig{
CPAUpstreamURL: cpa.URL(),
ManagementKey: cpa.ManagementKey,
CollectorMode: "http",
Queue: cfg.Queue,
PopSide: cfg.PopSide,
BatchSize: cfg.BatchSize,
PollInterval: 10 * time.Millisecond,
})

deadline := time.Now().Add(2 * time.Second)
for manager.Status().Collector != "running" && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if status := manager.Status(); status.Collector != "running" {
t.Fatalf("collector status = %q, want running; last error = %q", status.Collector, status.LastError)
}

appCtx := app.FromExisting(cfg, store, manager, time.Now().UnixMilli(), nil, nil, nil, "test-service")
handler := &healthcontroller.Handler{App: appCtx}
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/health/ready", nil)
request.RemoteAddr = "127.0.0.1:12345"
handler.Ready(recorder, request)

if recorder.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", recorder.Code, recorder.Body.String())
}
var body map[string]any
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
t.Fatalf("decode response: %v", err)
}
if body["ok"] != true || body["collector"] != "running" {
t.Fatalf("response = %#v", body)
}
if body["events"] != float64(0) || body["totalInserted"] != float64(0) {
t.Fatalf("unexpected counters: %#v", body)
}
if _, exists := body["dbPath"]; exists {
t.Fatal("readiness response must not expose the database path")
}
if _, exists := body["lastError"]; exists {
t.Fatal("readiness response must not expose collector error details")
}
}

func TestReadyRejectsNonLoopbackRequests(t *testing.T) {
handler := &healthcontroller.Handler{}
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/health/ready", nil)
request.RemoteAddr = "203.0.113.10:12345"

handler.Ready(recorder, request)

if recorder.Code != http.StatusForbidden {
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusForbidden)
}
}
3 changes: 2 additions & 1 deletion apps/manager-server/internal/http/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import (
)

func New(appCtx *app.Context) http.Handler {
healthHandler := &healthcontroller.Handler{ServiceID: appCtx.ServiceID}
healthHandler := &healthcontroller.Handler{App: appCtx}
systemHandler := &systemcontroller.Handler{App: appCtx}
setupHandler := &setupcontroller.Handler{App: appCtx}
managerConfigHandler := &managerconfigcontroller.Handler{App: appCtx}
Expand All @@ -43,6 +43,7 @@ func New(appCtx *app.Context) http.Handler {

mux := http.NewServeMux()
mux.HandleFunc("/health", middleware.WithCORS(appCtx.Config, healthHandler.Health))
mux.HandleFunc("/health/ready", middleware.WithCORS(appCtx.Config, healthHandler.Ready))
mux.HandleFunc("/status", middleware.WithCORS(appCtx.Config, systemHandler.Status))
mux.HandleFunc("/usage-service/info", middleware.WithCORS(appCtx.Config, systemHandler.Info))
mux.HandleFunc("/usage-service/config", middleware.WithCORS(appCtx.Config, managerConfigHandler.Handle))
Expand Down
4 changes: 4 additions & 0 deletions bin/native/cpa-launcher.cmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
@echo off
setlocal
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0cpa-launcher.ps1" %*
exit /b %ERRORLEVEL%
Loading