Pulse/internal/api/kubernetes_agents.go
rcourtman 6340cd36f2 Dedupe internal/api handler families behind shared flows and generics
Clears the sixteen dupl pair groups in internal/api plus the pkg/pulsecli
pair:

- router.go: privileged settings endpoints share the
  serveSetupTokenOrSettingsWrite gate; patrol findings convert via one
  unifiedFindingFromAI; the five infrastructure-summary chart loops share
  collectGuestChartData / fillChartSeriesFromBatch; the VM/LXC workloads
  summary loops share appendGuestWorkloadSummaries.
- deploy_handlers.go: preflight and job status/SSE handlers share
  handleDeployJobStatus / handleDeployJobEvents.
- recovery_handlers.go: points series/facets share
  parseRecoveryListPointsOptions.
- truenas_handlers.go / vmware_handlers.go / router_routes_registration.go:
  the connection update flow (locate, decode-with-fallback, normalize,
  preserve masked secrets, validate, save, redact) moves to the new
  platform_connection_shared.go (updatePlatformConnection +
  decodeOptionalInstanceRequest + the admin-gated item-route builder);
  per-platform wrappers carry nolint'd declarative wiring only.
- docker_metadata.go / guest_metadata.go: GET/PUT payload semantics move
  to metadata_handlers_shared.go; the zero-record-instead-of-404 contract
  is pinned by TestContract_MetadataGetPayloadsUseZeroRecordsInsteadOf404.
- kubernetes_agents.go / docker_agents.go: lifecycle PUTs share
  per-handler action helpers.
- config_node_handlers.go: PBS/PMG probes share
  testProxmoxPlatformConnection.
- cloud_handoff_handlers.go / purchase_return_redemptions.go: secrets
  sqlite stores open through openHardenedSecretsDB so permission
  hardening stays single-sourced.
- ai_handlers.go / chat_service_adapter.go: the GetMessages adapters are
  deliberate contract mirrors — suppressed with nolint and enforced by
  TestOrchestratorAndChatAdaptersMapTheSameMessageFields.
- pkg/pulsecli/actions.go: action subcommands seed env defaults via
  actionAPIDefaults (tested); the audit/events cobra registration pair is
  nolint'd parallel wiring.
- .golangci.yml: exclude gitignored tmp/ from ./... typechecking.
- subsystem_lookup_test.py: refresh the pinned api-contracts.md line
  numbers shifted by the contract additions.

golangci-lint run ./... is now fully green. Full internal/api and
pkg/pulsecli test suites pass.
2026-06-10 10:52:05 +01:00

306 lines
11 KiB
Go

