Pulse/internal/api/docker_metadata.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

216 lines
7.3 KiB
Go

package api
import (
"context"
"encoding/json"
"net/http"
"strings"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rs/zerolog/log"
)
const (
dockerRuntimeMetadataCollectionPath = "/api/docker/runtimes/metadata"
dockerRuntimeMetadataPathPrefix = "/api/docker/runtimes/metadata/"
)
// DockerMetadataHandler handles Docker resource metadata operations
type DockerMetadataHandler struct {
mtPersistence *config.MultiTenantPersistence
}
// NewDockerMetadataHandler creates a new Docker metadata handler
func NewDockerMetadataHandler(mtPersistence *config.MultiTenantPersistence) *DockerMetadataHandler {
return &DockerMetadataHandler{
mtPersistence: mtPersistence,
}
}
func (h *DockerMetadataHandler) getStore(ctx context.Context) *config.DockerMetadataStore {
orgID := "default"
if ctx != nil {
if requestOrgID := GetOrgID(ctx); requestOrgID != "" {
orgID = requestOrgID
}
}
p, _ := h.mtPersistence.GetPersistence(orgID)
return p.GetDockerMetadataStore()
}
// Store returns the underlying metadata store for default tenant
func (h *DockerMetadataHandler) Store() *config.DockerMetadataStore {
return h.getStore(context.Background())
}
// HandleGetMetadata retrieves metadata for a specific Docker resource or all resources
func (h *DockerMetadataHandler) HandleGetMetadata(w http.ResponseWriter, r *http.Request) {
handleMetadataGetRequest(w, r, "/api/docker/metadata",
func(ctx context.Context) map[string]*config.DockerMetadata { return h.getStore(ctx).GetAll() },
func(ctx context.Context, id string) *config.DockerMetadata { return h.getStore(ctx).Get(id) },
func(id string) *config.DockerMetadata { return &config.DockerMetadata{ID: id} },
)
}
// HandleUpdateMetadata updates metadata for a Docker resource
func (h *DockerMetadataHandler) HandleUpdateMetadata(w http.ResponseWriter, r *http.Request) {
handleMetadataUpdateRequest(w, r, "/api/docker/metadata",
"Resource ID required",
"resourceID",
"Failed to save Docker metadata",
"Updated Docker metadata",
func(meta *config.DockerMetadata) string { return meta.CustomURL },
func(ctx context.Context, id string, meta *config.DockerMetadata) error {
return h.getStore(ctx).Set(id, meta)
},
)
}
// HandleDeleteMetadata removes metadata for a Docker resource
func (h *DockerMetadataHandler) HandleDeleteMetadata(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
resourceID := strings.TrimPrefix(r.URL.Path, "/api/docker/metadata/")
if resourceID == "" || resourceID == "metadata" {
http.Error(w, "Resource ID required", http.StatusBadRequest)
return
}
store := h.getStore(r.Context())
if err := store.Delete(resourceID); err != nil {
log.Error().Err(err).Str("resourceID", resourceID).Msg("Failed to delete Docker metadata")
http.Error(w, "Failed to delete metadata", http.StatusInternalServerError)
return
}
log.Info().Str("resourceID", resourceID).Msg("Deleted Docker metadata")
w.WriteHeader(http.StatusNoContent)
}
// HandleGetRuntimeMetadata retrieves metadata for a Docker runtime or all runtimes.
func (h *DockerMetadataHandler) HandleGetRuntimeMetadata(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Check if requesting a specific runtime.
path := r.URL.Path
if path == dockerRuntimeMetadataCollectionPath || path == dockerRuntimeMetadataCollectionPath+"/" {
// Get all runtime metadata.
w.Header().Set("Content-Type", "application/json")
store := h.getStore(r.Context())
allMeta := store.GetAllHostMetadata()
if allMeta == nil {
// Return empty object instead of null.
json.NewEncoder(w).Encode(make(map[string]*config.DockerHostMetadata))
} else {
json.NewEncoder(w).Encode(allMeta)
}
return
}
// Get specific runtime ID from path.
runtimeID := strings.TrimPrefix(path, dockerRuntimeMetadataPathPrefix)
w.Header().Set("Content-Type", "application/json")
if runtimeID != "" {
// Get specific runtime metadata.
store := h.getStore(r.Context())
meta := store.GetHostMetadata(runtimeID)
if meta == nil {
// Return empty metadata instead of 404.
json.NewEncoder(w).Encode(&config.DockerHostMetadata{})
} else {
json.NewEncoder(w).Encode(meta)
}
} else {
// This shouldn't happen with current routing, but handle it anyway.
http.Error(w, "Invalid request path", http.StatusBadRequest)
}
}
// HandleUpdateRuntimeMetadata updates metadata for a Docker / Podman host.
func (h *DockerMetadataHandler) HandleUpdateRuntimeMetadata(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut && r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
runtimeID := strings.TrimPrefix(r.URL.Path, dockerRuntimeMetadataPathPrefix)
if runtimeID == "" || runtimeID == "metadata" {
http.Error(w, "Docker / Podman host ID required", http.StatusBadRequest)
return
}
// Limit request body to 16KB to prevent memory exhaustion
r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
var meta config.DockerHostMetadata
if err := json.NewDecoder(r.Body).Decode(&meta); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// Validate URL if provided
if errMsg := validateCustomURL(meta.CustomURL); errMsg != "" {
http.Error(w, errMsg, http.StatusBadRequest)
return
}
// Get existing metadata to merge with new data
store := h.getStore(r.Context())
existing := store.GetHostMetadata(runtimeID)
if existing != nil {
// Merge: only update fields that are provided
if meta.CustomDisplayName != "" || existing.CustomDisplayName != "" {
if meta.CustomDisplayName == "" {
meta.CustomDisplayName = existing.CustomDisplayName
}
}
// CustomURL can be explicitly cleared, so we don't merge it unless updating
if meta.Notes == nil && existing.Notes != nil {
meta.Notes = existing.Notes
}
}
if err := store.SetHostMetadata(runtimeID, &meta); err != nil {
log.Error().Err(err).Str("runtimeID", runtimeID).Msg("Failed to save Docker / Podman host metadata")
http.Error(w, metadataSaveErrorMessage(err), http.StatusInternalServerError)
return
}
log.Info().Str("runtimeID", runtimeID).Str("url", meta.CustomURL).Msg("Updated Docker / Podman host metadata")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(&meta)
}
// HandleDeleteRuntimeMetadata removes metadata for a Docker / Podman host.
func (h *DockerMetadataHandler) HandleDeleteRuntimeMetadata(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
runtimeID := strings.TrimPrefix(r.URL.Path, dockerRuntimeMetadataPathPrefix)
if runtimeID == "" || runtimeID == "metadata" {
http.Error(w, "Docker / Podman host ID required", http.StatusBadRequest)
return
}
store := h.getStore(r.Context())
if err := store.SetHostMetadata(runtimeID, nil); err != nil {
log.Error().Err(err).Str("runtimeID", runtimeID).Msg("Failed to delete Docker / Podman host metadata")
http.Error(w, "Failed to delete metadata", http.StatusInternalServerError)
return
}
log.Info().Str("runtimeID", runtimeID).Msg("Deleted Docker / Podman host metadata")
w.WriteHeader(http.StatusNoContent)
}