Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix: Include GuestURL in NodeFrontend for cluster node navigation

rcourtman9f3367da366a
diff --git a/frontend-modern/src/api/monitoring.ts b/frontend-modern/src/api/monitoring.ts
index 695f1ddfa7..acff6c84e7 100644
--- a/frontend-modern/src/api/monitoring.ts
+++ b/frontend-modern/src/api/monitoring.ts
@@ -568,6 +568,61 @@ export class MonitoringAPI {
return data;
}
+
+ /**
+ * Triggers an update for a Docker container on a specific host.
+ * The update will pull the latest image and recreate the container.
+ */
+ static async updateDockerContainer(
+ hostId: string,
+ containerId: string,
+ containerName: string
+ ): Promise<UpdateDockerContainerResponse> {
+ const url = `${this.baseUrl}/agents/docker/containers/update`;
+
+ const response = await apiFetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ hostId, containerId, containerName }),
+ });
+
+ if (!response.ok) {
+ let message = `Failed with status ${response.status}`;
+ try {
+ const text = await response.text();
+ if (text?.trim()) {
+ message = text.trim();
+ try {
+ const parsed = JSON.parse(text);
+ if (typeof parsed?.error === 'string' && parsed.error.trim()) {
+ message = parsed.error.trim();
+ } else if (typeof parsed?.message === 'string' && parsed.message.trim()) {
+ message = parsed.message.trim();
+ }
+ } catch (_jsonErr) {
+ // ignore JSON parse errors, fallback to raw text
+ }
+ }
+ } catch (_err) {
+ // ignore read error, keep default message
+ }
+
+ throw new Error(message);
+ }
+
+ const text = await response.text();
+ if (!text?.trim()) {
+ return { success: true };
+ }
+
+ try {
+ return JSON.parse(text) as UpdateDockerContainerResponse;
+ } catch (err) {
+ throw new Error((err as Error).message || 'Failed to parse update container response');
+ }
+ }
}
export interface DeleteDockerHostResponse {
@@ -582,3 +637,16 @@ export interface DeleteKubernetesClusterResponse {
clusterId?: string;
message?: string;
}
+
+export interface UpdateDockerContainerResponse {
+ success?: boolean;
+ commandId?: string;
+ hostId?: string;
+ container?: {
+ id: string;
+ name: string;
+ };
+ message?: string;
+ note?: string;
+}
+
diff --git a/frontend-modern/src/components/Docker/DockerUnifiedTable.tsx b/frontend-modern/src/components/Docker/DockerUnifiedTable.tsx
index ed575d8857..68fce28047 100644
--- a/frontend-modern/src/components/Docker/DockerUnifiedTable.tsx
+++ b/frontend-modern/src/components/Docker/DockerUnifiedTable.tsx
@@ -28,7 +28,7 @@ import { ResponsiveMetricCell } from '@/components/shared/responsive';
import { useBreakpoint } from '@/hooks/useBreakpoint';
import { StackedMemoryBar } from '@/components/Dashboard/StackedMemoryBar';
import { UrlEditPopover } from '@/components/shared/UrlEditPopover';
-import { UpdateIcon } from '@/components/Docker/UpdateBadge';
+import { UpdateButton } from '@/components/Docker/UpdateBadge';
import type { ColumnConfig } from '@/types/responsive';
const typeBadgeClass = (type: 'container' | 'service' | 'task' | 'unknown') => {
@@ -1304,7 +1304,13 @@ const DockerContainerRow: Component<{
>
{container.image || '—'}
</span>
- <UpdateIcon updateStatus={container.updateStatus} />
+ <UpdateButton
+ updateStatus={container.updateStatus}
+ hostId={host.id}
+ containerId={container.id}
+ containerName={container.name}
+ compact
+ />
</div>
</div>
);
diff --git a/frontend-modern/src/components/Docker/UpdateBadge.tsx b/frontend-modern/src/components/Docker/UpdateBadge.tsx
index 9022053657..edcbdd7120 100644
--- a/frontend-modern/src/components/Docker/UpdateBadge.tsx
+++ b/frontend-modern/src/components/Docker/UpdateBadge.tsx
@@ -1,5 +1,8 @@
-import { Component, Show } from 'solid-js';
+import { Component, Show, createSignal } from 'solid-js';
import type { DockerContainerUpdateStatus } from '@/types/api';
+import { showTooltip, hideTooltip } from '@/components/shared/Tooltip';
+import { MonitoringAPI } from '@/api/monitoring';
+
interface UpdateBadgeProps {
updateStatus?: DockerContainerUpdateStatus;
@@ -22,8 +25,15 @@ export const UpdateBadge: Component<UpdateBadgeProps> = (props) => {
// Show subtle error indicator if check failed
<Show when={hasError()}>
<span
- class="inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-xs font-medium bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400"
- title={`Update check failed: ${props.updateStatus?.error}`}
+ class="inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-xs font-medium bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400 cursor-help"
+ onMouseEnter={(e) => {
+ const rect = e.currentTarget.getBoundingClientRect();
+ showTooltip(`Update check failed: ${props.updateStatus?.error}`, rect.left + rect.width / 2, rect.top, {
+ align: 'center',
+ direction: 'up'
+ });
+ }}
+ onMouseLeave={() => hideTooltip()}
>
<svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
@@ -36,8 +46,18 @@ export const UpdateBadge: Component<UpdateBadgeProps> = (props) => {
}
>
<span
- class="inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-xs font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300"
- title={`Image update available. Current: ${props.updateStatus?.currentDigest?.slice(0, 19) || 'unknown'}... Latest: ${props.updateStatus?.latestDigest?.slice(0, 19) || 'unknown'}...`}
+ class="inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-xs font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 cursor-help"
+ onMouseEnter={(e) => {
+ const rect = e.currentTarget.getBoundingClientRect();
+ const current = props.updateStatus?.currentDigest?.slice(0, 19) || 'unknown';
+ const latest = props.updateStatus?.latestDigest?.slice(0, 19) || 'unknown';
+ const content = `Image update available\nCurrent: ${current}...\nLatest: ${latest}...`;
+ showTooltip(content, rect.left + rect.width / 2, rect.top, {
+ align: 'center',
+ direction: 'up'
+ });
+ }}
+ onMouseLeave={() => hideTooltip()}
>
<svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
@@ -71,7 +91,14 @@ export const UpdateIcon: Component<{ updateStatus?: DockerContainerUpdateStatus
<Show when={hasUpdate()}>
<span
class="inline-flex items-center justify-center w-5 h-5 rounded-full bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 cursor-help"
- title={getTooltip()}
+ onMouseEnter={(e) => {
+ const rect = e.currentTarget.getBoundingClientRect();
+ showTooltip(getTooltip(), rect.left + rect.width / 2, rect.top, {
+ align: 'center',
+ direction: 'up'
+ });
+ }}
+ onMouseLeave={() => hideTooltip()}
>
<svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
@@ -81,4 +108,168 @@ export const UpdateIcon: Component<{ updateStatus?: DockerContainerUpdateStatus
);
};
+interface UpdateButtonProps {
+ updateStatus?: DockerContainerUpdateStatus;
+ hostId: string;
+ containerId: string;
+ containerName: string;
+ compact?: boolean;
+ onUpdateTriggered?: () => void;
+}
+
+type UpdateState = 'idle' | 'confirming' | 'updating' | 'success' | 'error';
+
+/**
+ * UpdateButton displays a clickable button to trigger container updates.
+ * Includes confirmation, loading states, and error handling.
+ */
+export const UpdateButton: Component<UpdateButtonProps> = (props) => {
+ const [state, setState] = createSignal<UpdateState>('idle');
+ const [errorMessage, setErrorMessage] = createSignal<string>('');
+
+ const hasUpdate = () => props.updateStatus?.updateAvailable === true;
+
+ const handleClick = async (e: MouseEvent) => {
+ e.stopPropagation();
+ e.preventDefault();
+
+ if (state() === 'idle') {
+ // Show confirmation
+ setState('confirming');
+ return;
+ }
+
+ if (state() === 'confirming') {
+ // User confirmed, trigger update
+ setState('updating');
+ try {
+ await MonitoringAPI.updateDockerContainer(
+ props.hostId,
+ props.containerId,
+ props.containerName
+ );
+ setState('success');
+ props.onUpdateTriggered?.();
+ // Reset after 3 seconds
+ setTimeout(() => setState('idle'), 3000);
+ } catch (err) {
+ setErrorMessage((err as Error).message || 'Failed to trigger update');
+ setState('error');
+ // Reset after 5 seconds
+ setTimeout(() => setState('idle'), 5000);
+ }
+ }
+ };
+
+ const handleCancel = (e: MouseEvent) => {
+ e.stopPropagation();
+ e.preventDefault();
+ setState('idle');
+ };
+
+ const getButtonClass = () => {
+ const base = 'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium transition-all';
+ switch (state()) {
+ case 'confirming':
+ return `${base} bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300 cursor-pointer hover:bg-amber-200 dark:hover:bg-amber-900/60`;
+ case 'updating':
+ return `${base} bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 cursor-wait`;
+ case 'success':
+ return `${base} bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300`;
+ case 'error':
+ return `${base} bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300 cursor-help`;
+ default:
+ return `${base} bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 cursor-pointer hover:bg-blue-200 dark:hover:bg-blue-900/60`;
+ }
+ };
+
+ const getTooltip = () => {
+ switch (state()) {
+ case 'confirming':
+ return 'Click again to confirm update';
+ case 'updating':
+ return 'Update in progress...';
+ case 'success':
+ return 'Update command sent! Container will restart shortly.';
+ case 'error':
+ return `Error: ${errorMessage()}`;
+ default:
+ if (!props.updateStatus) return 'Update container';
+ const current = props.updateStatus.currentDigest?.slice(0, 12) || 'unknown';
+ const latest = props.updateStatus.latestDigest?.slice(0, 12) || 'unknown';
+ return `Click to update\nCurrent: ${current}...\nLatest: ${latest}...`;
+ }
+ };
+
+ return (
+ <Show when={hasUpdate()}>
+ <div class="inline-flex items-center gap-1" data-prevent-toggle>
+ <button
+ type="button"
+ class={getButtonClass()}
+ onClick={handleClick}
+ onMouseDown={(e) => { e.stopPropagation(); }}
+ disabled={state() === 'updating'}
+ data-prevent-toggle
+ onMouseEnter={(e) => {
+ const rect = e.currentTarget.getBoundingClientRect();
+ showTooltip(getTooltip(), rect.left + rect.width / 2, rect.top, {
+ align: 'center',
+ direction: 'up'
+ });
+ }}
+ onMouseLeave={() => hideTooltip()}
+ >
+ <Show when={state() === 'updating'}>
+ {/* Spinner */}
+ <svg class="w-3 h-3 animate-spin" fill="none" viewBox="0 0 24 24">
+ <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
+ <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
+ </svg>
+ </Show>
+ <Show when={state() === 'success'}>
+ {/* Check icon */}
+ <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
+ <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
+ </svg>
+ </Show>
+ <Show when={state() === 'error'}>
+ {/* X icon */}
+ <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
+ <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
+ </svg>
+ </Show>
+ <Show when={state() === 'idle' || state() === 'confirming'}>
+ {/* Upload/update icon */}
+ <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
+ <path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
+ </svg>
+ </Show>
+ <Show when={!props.compact}>
+ <span>
+ {state() === 'confirming' ? 'Confirm?' :
+ state() === 'updating' ? 'Updating...' :
+ state() === 'success' ? 'Queued!' :
+ state() === 'error' ? 'Failed' : 'Update'}
+ </span>
+ </Show>
+ </button>
+ <Show when={state() === 'confirming'}>
+ <button
+ type="button"
+ class="inline-flex items-center justify-center w-5 h-5 rounded-full bg-gray-200 text-gray-600 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors"
+ onClick={handleCancel}
+ title="Cancel"
+ >
+ <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
+ <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
+ </svg>
+ </button>
+ </Show>
+ </div>
+ </Show>
+ );
+};
+
export default UpdateBadge;
+
diff --git a/internal/api/docker_agents.go b/internal/api/docker_agents.go
index 00d61a6c6d..4633dfe3c4 100644
--- a/internal/api/docker_agents.go
+++ b/internal/api/docker_agents.go
@@ -458,3 +458,59 @@ func (h *DockerAgentHandlers) HandleSetCustomDisplayName(w http.ResponseWriter,
log.Error().Err(err).Msg("Failed to serialize docker host custom display name response")
}
}
+
+// HandleContainerUpdate triggers a container update on a Docker host.
+// POST /api/agents/docker/containers/{containerId}/update
+func (h *DockerAgentHandlers) HandleContainerUpdate(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 8KB to prevent memory exhaustion
+ r.Body = http.MaxBytesReader(w, r.Body, 8*1024)
+ defer r.Body.Close()
+
+ var req struct {
+ HostID string `json:"hostId"`
+ ContainerID string `json:"containerId"`
+ ContainerName string `json:"containerName"`
+ }
+ 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
+ }
+
+ if req.HostID == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "missing_host_id", "Host ID is required", nil)
+ return
+ }
+ if req.ContainerID == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "missing_container_id", "Container ID is required", nil)
+ return
+ }
+
+ // Queue the update command
+ commandStatus, err := h.monitor.QueueDockerContainerUpdateCommand(req.HostID, req.ContainerID, req.ContainerName)
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "update_command_failed", err.Error(), nil)
+ return
+ }
+
+ go h.wsHub.BroadcastState(h.monitor.GetState().ToFrontend())
+
+ if err := utils.WriteJSONResponse(w, map[string]any{
+ "success": true,
+ "commandId": commandStatus.ID,
+ "hostId": req.HostID,
+ "container": map[string]string{
+ "id": req.ContainerID,
+ "name": req.ContainerName,
+ },
+ "message": "Container update command queued",
+ "note": "The update will be executed on the next agent report cycle",
+ }); err != nil {
+ log.Error().Err(err).Msg("Failed to serialize container update response")
+ }
+}
+
diff --git a/internal/api/router.go b/internal/api/router.go
index 91f81a1437..d720af4a19 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -242,6 +242,7 @@ func (r *Router) setupRoutes() {
r.mux.HandleFunc("/api/temperature-proxy/host-status", r.requireSensorProxyEnabled(RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.handleHostProxyStatus))))
r.mux.HandleFunc("/api/agents/docker/commands/", RequireAuth(r.config, RequireScope(config.ScopeDockerReport, r.dockerAgentHandlers.HandleCommandAck)))
r.mux.HandleFunc("/api/agents/docker/hosts/", RequireAdmin(r.config, RequireScope(config.ScopeDockerManage, r.dockerAgentHandlers.HandleDockerHostActions)))
+ r.mux.HandleFunc("/api/agents/docker/containers/update", RequireAdmin(r.config, RequireScope(config.ScopeDockerManage, r.dockerAgentHandlers.HandleContainerUpdate)))
r.mux.HandleFunc("/api/agents/kubernetes/clusters/", RequireAdmin(r.config, RequireScope(config.ScopeKubernetesManage, r.kubernetesAgentHandlers.HandleClusterActions)))
r.mux.HandleFunc("/api/version", r.handleVersion)
r.mux.HandleFunc("/api/storage/", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.handleStorage)))
diff --git a/internal/dockeragent/agent.go b/internal/dockeragent/agent.go
index efaab683d4..4da036c75a 100644
--- a/internal/dockeragent/agent.go
+++ b/internal/dockeragent/agent.go
@@ -1208,6 +1208,8 @@ func (a *Agent) handleCommand(ctx context.Context, target TargetConfig, command
switch strings.ToLower(command.Type) {
case agentsdocker.CommandTypeStop:
return a.handleStopCommand(ctx, target, command)
+ case agentsdocker.CommandTypeUpdateContainer:
+ return a.handleUpdateContainerCommand(ctx, target, command)
default:
a.logger.Warn().Str("command", command.Type).Msg("Received unsupported control command")
return nil
diff --git a/internal/dockeragent/container_update.go b/internal/dockeragent/container_update.go
new file mode 100644
index 0000000000..28afbde016
--- /dev/null
+++ b/internal/dockeragent/container_update.go
@@ -0,0 +1,240 @@
+package dockeragent
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "strings"
+ "time"
+
+ "github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/api/types/image"
+ "github.com/docker/docker/api/types/network"
+ agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker"
+)
+
+// ContainerUpdateResult captures the outcome of a container update operation.
+type ContainerUpdateResult struct {
+ Success bool `json:"success"`
+ ContainerID string `json:"containerId"`
+ ContainerName string `json:"containerName"`
+ OldImageDigest string `json:"oldImageDigest,omitempty"`
+ NewImageDigest string `json:"newImageDigest,omitempty"`
+ BackupCreated bool `json:"backupCreated"`
+ BackupContainer string `json:"backupContainer,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+// handleUpdateContainerCommand handles the update_container command from Pulse.
+func (a *Agent) handleUpdateContainerCommand(ctx context.Context, target TargetConfig, command agentsdocker.Command) error {
+ containerID, ok := command.Payload["containerId"].(string)
+ if !ok || containerID == "" {
+ a.logger.Error().Msg("Update command missing containerId in payload")
+ if err := a.sendCommandAck(ctx, target, command.ID, agentsdocker.CommandStatusFailed, "Missing containerId in payload"); err != nil {
+ a.logger.Error().Err(err).Msg("Failed to send failure acknowledgement")
+ }
+ return nil
+ }
+
+ a.logger.Info().
+ Str("commandID", command.ID).
+ Str("containerId", containerID).
+ Msg("Received update_container command from Pulse")
+
+ // Send acknowledgement that we're starting the update
+ if err := a.sendCommandAck(ctx, target, command.ID, agentsdocker.CommandStatusAcknowledged, "Starting container update"); err != nil {
+ a.logger.Error().Err(err).Msg("Failed to send acknowledgement to Pulse")
+ return nil
+ }
+
+ // Perform the update
+ result := a.updateContainer(ctx, containerID)
+
+ // Send completion status
+ status := agentsdocker.CommandStatusCompleted
+ message := fmt.Sprintf("Container %s updated successfully", result.ContainerName)
+ if !result.Success {
+ status = agentsdocker.CommandStatusFailed
+ message = result.Error
+ }
+
+ if err := a.sendCommandAck(ctx, target, command.ID, status, message); err != nil {
+ a.logger.Error().Err(err).Msg("Failed to send completion acknowledgement to Pulse")
+ }
+
+ return nil
+}
+
+// updateContainer performs the actual container update operation.
+// This is the core logic that:
+// 1. Inspects the current container configuration
+// 2. Pulls the latest image
+// 3. Stops and renames the old container (for backup)
+// 4. Creates a new container with the same config
+// 5. Starts the new container
+// 6. Cleans up on success or rolls back on failure
+func (a *Agent) updateContainer(ctx context.Context, containerID string) ContainerUpdateResult {
+ result := ContainerUpdateResult{
+ ContainerID: containerID,
+ }
+
+ // 1. Inspect the current container to get its full configuration
+ inspect, err := a.docker.ContainerInspect(ctx, containerID)
+ if err != nil {
+ result.Error = fmt.Sprintf("Failed to inspect container: %v", err)
+ a.logger.Error().Err(err).Str("containerId", containerID).Msg("Failed to inspect container for update")
+ return result
+ }
+
+ result.ContainerName = strings.TrimPrefix(inspect.Name, "/")
+ result.OldImageDigest = inspect.Image
+
+ a.logger.Info().
+ Str("container", result.ContainerName).
+ Str("image", inspect.Config.Image).
+ Msg("Starting container update")
+
+ // 2. Pull the latest image
+ imageName := inspect.Config.Image
+ a.logger.Info().Str("image", imageName).Msg("Pulling latest image")
+
+ pullResp, err := a.docker.ImagePull(ctx, imageName, image.PullOptions{})
+ if err != nil {
+ result.Error = fmt.Sprintf("Failed to pull image %s: %v", imageName, err)
+ a.logger.Error().Err(err).Str("image", imageName).Msg("Failed to pull latest image")
+ return result
+ }
+ // Consume the pull response to ensure the pull completes
+ _, _ = io.Copy(io.Discard, pullResp)
+ pullResp.Close()
+
+ a.logger.Info().Str("image", imageName).Msg("Successfully pulled latest image")
+
+ // 3. Stop the current container
+ stopTimeout := 30 // seconds
+ if err := a.docker.ContainerStop(ctx, containerID, container.StopOptions{Timeout: &stopTimeout}); err != nil {
+ result.Error = fmt.Sprintf("Failed to stop container: %v", err)
+ a.logger.Error().Err(err).Str("container", result.ContainerName).Msg("Failed to stop container")
+ return result
+ }
+
+ a.logger.Info().Str("container", result.ContainerName).Msg("Container stopped")
+
+ // 4. Rename the old container for backup
+ backupName := result.ContainerName + "_pulse_backup_" + time.Now().Format("20060102_150405")
+ if err := a.docker.ContainerRename(ctx, containerID, backupName); err != nil {
+ result.Error = fmt.Sprintf("Failed to rename container for backup: %v", err)
+ a.logger.Error().Err(err).Str("container", result.ContainerName).Msg("Failed to rename container for backup")
+ // Try to restart the original container
+ _ = a.docker.ContainerStart(ctx, containerID, container.StartOptions{})
+ return result
+ }
+
+ result.BackupCreated = true
+ result.BackupContainer = backupName
+ a.logger.Info().Str("backup", backupName).Msg("Container renamed for backup")
+
+ // 5. Prepare network configuration
+ // We need to handle network settings carefully
+ var networkingConfig *network.NetworkingConfig
+ if len(inspect.NetworkSettings.Networks) > 0 {
+ networkingConfig = &network.NetworkingConfig{
+ EndpointsConfig: make(map[string]*network.EndpointSettings),
+ }
+ // Only set the first network here; we'll connect to others after creation
+ for netName, netConfig := range inspect.NetworkSettings.Networks {
+ networkingConfig.EndpointsConfig[netName] = &network.EndpointSettings{
+ Aliases: netConfig.Aliases,
+ IPAMConfig: netConfig.IPAMConfig,
+ Links: netConfig.Links,
+ NetworkID: netConfig.NetworkID,
+ EndpointID: "", // Will be assigned
+ Gateway: "", // Will be assigned
+ IPAddress: "", // Will be assigned
+ MacAddress: netConfig.MacAddress,
+ DriverOpts: netConfig.DriverOpts,
+ }
+ break // Only set one network during creation
+ }
+ }
+
+ // 6. Create a new container with the same configuration
+ createResp, err := a.docker.ContainerCreate(
+ ctx,
+ inspect.Config,
+ inspect.HostConfig,
+ networkingConfig,
+ nil, // Platform
+ result.ContainerName,
+ )
+ if err != nil {
+ result.Error = fmt.Sprintf("Failed to create new container: %v", err)
+ a.logger.Error().Err(err).Str("container", result.ContainerName).Msg("Failed to create new container")
+ // Rollback: rename backup back to original name
+ _ = a.docker.ContainerRename(ctx, backupName, result.ContainerName)
+ _ = a.docker.ContainerStart(ctx, containerID, container.StartOptions{})
+ return result
+ }
+
+ newContainerID := createResp.ID
+ a.logger.Info().Str("newContainerId", newContainerID).Msg("New container created")
+
+ // 7. Connect to additional networks (if more than one)
+ networkCount := 0
+ for netName, netConfig := range inspect.NetworkSettings.Networks {
+ networkCount++
+ if networkCount == 1 {
+ continue // Skip the first one, already connected during creation
+ }
+ endpointConfig := &network.EndpointSettings{
+ Aliases: netConfig.Aliases,
+ IPAMConfig: netConfig.IPAMConfig,
+ Links: netConfig.Links,
+ MacAddress: netConfig.MacAddress,
+ DriverOpts: netConfig.DriverOpts,
+ }
+ if err := a.docker.NetworkConnect(ctx, netName, newContainerID, endpointConfig); err != nil {
+ a.logger.Warn().Err(err).Str("network", netName).Msg("Failed to connect to network, continuing anyway")
+ }
+ }
+
+ // 8. Start the new container
+ if err := a.docker.ContainerStart(ctx, newContainerID, container.StartOptions{}); err != nil {
+ result.Error = fmt.Sprintf("Failed to start new container: %v", err)
+ a.logger.Error().Err(err).Str("container", result.ContainerName).Msg("Failed to start new container")
+ // Rollback: remove new container, rename backup back
+ _ = a.docker.ContainerRemove(ctx, newContainerID, container.RemoveOptions{Force: true})
+ _ = a.docker.ContainerRename(ctx, backupName, result.ContainerName)
+ _ = a.docker.ContainerStart(ctx, containerID, container.StartOptions{})
+ return result
+ }
+
+ a.logger.Info().Str("container", result.ContainerName).Msg("New container started successfully")
+
+ // 9. Get the new image digest
+ newInspect, err := a.docker.ContainerInspect(ctx, newContainerID)
+ if err == nil {
+ result.NewImageDigest = newInspect.Image
+ }
+
+ // 10. Schedule cleanup of backup container after a delay
+ // This gives time to verify the new container is working
+ go func() {
+ time.Sleep(5 * time.Minute)
+ cleanupCtx := context.Background()
+ if err := a.docker.ContainerRemove(cleanupCtx, backupName, container.RemoveOptions{Force: true}); err != nil {
+ a.logger.Warn().Err(err).Str("backup", backupName).Msg("Failed to cleanup backup container")
+ } else {
+ a.logger.Info().Str("backup", backupName).Msg("Backup container cleaned up")
+ }
+ }()
+
+ result.Success = true
+ a.logger.Info().
+ Str("container", result.ContainerName).
+ Str("oldDigest", result.OldImageDigest[:12]).
+ Str("newDigest", result.NewImageDigest[:12]).
+ Msg("Container update completed successfully")
+
+ return result
+}
diff --git a/internal/models/converters.go b/internal/models/converters.go
index 13f8cadd95..90d82cd587 100644
--- a/internal/models/converters.go
+++ b/internal/models/converters.go
@@ -19,6 +19,7 @@ func (n Node) ToFrontend() NodeFrontend {
DisplayName: n.DisplayName,
Instance: n.Instance,
Host: n.Host,
+ GuestURL: n.GuestURL,
Status: n.Status,
Type: n.Type,
CPU: n.CPU,
@@ -599,6 +600,16 @@ func (c DockerContainer) ToFrontend() DockerContainerFrontend {
}
}
+ if c.UpdateStatus != nil {
+ container.UpdateStatus = &DockerContainerUpdateStatusFrontend{
+ UpdateAvailable: c.UpdateStatus.UpdateAvailable,
+ CurrentDigest: c.UpdateStatus.CurrentDigest,
+ LatestDigest: c.UpdateStatus.LatestDigest,
+ LastChecked: timeToUnixMillis(c.UpdateStatus.LastChecked),
+ Error: c.UpdateStatus.Error,
+ }
+ }
+
return container
}
diff --git a/internal/models/models_frontend.go b/internal/models/models_frontend.go
index 9ecb18c237..c0b0505120 100644
--- a/internal/models/models_frontend.go
+++ b/internal/models/models_frontend.go
@@ -11,6 +11,7 @@ type NodeFrontend struct {
DisplayName string `json:"displayName"`
Instance string `json:"instance"`
Host string `json:"host,omitempty"`
+ GuestURL string `json:"guestURL,omitempty"` // Optional guest-accessible URL (for navigation)
Status string `json:"status"`
Type string `json:"type"`
CPU float64 `json:"cpu"`
@@ -261,11 +262,22 @@ type DockerContainerFrontend struct {
Networks []DockerContainerNetworkFrontend `json:"networks,omitempty"`
WritableLayerBytes int64 `json:"writableLayerBytes,omitempty"`
RootFilesystemBytes int64 `json:"rootFilesystemBytes,omitempty"`
- BlockIO *DockerContainerBlockIOFrontend `json:"blockIo,omitempty"`
- Mounts []DockerContainerMountFrontend `json:"mounts,omitempty"`
- Podman *DockerPodmanContainerFrontend `json:"podman,omitempty"`
+ BlockIO *DockerContainerBlockIOFrontend `json:"blockIo,omitempty"`
+ Mounts []DockerContainerMountFrontend `json:"mounts,omitempty"`
+ Podman *DockerPodmanContainerFrontend `json:"podman,omitempty"`
+ UpdateStatus *DockerContainerUpdateStatusFrontend `json:"updateStatus,omitempty"`
}
+// DockerContainerUpdateStatusFrontend tracks the image update status for a container.
+type DockerContainerUpdateStatusFrontend struct {
+ UpdateAvailable bool `json:"updateAvailable"`
+ CurrentDigest string `json:"currentDigest,omitempty"`
+ LatestDigest string `json:"latestDigest,omitempty"`
+ LastChecked int64 `json:"lastChecked"`
+ Error string `json:"error,omitempty"` // e.g., "rate limited", "auth required"
+}
+
+
// DockerContainerPortFrontend represents a container port mapping
type DockerContainerPortFrontend struct {
PrivatePort int `json:"privatePort"`
diff --git a/internal/monitoring/docker_commands.go b/internal/monitoring/docker_commands.go
index 424a2034cd..8fdd2f0d6c 100644
--- a/internal/monitoring/docker_commands.go
+++ b/internal/monitoring/docker_commands.go
@@ -13,6 +13,8 @@ import (
const (
// DockerCommandTypeStop instructs the agent to stop reporting and uninstall itself.
DockerCommandTypeStop = "stop"
+ // DockerCommandTypeUpdateContainer instructs the agent to update a container to its latest image.
+ DockerCommandTypeUpdateContainer = "update_container"
// DockerCommandStatusQueued indicates the command is queued and waiting to be dispatched.
DockerCommandStatusQueued = "queued"
@@ -151,6 +153,68 @@ func (m *Monitor) queueDockerStopCommand(hostID string) (models.DockerHostComman
return cmd.status, nil
}
+// QueueDockerContainerUpdateCommand enqueues an update command for a specific container.
+func (m *Monitor) QueueDockerContainerUpdateCommand(hostID, containerID, containerName string) (models.DockerHostCommandStatus, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ hostID = normalizeDockerHostID(hostID)
+ if hostID == "" {
+ return models.DockerHostCommandStatus{}, fmt.Errorf("docker host id is required")
+ }
+
+ containerID = strings.TrimSpace(containerID)
+ if containerID == "" {
+ return models.DockerHostCommandStatus{}, fmt.Errorf("container id is required")
+ }
+
+ // Ensure the host exists
+ var hostExists bool
+ for _, host := range m.state.GetDockerHosts() {
+ if host.ID == hostID {
+ hostExists = true
+ break
+ }
+ }
+ if !hostExists {
+ return models.DockerHostCommandStatus{}, fmt.Errorf("docker host %q not found", hostID)
+ }
+
+ // Check for existing commands in progress for this host
+ if existing, ok := m.dockerCommands[hostID]; ok {
+ switch existing.status.Status {
+ case DockerCommandStatusQueued, DockerCommandStatusDispatched, DockerCommandStatusAcknowledged:
+ return existing.status, fmt.Errorf("docker host %q already has a command in progress", hostID)
+ }
+ }
+
+ // Create payload with container information
+ payload := map[string]any{
+ "containerId": containerID,
+ "containerName": containerName,
+ }
+
+ cmd := newDockerHostCommand(DockerCommandTypeUpdateContainer, fmt.Sprintf("Updating container %s", containerName), dockerCommandDefaultTTL, payload)
+ if m.dockerCommands == nil {
+ m.dockerCommands = make(map[string]*dockerHostCommand)
+ }
+ m.dockerCommands[hostID] = &cmd
+ if m.dockerCommandIndex == nil {
+ m.dockerCommandIndex = make(map[string]string)
+ }
+ m.dockerCommandIndex[cmd.status.ID] = hostID
+
+ m.state.SetDockerHostCommand(hostID, &cmd.status)
+ log.Info().
+ Str("dockerHostID", hostID).
+ Str("containerId", containerID).
+ Str("containerName", containerName).
+ Str("commandID", cmd.status.ID).
+ Msg("Queued docker container update command")
+
+ return cmd.status, nil
+}
+
func (m *Monitor) getDockerCommandPayload(hostID string) (map[string]any, *models.DockerHostCommandStatus) {
m.mu.Lock()
defer m.mu.Unlock()
diff --git a/pkg/agents/docker/command.go b/pkg/agents/docker/command.go
index e1aabce7f7..b404620a19 100644
--- a/pkg/agents/docker/command.go
+++ b/pkg/agents/docker/command.go
@@ -23,6 +23,8 @@ type CommandAck struct {
const (
// CommandTypeStop instructs the agent to stop reporting and shut down.
CommandTypeStop = "stop"
+ // CommandTypeUpdateContainer instructs the agent to update a specific container to its latest image.
+ CommandTypeUpdateContainer = "update_container"
// CommandStatusAcknowledged indicates a command was received and is in progress.
CommandStatusAcknowledged = "acknowledged"