package api
import (
"context"
"encoding/json"
"net/http"
"strings"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
"github.com/rcourtman/pulse-go-rewrite/internal/utils"
"github.com/rcourtman/pulse-go-rewrite/internal/websocket"
agentsk8s "github.com/rcourtman/pulse-go-rewrite/pkg/agents/kubernetes"
"github.com/rs/zerolog/log"
)
// KubernetesAgentHandlers manages ingest from the Kubernetes agent.
type KubernetesAgentHandlers struct {
baseAgentHandlers
recoveryIngestor interface {
IngestKubernetesReport(ctx context.Context, orgID string, report agentsk8s.Report) error
}
}
// NewKubernetesAgentHandlers constructs a new Kubernetes agent handler group.
func NewKubernetesAgentHandlers(mtm *monitoring.MultiTenantMonitor, m *monitoring.Monitor, hub *websocket.Hub) *KubernetesAgentHandlers {
return &KubernetesAgentHandlers{baseAgentHandlers: newBaseAgentHandlers(mtm, m, hub)}
}
func (h *KubernetesAgentHandlers) SetRecoveryIngestor(ingestor interface {
IngestKubernetesReport(ctx context.Context, orgID string, report agentsk8s.Report) error
}) {
h.recoveryIngestor = ingestor
}
// HandleReport accepts heartbeat payloads from the Kubernetes agent.
func (h *KubernetesAgentHandlers) HandleReport(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only POST is allowed", nil)
return
}
// Limit request body to 2MB to prevent memory exhaustion (pods can be sizable).
r.Body = http.MaxBytesReader(w, r.Body, 2*1024*1024)
defer r.Body.Close()
// Support gzip-compressed reports from agents (backward compatible with uncompressed)
body, err := utils.DecompressBodyIfGzipped(r, 10*1024*1024)
if err != nil {
writeErrorResponse(w, http.StatusUnsupportedMediaType, "unsupported_encoding", err.Error(), nil)
return
}
defer body.Close()
var report agentsk8s.Report
if err := json.NewDecoder(body).Decode(&report); err != nil {
writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Failed to decode request body", map[string]string{"error": err.Error()})
return
}
if report.Timestamp.IsZero() {
report.Timestamp = time.Now()
}
tokenRecord := getAPITokenRecordFromRequest(r)
cluster, err := h.getMonitor(r.Context()).ApplyKubernetesReport(report, tokenRecord)
if err != nil {
writeErrorResponse(w, http.StatusBadRequest, "invalid_report", err.Error(), nil)
return
}
if h.recoveryIngestor != nil {
orgID := GetOrgID(r.Context())
if ingestErr := h.recoveryIngestor.IngestKubernetesReport(r.Context(), orgID, report); ingestErr != nil {
// Never fail the agent ingest path because recovery ingestion is best-effort.
log.Warn().Err(ingestErr).Str("org_id", orgID).Msg("Failed to ingest kubernetes recovery artifacts")
}
}
log.Debug().
Str("k8sClusterID", cluster.ID).
Str("k8sClusterName", cluster.Name).
Int("nodes", len(cluster.Nodes)).
Int("pods", len(cluster.Pods)).
Int("deployments", len(cluster.Deployments)).
Msg("Kubernetes agent report processed")
h.broadcastState(r.Context())
if err := utils.WriteJSONResponse(w, map[string]any{
"success": true,
"clusterId": cluster.ID,
"nodes": len(cluster.Nodes),
"pods": len(cluster.Pods),
"deployments": len(cluster.Deployments),
"lastSeen": cluster.LastSeen,
}); err != nil {
log.Error().Err(err).Msg("Failed to serialize kubernetes agent response")
}
}
// HandleClusterActions routes kubernetes cluster management actions based on path and method.
func (h *KubernetesAgentHandlers) HandleClusterActions(w http.ResponseWriter, r *http.Request) {
// Allow reenroll request
if strings.HasSuffix(r.URL.Path, "/allow-reenroll") && r.Method == http.MethodPost {
h.HandleAllowReenroll(w, r)
return
}
// Unhide request
if strings.HasSuffix(r.URL.Path, "/unhide") && r.Method == http.MethodPut {
h.HandleUnhideCluster(w, r)
return
}
// Pending uninstall request
if strings.HasSuffix(r.URL.Path, "/pending-uninstall") && r.Method == http.MethodPut {
h.HandleMarkPendingUninstall(w, r)
return
}
// Custom display name update request
if strings.HasSuffix(r.URL.Path, "/display-name") && r.Method == http.MethodPut {
h.HandleSetCustomDisplayName(w, r)
return
}
// Delete/hide request
if r.Method == http.MethodDelete {
h.HandleDeleteCluster(w, r)
return
}
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed", nil)
}
// HandleDeleteCluster removes and blocks a cluster from re-enrolling.
func (h *KubernetesAgentHandlers) HandleDeleteCluster(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only DELETE is allowed", nil)
return
}
trimmedPath := strings.TrimPrefix(r.URL.Path, "/api/agents/kubernetes/clusters/")
clusterID := strings.TrimSpace(trimmedPath)
clusterID = strings.TrimSuffix(clusterID, "/")
if clusterID == "" {
writeErrorResponse(w, http.StatusBadRequest, "missing_cluster_id", "Kubernetes cluster ID is required", nil)
return
}
cluster, err := h.getMonitor(r.Context()).RemoveKubernetesCluster(clusterID)
if err != nil {
writeErrorResponse(w, http.StatusNotFound, "k8s_cluster_not_found", err.Error(), nil)
return
}
h.broadcastState(r.Context())
if err := utils.WriteJSONResponse(w, map[string]any{
"success": true,
"clusterId": cluster.ID,
"message": "Kubernetes cluster removed",
}); err != nil {
log.Error().Err(err).Msg("Failed to serialize kubernetes cluster operation response")
}
}
// HandleAllowReenroll clears the removal block for a cluster to permit future reports.
func (h *KubernetesAgentHandlers) HandleAllowReenroll(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only POST is allowed", nil)
return
}
trimmedPath := strings.TrimPrefix(r.URL.Path, "/api/agents/kubernetes/clusters/")
trimmedPath = strings.TrimSuffix(trimmedPath, "/allow-reenroll")
clusterID := strings.TrimSpace(trimmedPath)
if clusterID == "" {
writeErrorResponse(w, http.StatusBadRequest, "missing_cluster_id", "Kubernetes cluster ID is required", nil)
return
}
if err := h.getMonitor(r.Context()).AllowKubernetesClusterReenroll(clusterID); err != nil {
writeErrorResponse(w, http.StatusBadRequest, "k8s_cluster_reenroll_failed", err.Error(), nil)
return
}
if err := utils.WriteJSONResponse(w, map[string]any{
"success": true,
"clusterId": clusterID,
}); err != nil {
log.Error().Err(err).Msg("Failed to serialize kubernetes cluster allow reenroll response")
}
}
// handleClusterLifecycleAction runs the shared PUT cluster lifecycle flow:
// resolve the cluster ID from the suffixed route, apply the monitor action,
// broadcast state, and respond. action returns the canonical cluster ID.
func (h *KubernetesAgentHandlers) handleClusterLifecycleAction(
w http.ResponseWriter,
r *http.Request,
pathSuffix string,
successMsg string,
logMsg string,
action func(ctx context.Context, clusterID string) (string, error),
) {
if r.Method != http.MethodPut {
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only PUT is allowed", nil)
return
}
trimmedPath := strings.TrimPrefix(r.URL.Path, "/api/agents/kubernetes/clusters/")
trimmedPath = strings.TrimSuffix(trimmedPath, pathSuffix)
clusterID := strings.TrimSpace(trimmedPath)
if clusterID == "" {
writeErrorResponse(w, http.StatusBadRequest, "missing_cluster_id", "Kubernetes cluster ID is required", nil)
return
}
canonicalID, err := action(r.Context(), clusterID)
if err != nil {
writeErrorResponse(w, http.StatusNotFound, "k8s_cluster_not_found", err.Error(), nil)
return
}
h.broadcastState(r.Context())
if err := utils.WriteJSONResponse(w, map[string]any{
"success": true,
"clusterId": canonicalID,
"message": successMsg,
}); err != nil {
log.Error().Err(err).Msg(logMsg)
}
}
// HandleUnhideCluster unhides a previously hidden kubernetes cluster.
func (h *KubernetesAgentHandlers) HandleUnhideCluster(w http.ResponseWriter, r *http.Request) {
h.handleClusterLifecycleAction(w, r, "/unhide", "Kubernetes cluster unhidden", "Failed to serialize kubernetes cluster unhide response",
func(ctx context.Context, clusterID string) (string, error) {
cluster, err := h.getMonitor(ctx).UnhideKubernetesCluster(clusterID)
if err != nil {
return "", err
}
return cluster.ID, nil
})
}
// HandleMarkPendingUninstall marks a cluster as pending uninstall.
func (h *KubernetesAgentHandlers) HandleMarkPendingUninstall(w http.ResponseWriter, r *http.Request) {
h.handleClusterLifecycleAction(w, r, "/pending-uninstall", "Kubernetes cluster marked as pending uninstall", "Failed to serialize kubernetes cluster pending uninstall response",
func(ctx context.Context, clusterID string) (string, error) {
cluster, err := h.getMonitor(ctx).MarkKubernetesClusterPendingUninstall(clusterID)
if err != nil {
return "", err
}
return cluster.ID, nil
})
}
// HandleSetCustomDisplayName updates the custom display name for a kubernetes cluster.
func (h *KubernetesAgentHandlers) HandleSetCustomDisplayName(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only PUT is allowed", nil)
return
}
trimmedPath := strings.TrimPrefix(r.URL.Path, "/api/agents/kubernetes/clusters/")
trimmedPath = strings.TrimSuffix(trimmedPath, "/display-name")
clusterID := strings.TrimSpace(trimmedPath)
if clusterID == "" {
writeErrorResponse(w, http.StatusBadRequest, "missing_cluster_id", "Kubernetes cluster ID is required", nil)
return
}
// Limit request body to 8KB to prevent memory exhaustion
r.Body = http.MaxBytesReader(w, r.Body, 8*1024)
defer r.Body.Close()
var req struct {
DisplayName string `json:"displayName"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Failed to decode request body", map[string]string{"error": err.Error()})
return
}
customName := strings.TrimSpace(req.DisplayName)
cluster, err := h.getMonitor(r.Context()).SetKubernetesClusterCustomDisplayName(clusterID, customName)
if err != nil {
writeErrorResponse(w, http.StatusNotFound, "k8s_cluster_not_found", err.Error(), nil)
return
}
h.broadcastState(r.Context())
if err := utils.WriteJSONResponse(w, map[string]any{
"success": true,
"clusterId": cluster.ID,
"message": "Kubernetes cluster custom display name updated",
}); err != nil {
log.Error().Err(err).Msg("Failed to serialize kubernetes cluster custom display name response")
}
}