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: AI Patrol now respects exact user-configured thresholds

rcourtman3040800e7b17
diff --git a/internal/ai/patrol.go b/internal/ai/patrol.go
index a5bb0341ca..6196884052 100644
--- a/internal/ai/patrol.go
+++ b/internal/ai/patrol.go
@@ -63,8 +63,16 @@ func DefaultPatrolThresholds() PatrolThresholds {
}
// CalculatePatrolThresholds derives patrol thresholds from alert thresholds
-// Patrol warns ~10% BEFORE the alert fires so users can take action early
+// This is the default mode which now uses EXACT thresholds (matching user configuration).
+// For proactive/early warning mode, use CalculatePatrolThresholdsWithMode(provider, true).
func CalculatePatrolThresholds(provider ThresholdProvider) PatrolThresholds {
+ return CalculatePatrolThresholdsWithMode(provider, false)
+}
+
+// CalculatePatrolThresholdsWithMode derives patrol thresholds from alert thresholds
+// When proactiveMode is false (default): uses exact alert thresholds
+// When proactiveMode is true: warns 5-15% BEFORE alerts fire for early warning
+func CalculatePatrolThresholdsWithMode(provider ThresholdProvider, proactiveMode bool) PatrolThresholds {
if provider == nil {
return DefaultPatrolThresholds()
}
@@ -76,20 +84,40 @@ func CalculatePatrolThresholds(provider ThresholdProvider) PatrolThresholds {
guestDisk := provider.GetGuestDiskThreshold()
storage := provider.GetStorageThreshold()
- // Calculate patrol thresholds (watch = alert-15%, warning = alert-5%)
+ if proactiveMode {
+ // Proactive mode: warn BEFORE thresholds are reached
+ // watch = alert-15%, warning = alert-5%
+ return PatrolThresholds{
+ NodeCPUWatch: clampThreshold(nodeCPU - 15),
+ NodeCPUWarning: clampThreshold(nodeCPU - 5),
+ NodeMemWatch: clampThreshold(nodeMem - 15),
+ NodeMemWarning: clampThreshold(nodeMem - 5),
+ GuestMemWatch: clampThreshold(guestMem - 12),
+ GuestMemWarning: clampThreshold(guestMem - 5),
+ GuestDiskWatch: clampThreshold(guestDisk - 15),
+ GuestDiskWarn: clampThreshold(guestDisk - 8),
+ GuestDiskCrit: clampThreshold(guestDisk - 3),
+ StorageWatch: clampThreshold(storage - 15),
+ StorageWarning: clampThreshold(storage - 8),
+ StorageCritical: clampThreshold(storage - 3),
+ }
+ }
+
+ // Exact mode (default): use exact alert thresholds
+ // Watch is slightly below warning, warning is at threshold
return PatrolThresholds{
- NodeCPUWatch: clampThreshold(nodeCPU - 15),
- NodeCPUWarning: clampThreshold(nodeCPU - 5),
- NodeMemWatch: clampThreshold(nodeMem - 15),
- NodeMemWarning: clampThreshold(nodeMem - 5),
- GuestMemWatch: clampThreshold(guestMem - 12),
- GuestMemWarning: clampThreshold(guestMem - 5),
- GuestDiskWatch: clampThreshold(guestDisk - 15),
- GuestDiskWarn: clampThreshold(guestDisk - 8),
- GuestDiskCrit: clampThreshold(guestDisk - 3),
- StorageWatch: clampThreshold(storage - 15),
- StorageWarning: clampThreshold(storage - 8),
- StorageCritical: clampThreshold(storage - 3),
+ NodeCPUWatch: clampThreshold(nodeCPU - 5), // Watch slightly before threshold
+ NodeCPUWarning: nodeCPU, // Warning at exact threshold
+ NodeMemWatch: clampThreshold(nodeMem - 5),
+ NodeMemWarning: nodeMem,
+ GuestMemWatch: clampThreshold(guestMem - 5),
+ GuestMemWarning: guestMem,
+ GuestDiskWatch: clampThreshold(guestDisk - 5),
+ GuestDiskWarn: guestDisk,
+ GuestDiskCrit: guestDisk + 5, // Critical slightly above threshold
+ StorageWatch: clampThreshold(storage - 5),
+ StorageWarning: storage,
+ StorageCritical: storage + 5,
}
}
@@ -228,7 +256,8 @@ type PatrolService struct {
intelligence *Intelligence
// Cached thresholds (recalculated when thresholdProvider changes)
- thresholds PatrolThresholds
+ thresholds PatrolThresholds
+ proactiveMode bool // When true, warn before thresholds; when false, use exact thresholds
// Runtime state
running bool
@@ -310,19 +339,50 @@ func (p *PatrolService) SetConfig(cfg PatrolConfig) {
}
// SetThresholdProvider sets the provider for user-configured alert thresholds
-// This allows patrol to warn BEFORE alerts fire
+// This allows patrol to use user-configured thresholds for alerting
func (p *PatrolService) SetThresholdProvider(provider ThresholdProvider) {
p.mu.Lock()
defer p.mu.Unlock()
p.thresholdProvider = provider
- p.thresholds = CalculatePatrolThresholds(provider)
+ p.thresholds = CalculatePatrolThresholdsWithMode(provider, p.proactiveMode)
log.Debug().
Float64("storageWatch", p.thresholds.StorageWatch).
Float64("storageWarning", p.thresholds.StorageWarning).
Float64("storageCritical", p.thresholds.StorageCritical).
+ Bool("proactiveMode", p.proactiveMode).
Msg("Patrol thresholds updated from alert config")
}
+// SetProactiveMode configures whether patrol warns before thresholds (true) or at exact thresholds (false)
+func (p *PatrolService) SetProactiveMode(proactive bool) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.proactiveMode == proactive {
+ return // No change
+ }
+ p.proactiveMode = proactive
+ // Recalculate thresholds with new mode
+ p.thresholds = CalculatePatrolThresholdsWithMode(p.thresholdProvider, proactive)
+ log.Info().
+ Bool("proactiveMode", proactive).
+ Float64("storageWarning", p.thresholds.StorageWarning).
+ Msg("Patrol mode updated")
+}
+
+// GetProactiveMode returns whether proactive threshold mode is enabled
+func (p *PatrolService) GetProactiveMode() bool {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.proactiveMode
+}
+
+// GetThresholds returns the current patrol thresholds (for display in UI)
+func (p *PatrolService) GetThresholds() PatrolThresholds {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.thresholds
+}
+
// SetFindingsPersistence enables findings persistence (load from and save to disk)
// This should be called before Start() to load any existing findings
func (p *PatrolService) SetFindingsPersistence(persistence FindingsPersistence) error {
diff --git a/internal/ai/patrol_test.go b/internal/ai/patrol_test.go
index 76e1d60575..8e9297deb1 100644
--- a/internal/ai/patrol_test.go
+++ b/internal/ai/patrol_test.go
@@ -45,18 +45,44 @@ func TestCalculatePatrolThresholds_FromProvider(t *testing.T) {
storage: 70,
}
+ // Default mode (exact thresholds)
thresholds := CalculatePatrolThresholds(provider)
- // Watch thresholds should be alertThreshold - 15
- expectedNodeCPUWatch := 90 - 15
+ // Watch thresholds should be alertThreshold - 5 (slight buffer)
+ expectedNodeCPUWatch := 90 - 5
if thresholds.NodeCPUWatch != float64(expectedNodeCPUWatch) {
t.Errorf("Expected NodeCPUWatch %d, got %f", expectedNodeCPUWatch, thresholds.NodeCPUWatch)
}
+ // Warning thresholds should be EXACT alert threshold (new default behavior)
+ expectedNodeCPUWarning := 90.0
+ if thresholds.NodeCPUWarning != expectedNodeCPUWarning {
+ t.Errorf("Expected NodeCPUWarning %f, got %f", expectedNodeCPUWarning, thresholds.NodeCPUWarning)
+ }
+}
+
+func TestCalculatePatrolThresholds_ProactiveMode(t *testing.T) {
+ provider := &mockThresholdProvider{
+ nodeCPU: 90,
+ nodeMemory: 85,
+ guestMem: 80,
+ guestDisk: 75,
+ storage: 70,
+ }
+
+ // Proactive mode (warn before thresholds)
+ thresholds := CalculatePatrolThresholdsWithMode(provider, true)
+
+ // Watch thresholds should be alertThreshold - 15 (early warning)
+ expectedNodeCPUWatch := 90 - 15
+ if thresholds.NodeCPUWatch != float64(expectedNodeCPUWatch) {
+ t.Errorf("Expected NodeCPUWatch %d in proactive mode, got %f", expectedNodeCPUWatch, thresholds.NodeCPUWatch)
+ }
+
// Warning thresholds should be alertThreshold - 5
expectedNodeCPUWarning := 90 - 5
if thresholds.NodeCPUWarning != float64(expectedNodeCPUWarning) {
- t.Errorf("Expected NodeCPUWarning %d, got %f", expectedNodeCPUWarning, thresholds.NodeCPUWarning)
+ t.Errorf("Expected NodeCPUWarning %d in proactive mode, got %f", expectedNodeCPUWarning, thresholds.NodeCPUWarning)
}
}
@@ -214,16 +240,77 @@ func TestPatrolService_SetThresholdProvider(t *testing.T) {
ps.SetThresholdProvider(provider)
- // Verify thresholds were calculated
+ // Verify thresholds were calculated (default: exact mode)
ps.mu.RLock()
thresholds := ps.thresholds
ps.mu.RUnlock()
- // Watch = alert - 15
- expectedWatch := 95.0 - 15.0
+ // Watch = alert - 5 (slight buffer in exact mode)
+ expectedWatch := 95.0 - 5.0
if thresholds.NodeCPUWatch != expectedWatch {
t.Errorf("Expected NodeCPUWatch %f, got %f", expectedWatch, thresholds.NodeCPUWatch)
}
+
+ // Warning = exact alert threshold (new default)
+ expectedWarning := 95.0
+ if thresholds.NodeCPUWarning != expectedWarning {
+ t.Errorf("Expected NodeCPUWarning %f (exact threshold), got %f", expectedWarning, thresholds.NodeCPUWarning)
+ }
+}
+
+func TestPatrolService_SetProactiveMode(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+
+ provider := &mockThresholdProvider{
+ nodeCPU: 95,
+ nodeMemory: 90,
+ guestMem: 85,
+ guestDisk: 80,
+ storage: 75,
+ }
+
+ ps.SetThresholdProvider(provider)
+
+ // Enable proactive mode
+ ps.SetProactiveMode(true)
+
+ if !ps.GetProactiveMode() {
+ t.Error("Expected proactive mode to be true")
+ }
+
+ // Verify thresholds were recalculated for proactive mode
+ ps.mu.RLock()
+ thresholds := ps.thresholds
+ ps.mu.RUnlock()
+
+ // Watch = alert - 15 in proactive mode
+ expectedWatch := 95.0 - 15.0
+ if thresholds.NodeCPUWatch != expectedWatch {
+ t.Errorf("Expected NodeCPUWatch %f in proactive mode, got %f", expectedWatch, thresholds.NodeCPUWatch)
+ }
+
+ // Warning = alert - 5 in proactive mode
+ expectedWarning := 95.0 - 5.0
+ if thresholds.NodeCPUWarning != expectedWarning {
+ t.Errorf("Expected NodeCPUWarning %f in proactive mode, got %f", expectedWarning, thresholds.NodeCPUWarning)
+ }
+
+ // Disable proactive mode
+ ps.SetProactiveMode(false)
+
+ if ps.GetProactiveMode() {
+ t.Error("Expected proactive mode to be false")
+ }
+
+ // Verify thresholds were recalculated back to exact mode
+ ps.mu.RLock()
+ thresholds = ps.thresholds
+ ps.mu.RUnlock()
+
+ // Warning should be exact threshold again
+ if thresholds.NodeCPUWarning != 95.0 {
+ t.Errorf("Expected NodeCPUWarning 95 (exact threshold) after disabling proactive mode, got %f", thresholds.NodeCPUWarning)
+ }
}
func TestPatrolService_GetStatus(t *testing.T) {
diff --git a/internal/ai/service.go b/internal/ai/service.go
index 1354a47e37..ce88ab0ff0 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -474,6 +474,7 @@ func (s *Service) StartPatrol(ctx context.Context) {
AnalyzeStorage: cfg.PatrolAnalyzeStorage,
}
patrol.SetConfig(patrolCfg)
+ patrol.SetProactiveMode(cfg.UseProactiveThresholds)
patrol.Start(ctx)
// Configure alert-triggered analyzer (also Pro-only)
@@ -532,9 +533,13 @@ func (s *Service) ReconfigurePatrol() {
}
patrol.SetConfig(patrolCfg)
+ // Update proactive threshold mode
+ patrol.SetProactiveMode(cfg.UseProactiveThresholds)
+
log.Info().
Bool("enabled", patrolCfg.Enabled).
Dur("interval", patrolCfg.Interval).
+ Bool("proactiveThresholds", cfg.UseProactiveThresholds).
Msg("Patrol configuration updated")
// Update alert-triggered analyzer (re-check license on each config change)
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index 965168cd7f..e7f37bfbac 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -167,10 +167,11 @@ type AISettingsResponse struct {
AuthMethod string `json:"auth_method"` // "api_key" or "oauth"
OAuthConnected bool `json:"oauth_connected"` // true if OAuth tokens are configured
// Patrol settings for token efficiency
- PatrolSchedulePreset string `json:"patrol_schedule_preset"` // DEPRECATED: legacy preset
- PatrolIntervalMinutes int `json:"patrol_interval_minutes"` // Patrol interval in minutes (0 = disabled)
- PatrolAutoFix bool `json:"patrol_auto_fix"` // true if patrol can auto-fix issues
- AlertTriggeredAnalysis bool `json:"alert_triggered_analysis"` // true if AI analyzes when alerts fire
+ PatrolSchedulePreset string `json:"patrol_schedule_preset"` // DEPRECATED: legacy preset
+ PatrolIntervalMinutes int `json:"patrol_interval_minutes"` // Patrol interval in minutes (0 = disabled)
+ PatrolAutoFix bool `json:"patrol_auto_fix"` // true if patrol can auto-fix issues
+ AlertTriggeredAnalysis bool `json:"alert_triggered_analysis"` // true if AI analyzes when alerts fire
+ UseProactiveThresholds bool `json:"use_proactive_thresholds"` // true if patrol warns before thresholds (false = use exact thresholds)
AvailableModels []config.ModelInfo `json:"available_models"` // List of models for current provider
// Multi-provider credentials - shows which providers are configured
AnthropicConfigured bool `json:"anthropic_configured"` // true if Anthropic API key or OAuth is set
@@ -201,10 +202,11 @@ type AISettingsUpdateRequest struct {
CustomContext *string `json:"custom_context,omitempty"` // user-provided infrastructure context
AuthMethod *string `json:"auth_method,omitempty"` // "api_key" or "oauth"
// Patrol settings for token efficiency
- PatrolSchedulePreset *string `json:"patrol_schedule_preset,omitempty"` // DEPRECATED: use patrol_interval_minutes
- PatrolIntervalMinutes *int `json:"patrol_interval_minutes,omitempty"` // Custom interval in minutes (0 = disabled, minimum 10)
- PatrolAutoFix *bool `json:"patrol_auto_fix,omitempty"` // true if patrol can auto-fix issues
- AlertTriggeredAnalysis *bool `json:"alert_triggered_analysis,omitempty"` // true if AI analyzes when alerts fire
+ PatrolSchedulePreset *string `json:"patrol_schedule_preset,omitempty"` // DEPRECATED: use patrol_interval_minutes
+ PatrolIntervalMinutes *int `json:"patrol_interval_minutes,omitempty"` // Custom interval in minutes (0 = disabled, minimum 10)
+ PatrolAutoFix *bool `json:"patrol_auto_fix,omitempty"` // true if patrol can auto-fix issues
+ AlertTriggeredAnalysis *bool `json:"alert_triggered_analysis,omitempty"` // true if AI analyzes when alerts fire
+ UseProactiveThresholds *bool `json:"use_proactive_thresholds,omitempty"` // true if patrol warns before thresholds (default: false = exact thresholds)
// Multi-provider credentials
AnthropicAPIKey *string `json:"anthropic_api_key,omitempty"` // Set Anthropic API key
OpenAIAPIKey *string `json:"openai_api_key,omitempty"` // Set OpenAI API key
@@ -266,11 +268,12 @@ func (h *AISettingsHandler) HandleGetAISettings(w http.ResponseWriter, r *http.R
AuthMethod: authMethod,
OAuthConnected: settings.OAuthAccessToken != "",
// Patrol settings
- PatrolSchedulePreset: settings.PatrolSchedulePreset,
- PatrolIntervalMinutes: settings.PatrolIntervalMinutes,
- PatrolAutoFix: settings.PatrolAutoFix,
- AlertTriggeredAnalysis: settings.AlertTriggeredAnalysis,
- AvailableModels: nil, // Now populated via /api/ai/models endpoint
+ PatrolSchedulePreset: settings.PatrolSchedulePreset,
+ PatrolIntervalMinutes: settings.PatrolIntervalMinutes,
+ PatrolAutoFix: settings.PatrolAutoFix,
+ AlertTriggeredAnalysis: settings.AlertTriggeredAnalysis,
+ UseProactiveThresholds: settings.UseProactiveThresholds,
+ AvailableModels: nil, // Now populated via /api/ai/models endpoint
// Multi-provider configuration
AnthropicConfigured: settings.HasProvider(config.AIProviderAnthropic),
OpenAIConfigured: settings.HasProvider(config.AIProviderOpenAI),
@@ -384,6 +387,10 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt
settings.PatrolAutoFix = *req.PatrolAutoFix
}
+ if req.UseProactiveThresholds != nil {
+ settings.UseProactiveThresholds = *req.UseProactiveThresholds
+ }
+
if req.BaseURL != nil {
settings.BaseURL = strings.TrimSpace(*req.BaseURL)
}
@@ -561,11 +568,12 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt
CustomContext: settings.CustomContext,
AuthMethod: authMethod,
OAuthConnected: settings.OAuthAccessToken != "",
- PatrolSchedulePreset: settings.PatrolSchedulePreset,
- PatrolIntervalMinutes: settings.PatrolIntervalMinutes,
- PatrolAutoFix: settings.PatrolAutoFix,
- AlertTriggeredAnalysis: settings.AlertTriggeredAnalysis,
- AvailableModels: nil, // Now populated via /api/ai/models endpoint
+ PatrolSchedulePreset: settings.PatrolSchedulePreset,
+ PatrolIntervalMinutes: settings.PatrolIntervalMinutes,
+ PatrolAutoFix: settings.PatrolAutoFix,
+ AlertTriggeredAnalysis: settings.AlertTriggeredAnalysis,
+ UseProactiveThresholds: settings.UseProactiveThresholds,
+ AvailableModels: nil, // Now populated via /api/ai/models endpoint
// Multi-provider configuration
AnthropicConfigured: settings.HasProvider(config.AIProviderAnthropic),
OpenAIConfigured: settings.HasProvider(config.AIProviderOpenAI),
diff --git a/internal/config/ai.go b/internal/config/ai.go
index 7fa35a8a96..95f81119e4 100644
--- a/internal/config/ai.go
+++ b/internal/config/ai.go
@@ -48,6 +48,7 @@ type AIConfig struct {
PatrolAnalyzeDocker bool `json:"patrol_analyze_docker"` // Include Docker hosts in patrol
PatrolAnalyzeStorage bool `json:"patrol_analyze_storage"` // Include storage in patrol
PatrolAutoFix bool `json:"patrol_auto_fix,omitempty"` // When true, patrol can attempt automatic remediation (default: false, observe only)
+ UseProactiveThresholds bool `json:"use_proactive_thresholds,omitempty"` // When true, patrol warns 5-15% BEFORE alert thresholds (default: false, use exact thresholds)
AutoFixModel string `json:"auto_fix_model,omitempty"` // Model for automatic remediation (defaults to PatrolModel, may want more capable model)
// Alert-triggered AI analysis - analyze specific resources when alerts fire
diff --git a/internal/dockeragent/agent.go b/internal/dockeragent/agent.go
index 4da036c75a..3cdcf7b691 100644
--- a/internal/dockeragent/agent.go
+++ b/internal/dockeragent/agent.go
@@ -17,10 +17,8 @@ import (
"os"
"os/exec"
"path/filepath"
- "runtime"
"strconv"
"strings"
- "syscall"
"time"
containertypes "github.com/docker/docker/api/types/container"
@@ -28,7 +26,6 @@ import (
systemtypes "github.com/docker/docker/api/types/system"
"github.com/docker/docker/client"
"github.com/rcourtman/pulse-go-rewrite/internal/buffer"
- "github.com/rcourtman/pulse-go-rewrite/internal/hostmetrics"
"github.com/rcourtman/pulse-go-rewrite/internal/utils"
agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker"
"github.com/rs/zerolog"
@@ -86,7 +83,7 @@ const (
// Agent collects Docker metrics and posts them to Pulse.
type Agent struct {
cfg Config
- docker *client.Client
+ docker dockerClient
daemonHost string
daemonID string // Cached at init; Podman can return unstable IDs across calls
runtime RuntimeKind
@@ -183,7 +180,7 @@ func New(cfg Config) (*Agent, error) {
return nil, err
}
- dockerClient, info, runtimeKind, err := connectRuntime(runtimePref, logger)
+ dockerClient, info, runtimeKind, err := connectRuntimeFn(runtimePref, logger)
if err != nil {
return nil, err
}
@@ -357,8 +354,8 @@ type runtimeCandidate struct {
applyDockerEnv bool
}
-func connectRuntime(preference RuntimeKind, logger *zerolog.Logger) (*client.Client, systemtypes.Info, RuntimeKind, error) {
- candidates := buildRuntimeCandidates(preference)
+func connectRuntime(preference RuntimeKind, logger *zerolog.Logger) (dockerClient, systemtypes.Info, RuntimeKind, error) {
+ candidates := buildRuntimeCandidatesFn(preference)
var attempts []string
for _, candidate := range candidates {
@@ -370,7 +367,7 @@ func connectRuntime(preference RuntimeKind, logger *zerolog.Logger) (*client.Cli
opts = append(opts, client.WithHost(candidate.host))
}
- cli, info, err := tryRuntimeCandidate(opts)
+ cli, info, err := tryRuntimeCandidateFn(opts)
if err != nil {
attempts = append(attempts, fmt.Sprintf("%s: %v", candidate.label, err))
continue
@@ -399,8 +396,8 @@ func connectRuntime(preference RuntimeKind, logger *zerolog.Logger) (*client.Cli
return nil, systemtypes.Info{}, RuntimeAuto, fmt.Errorf("failed to connect to container runtime: %s", strings.Join(attempts, "; "))
}
-func tryRuntimeCandidate(opts []client.Opt) (*client.Client, systemtypes.Info, error) {
- cli, err := client.NewClientWithOpts(opts...)
+func tryRuntimeCandidate(opts []client.Opt) (dockerClient, systemtypes.Info, error) {
+ cli, err := newDockerClientFn(opts...)
if err != nil {
return nil, systemtypes.Info{}, err
}
@@ -529,7 +526,7 @@ func (a *Agent) Run(ctx context.Context) error {
a.cfg.Interval = interval
}
- ticker := time.NewTicker(interval)
+ ticker := newTickerFn(interval)
defer ticker.Stop()
const (
@@ -538,8 +535,8 @@ func (a *Agent) Run(ctx context.Context) error {
recurringJitterWindow = 5 * time.Minute
)
- initialDelay := 5*time.Second + randomDuration(startupJitterWindow)
- updateTimer := time.NewTimer(initialDelay)
+ initialDelay := 5*time.Second + randomDurationFn(startupJitterWindow)
+ updateTimer := newTimerFn(initialDelay)
defer func() {
if !updateTimer.Stop() {
select {
@@ -575,7 +572,7 @@ func (a *Agent) Run(ctx context.Context) error {
}
case <-updateTimer.C:
go a.checkForUpdates(ctx)
- nextDelay := updateInterval + randomDuration(recurringJitterWindow)
+ nextDelay := updateInterval + randomDurationFn(recurringJitterWindow)
if nextDelay <= 0 {
nextDelay = updateInterval
}
@@ -686,7 +683,7 @@ func (a *Agent) buildReport(ctx context.Context) (agentsdocker.Report, error) {
uptime := readSystemUptime()
metricsCtx, metricsCancel := context.WithTimeout(ctx, 10*time.Second)
- snapshot, err := hostmetrics.Collect(metricsCtx, nil)
+ snapshot, err := hostmetricsCollect(metricsCtx, nil)
metricsCancel()
if err != nil {
return agentsdocker.Report{}, fmt.Errorf("collect host metrics: %w", err)
@@ -1616,13 +1613,8 @@ func (a *Agent) Close() error {
}
func readMachineID() (string, error) {
- paths := []string{
- "/etc/machine-id",
- "/var/lib/dbus/machine-id",
- }
-
- for _, path := range paths {
- data, err := os.ReadFile(path)
+ for _, path := range machineIDPaths {
+ data, err := osReadFileFn(path)
if err == nil {
return strings.TrimSpace(string(data)), nil
}
@@ -1749,7 +1741,7 @@ func (a *Agent) checkForUpdates(ctx context.Context) {
Msg("New agent version available, performing self-update")
// Perform self-update
- if err := a.selfUpdate(ctx); err != nil {
+ if err := selfUpdateFunc(a, ctx); err != nil {
a.logger.Error().Err(err).Msg("Failed to self-update agent")
return
}
@@ -1759,7 +1751,7 @@ func (a *Agent) checkForUpdates(ctx context.Context) {
// isUnraid checks if we're running on Unraid by looking for /etc/unraid-version
func isUnraid() bool {
- _, err := os.Stat("/etc/unraid-version")
+ _, err := osStatFn(unraidVersionPath)
return err == nil
}
@@ -1790,7 +1782,7 @@ func verifyELFMagic(path string) error {
}
func determineSelfUpdateArch() string {
- switch runtime.GOARCH {
+ switch goArch {
case "amd64":
return "linux-amd64"
case "arm64":
@@ -1799,12 +1791,12 @@ func determineSelfUpdateArch() string {
return "linux-armv7"
}
- out, err := exec.Command("uname", "-m").Output()
+ out, err := unameMachine()
if err != nil {
return ""
}
- normalized := strings.ToLower(strings.TrimSpace(string(out)))
+ normalized := strings.ToLower(strings.TrimSpace(out))
switch normalized {
case "x86_64", "amd64":
return "linux-amd64"
@@ -1825,7 +1817,7 @@ func (a *Agent) selfUpdate(ctx context.Context) error {
}
// Get path to current executable
- execPath, err := os.Executable()
+ execPath, err := osExecutableFn()
if err != nil {
return fmt.Errorf("failed to get executable path: %w", err)
}
@@ -1912,12 +1904,12 @@ func (a *Agent) selfUpdate(ctx context.Context) error {
// Create temporary file in the same directory as the target binary
// to ensure atomic rename works (os.Rename fails across filesystems)
targetDir := filepath.Dir(realExecPath)
- tmpFile, err := os.CreateTemp(targetDir, "pulse-docker-agent-*.tmp")
+ tmpFile, err := osCreateTempFn(targetDir, "pulse-docker-agent-*.tmp")
if err != nil {
return fmt.Errorf("failed to create temp file in %s: %w", targetDir, err)
}
tmpPath := tmpFile.Name()
- defer os.Remove(tmpPath) // Clean up if something goes wrong
+ defer osRemoveFn(tmpPath) // Clean up if something goes wrong
// Write downloaded binary to temp file with size limit (100 MB max)
const maxBinarySize = 100 * 1024 * 1024
@@ -1955,38 +1947,38 @@ func (a *Agent) selfUpdate(ctx context.Context) error {
a.logger.Debug().Str("checksum", downloadChecksum).Msg("Self-update: checksum verified")
// Make temp file executable
- if err := os.Chmod(tmpPath, 0755); err != nil {
+ if err := osChmodFn(tmpPath, 0755); err != nil {
return fmt.Errorf("failed to make temp file executable: %w", err)
}
// Create backup of current binary (use realExecPath for atomic operations)
backupPath := realExecPath + ".backup"
- if err := os.Rename(realExecPath, backupPath); err != nil {
+ if err := osRenameFn(realExecPath, backupPath); err != nil {
return fmt.Errorf("failed to backup current binary: %w", err)
}
// Move new binary to current location
- if err := os.Rename(tmpPath, realExecPath); err != nil {
+ if err := osRenameFn(tmpPath, realExecPath); err != nil {
// Restore backup on failure
- os.Rename(backupPath, realExecPath)
+ _ = osRenameFn(backupPath, realExecPath)
return fmt.Errorf("failed to replace binary: %w", err)
}
// Remove backup on success
- os.Remove(backupPath)
+ _ = osRemoveFn(backupPath)
// On Unraid, also update the persistent copy on the flash drive
if isUnraid() {
- persistPath := "/boot/config/plugins/pulse-docker-agent/pulse-docker-agent"
- if _, err := os.Stat(persistPath); err == nil {
+ persistPath := unraidPersistPath
+ if _, err := osStatFn(persistPath); err == nil {
a.logger.Debug().Str("path", persistPath).Msg("Updating Unraid persistent binary")
- if newBinary, err := os.ReadFile(execPath); err == nil {
+ if newBinary, err := osReadFileFn(execPath); err == nil {
tmpPersist := persistPath + ".tmp"
- if err := os.WriteFile(tmpPersist, newBinary, 0644); err != nil {
+ if err := osWriteFileFn(tmpPersist, newBinary, 0644); err != nil {
a.logger.Warn().Err(err).Msg("Failed to write Unraid persistent binary")
- } else if err := os.Rename(tmpPersist, persistPath); err != nil {
+ } else if err := osRenameFn(tmpPersist, persistPath); err != nil {
a.logger.Warn().Err(err).Msg("Failed to rename Unraid persistent binary")
- os.Remove(tmpPersist)
+ _ = osRemoveFn(tmpPersist)
} else {
a.logger.Info().Str("path", persistPath).Msg("Updated Unraid persistent binary")
}
@@ -1998,7 +1990,7 @@ func (a *Agent) selfUpdate(ctx context.Context) error {
args := os.Args
env := os.Environ()
- if err := syscall.Exec(execPath, args, env); err != nil {
+ if err := syscallExecFn(execPath, args, env); err != nil {
return fmt.Errorf("failed to restart agent: %w", err)
}
diff --git a/internal/dockeragent/container_update.go b/internal/dockeragent/container_update.go
index 28afbde016..d105e42b8a 100644
--- a/internal/dockeragent/container_update.go
+++ b/internal/dockeragent/container_update.go
@@ -121,7 +121,7 @@ func (a *Agent) updateContainer(ctx context.Context, containerID string) Contain
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")
+ backupName := result.ContainerName + "_pulse_backup_" + nowFn().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")
@@ -220,7 +220,7 @@ func (a *Agent) updateContainer(ctx context.Context, containerID string) Contain
// 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)
+ sleepFn(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")
diff --git a/internal/dockeragent/deps.go b/internal/dockeragent/deps.go
new file mode 100644
index 0000000000..84c6653d35
--- /dev/null
+++ b/internal/dockeragent/deps.go
@@ -0,0 +1,58 @@
+package dockeragent
+
+import (
+ "context"
+ "io"
+ "os"
+ "os/exec"
+ "runtime"
+ "syscall"
+ "time"
+
+ "github.com/docker/docker/client"
+ "github.com/rcourtman/pulse-go-rewrite/internal/hostmetrics"
+)
+
+var (
+ connectRuntimeFn = connectRuntime
+ hostmetricsCollect = hostmetrics.Collect
+ newTickerFn = time.NewTicker
+ newTimerFn = time.NewTimer
+ randomDurationFn = randomDuration
+ nowFn = time.Now
+ sleepFn = time.Sleep
+ buildRuntimeCandidatesFn = buildRuntimeCandidates
+ tryRuntimeCandidateFn = tryRuntimeCandidate
+ osExecutableFn = os.Executable
+ osCreateTempFn = os.CreateTemp
+ osRenameFn = os.Rename
+ osChmodFn = os.Chmod
+ osRemoveFn = os.Remove
+ osReadFileFn = os.ReadFile
+ osWriteFileFn = os.WriteFile
+ osStatFn = os.Stat
+ syscallExecFn = syscall.Exec
+ goArch = runtime.GOARCH
+ unameMachine = func() (string, error) {
+ out, err := exec.Command("uname", "-m").Output()
+ if err != nil {
+ return "", err
+ }
+ return string(out), nil
+ }
+ machineIDPaths = []string{
+ "/etc/machine-id",
+ "/var/lib/dbus/machine-id",
+ }
+ unraidVersionPath = "/etc/unraid-version"
+ unraidPersistPath = "/boot/config/plugins/pulse-docker-agent/pulse-docker-agent"
+ openProcUptime = func() (io.ReadCloser, error) {
+ return os.Open("/proc/uptime")
+ }
+ newDockerClientFn = func(opts ...client.Opt) (dockerClient, error) {
+ return client.NewClientWithOpts(opts...)
+ }
+ selfUpdateFunc = func(a *Agent, ctx context.Context) error {
+ return a.selfUpdate(ctx)
+ }
+)
diff --git a/internal/dockeragent/docker_client.go b/internal/dockeragent/docker_client.go
new file mode 100644
index 0000000000..66da443791
--- /dev/null
+++ b/internal/dockeragent/docker_client.go
@@ -0,0 +1,32 @@
+package dockeragent
+
+import (
+ "context"
+ "io"
+
+ containertypes "github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/api/types/image"
+ "github.com/docker/docker/api/types/network"
+ swarmtypes "github.com/docker/docker/api/types/swarm"
+ systemtypes "github.com/docker/docker/api/types/system"
+ "github.com/opencontainers/image-spec/specs-go/v1"
+)
+
+type dockerClient interface {
+ Info(ctx context.Context) (systemtypes.Info, error)
+ DaemonHost() string
+ ContainerList(ctx context.Context, options containertypes.ListOptions) ([]containertypes.Summary, error)
+ ContainerInspectWithRaw(ctx context.Context, containerID string, size bool) (containertypes.InspectResponse, []byte, error)
+ ContainerStatsOneShot(ctx context.Context, containerID string) (containertypes.StatsResponseReader, error)
+ ContainerInspect(ctx context.Context, containerID string) (containertypes.InspectResponse, error)
+ ImagePull(ctx context.Context, ref string, options image.PullOptions) (io.ReadCloser, error)
+ ContainerStop(ctx context.Context, containerID string, options containertypes.StopOptions) error
+ ContainerRename(ctx context.Context, containerID, newName string) error
+ ContainerCreate(ctx context.Context, config *containertypes.Config, hostConfig *containertypes.HostConfig, networkingConfig *network.NetworkingConfig, platform *v1.Platform, containerName string) (containertypes.CreateResponse, error)
+ NetworkConnect(ctx context.Context, networkID, containerID string, config *network.EndpointSettings) error
+ ContainerStart(ctx context.Context, containerID string, options containertypes.StartOptions) error
+ ContainerRemove(ctx context.Context, containerID string, options containertypes.RemoveOptions) error
+ ServiceList(ctx context.Context, options swarmtypes.ServiceListOptions) ([]swarmtypes.Service, error)
+ TaskList(ctx context.Context, options swarmtypes.TaskListOptions) ([]swarmtypes.Task, error)
+ Close() error
+}
diff --git a/internal/dockeragent/registry_coverage_test.go b/internal/dockeragent/registry_coverage_test.go
new file mode 100644
index 0000000000..d68273df33
--- /dev/null
+++ b/internal/dockeragent/registry_coverage_test.go
@@ -0,0 +1,497 @@
+package dockeragent
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rs/zerolog"
+)
+
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
+ return f(req)
+}
+
+type errReadCloser struct {
+ err error
+}
+
+func (e errReadCloser) Read(_ []byte) (int, error) {
+ return 0, e.err
+}
+
+func (e errReadCloser) Close() error {
+ return nil
+}
+
+func newStringResponse(status int, headers map[string]string, body string) *http.Response {
+ resp := &http.Response{
+ StatusCode: status,
+ Header: make(http.Header),
+ Body: io.NopCloser(strings.NewReader(body)),
+ }
+ for key, value := range headers {
+ resp.Header.Set(key, value)
+ }
+ return resp
+}
+
+func TestRegistryChecker_CheckImageUpdate_CacheHits(t *testing.T) {
+ logger := zerolog.Nop()
+
+ t.Run("cached error", func(t *testing.T) {
+ checker := NewRegistryChecker(logger)
+ cacheKey := "example.test/repo:tag"
+ checker.cacheError(cacheKey, "cached error")
+
+ result := checker.CheckImageUpdate(context.Background(), "example.test/repo:tag", "sha256:current")
+ if result == nil {
+ t.Fatal("Expected result for cached error")
+ }
+ if result.Error != "cached error" {
+ t.Errorf("Expected cached error, got %q", result.Error)
+ }
+ if result.UpdateAvailable {
+ t.Error("Expected no update when cached error is present")
+ }
+ })
+
+ t.Run("cached digest", func(t *testing.T) {
+ checker := NewRegistryChecker(logger)
+ cacheKey := "example.test/repo:tag"
+ checker.cacheDigest(cacheKey, "sha256:latest")
+
+ result := checker.CheckImageUpdate(context.Background(), "example.test/repo:tag", "sha256:current")
+ if result == nil {
+ t.Fatal("Expected result for cached digest")
+ }
+ if result.LatestDigest != "sha256:latest" {
+ t.Errorf("Expected latest digest sha256:latest, got %q", result.LatestDigest)
+ }
+ if !result.UpdateAvailable {
+ t.Error("Expected update available for cached digest")
+ }
+ })
+}
+
+func TestRegistryChecker_CheckImageUpdate_FetchPaths(t *testing.T) {
+ logger := zerolog.Nop()
+
+ t.Run("fetch error caches error", func(t *testing.T) {
+ checker := NewRegistryChecker(logger)
+ checker.httpClient = &http.Client{
+ Transport: roundTripFunc(func(_ *http.Request) (*http.Response, error) {
+ return newStringResponse(http.StatusInternalServerError, nil, ""), nil
+ }),
+ }
+
+ result := checker.CheckImageUpdate(context.Background(), "example.test/repo:tag", "sha256:current")
+ if result == nil {
+ t.Fatal("Expected result on fetch error")
+ }
+ if result.Error != "registry error: 500" {
+ t.Fatalf("Expected registry error, got %q", result.Error)
+ }
+
+ cacheKey := "example.test/repo:tag"
+ cached := checker.getCached(cacheKey)
+ if cached == nil || cached.err != "registry error: 500" {
+ t.Fatalf("Expected cached error to be stored, got %+v", cached)
+ }
+ })
+
+ t.Run("fetch success caches digest", func(t *testing.T) {
+ checker := NewRegistryChecker(logger)
+ checker.httpClient = &http.Client{
+ Transport: roundTripFunc(func(_ *http.Request) (*http.Response, error) {
+ headers := map[string]string{
+ "Docker-Content-Digest": "sha256:latest",
+ }
+ return newStringResponse(http.StatusOK, headers, ""), nil
+ }),
+ }
+
+ result := checker.CheckImageUpdate(context.Background(), "example.test/repo:tag", "sha256:current")
+ if result == nil {
+ t.Fatal("Expected result on fetch success")
+ }
+ if result.LatestDigest != "sha256:latest" {
+ t.Fatalf("Expected latest digest sha256:latest, got %q", result.LatestDigest)
+ }
+ if !result.UpdateAvailable {
+ t.Fatal("Expected update available for new digest")
+ }
+
+ cacheKey := "example.test/repo:tag"
+ cached := checker.getCached(cacheKey)
+ if cached == nil || cached.latestDigest != "sha256:latest" {
+ t.Fatalf("Expected cached digest to be stored, got %+v", cached)
+ }
+ })
+}
+
+func TestRegistryChecker_GetCached_ExpiredEntry(t *testing.T) {
+ checker := NewRegistryChecker(zerolog.Nop())
+ checker.cache.entries["expired"] = cacheEntry{
+ latestDigest: "sha256:old",
+ expiresAt: time.Now().Add(-time.Minute),
+ }
+
+ if got := checker.getCached("expired"); got != nil {
+ t.Fatalf("Expected expired cache entry to return nil, got %+v", got)
+ }
+}
+
+func TestRegistryChecker_FetchDigest_StatusErrors(t *testing.T) {
+ tests := []struct {
+ name string
+ status int
+ wantErr string
+ }{
+ {
+ name: "unauthorized",
+ status: http.StatusUnauthorized,
+ wantErr: "authentication required",
+ },
+ {
+ name: "not found",
+ status: http.StatusNotFound,
+ wantErr: "image not found",
+ },
+ {
+ name: "rate limited",
+ status: http.StatusTooManyRequests,
+ wantErr: "rate limited",
+ },
+ {
+ name: "registry error",
+ status: http.StatusInternalServerError,
+ wantErr: "registry error: 500",
+ },
+ {
+ name: "missing digest",
+ status: http.StatusOK,
+ wantErr: "no digest in response",
+ },
+ }
+
+ expectedAccept := strings.Join([]string{
+ "application/vnd.docker.distribution.manifest.list.v2+json",
+ "application/vnd.docker.distribution.manifest.v2+json",
+ "application/vnd.oci.image.manifest.v1+json",
+ "application/vnd.oci.image.index.v1+json",
+ }, ", ")
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ var gotAccept string
+ checker := &RegistryChecker{
+ httpClient: &http.Client{
+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ gotAccept = req.Header.Get("Accept")
+ return newStringResponse(tt.status, nil, ""), nil
+ }),
+ },
+ }
+
+ _, err := checker.fetchDigest(context.Background(), "example.test", "repo", "tag")
+ if err == nil || err.Error() != tt.wantErr {
+ t.Fatalf("Expected error %q, got %v", tt.wantErr, err)
+ }
+ if gotAccept != expectedAccept {
+ t.Fatalf("Expected Accept header %q, got %q", expectedAccept, gotAccept)
+ }
+ })
+ }
+}
+
+func TestRegistryChecker_FetchDigest_RequestError(t *testing.T) {
+ checker := &RegistryChecker{
+ httpClient: &http.Client{
+ Transport: roundTripFunc(func(_ *http.Request) (*http.Response, error) {
+ return nil, errors.New("boom")
+ }),
+ },
+ }
+
+ _, err := checker.fetchDigest(context.Background(), "example.test", "repo", "tag")
+ if err == nil || !strings.Contains(err.Error(), "request:") {
+ t.Fatalf("Expected request error, got %v", err)
+ }
+}
+
+func TestRegistryChecker_FetchDigest_RequestCreationError(t *testing.T) {
+ checker := &RegistryChecker{httpClient: &http.Client{}}
+
+ _, err := checker.fetchDigest(context.Background(), "bad host", "repo", "tag")
+ if err == nil || !strings.Contains(err.Error(), "create request:") {
+ t.Fatalf("Expected create request error, got %v", err)
+ }
+}
+
+func TestRegistryChecker_FetchDigest_DigestHeaders(t *testing.T) {
+ expectedAccept := strings.Join([]string{
+ "application/vnd.docker.distribution.manifest.list.v2+json",
+ "application/vnd.docker.distribution.manifest.v2+json",
+ "application/vnd.oci.image.manifest.v1+json",
+ "application/vnd.oci.image.index.v1+json",
+ }, ", ")
+
+ t.Run("docker content digest header", func(t *testing.T) {
+ var gotAccept string
+ checker := &RegistryChecker{
+ httpClient: &http.Client{
+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ gotAccept = req.Header.Get("Accept")
+ headers := map[string]string{
+ "Docker-Content-Digest": "sha256:abc123",
+ }
+ return newStringResponse(http.StatusOK, headers, ""), nil
+ }),
+ },
+ }
+
+ digest, err := checker.fetchDigest(context.Background(), "example.test", "repo", "tag")
+ if err != nil {
+ t.Fatalf("Expected digest, got error %v", err)
+ }
+ if digest != "sha256:abc123" {
+ t.Fatalf("Expected digest sha256:abc123, got %q", digest)
+ }
+ if gotAccept != expectedAccept {
+ t.Fatalf("Expected Accept header %q, got %q", expectedAccept, gotAccept)
+ }
+ })
+
+ t.Run("etag digest header", func(t *testing.T) {
+ checker := &RegistryChecker{
+ httpClient: &http.Client{
+ Transport: roundTripFunc(func(_ *http.Request) (*http.Response, error) {
+ headers := map[string]string{
+ "Etag": "\"sha256:etag\"",
+ }
+ return newStringResponse(http.StatusOK, headers, ""), nil
+ }),
+ },
+ }
+
+ digest, err := checker.fetchDigest(context.Background(), "example.test", "repo", "tag")
+ if err != nil {
+ t.Fatalf("Expected digest, got error %v", err)
+ }
+ if digest != "sha256:etag" {
+ t.Fatalf("Expected digest sha256:etag, got %q", digest)
+ }
+ })
+}
+
+func TestRegistryChecker_FetchDigest_AuthPaths(t *testing.T) {
+ t.Run("auth token error", func(t *testing.T) {
+ checker := &RegistryChecker{
+ httpClient: &http.Client{
+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ if req.URL.Host == "auth.docker.io" {
+ return newStringResponse(http.StatusInternalServerError, nil, ""), nil
+ }
+ return nil, errors.New("unexpected manifest request")
+ }),
+ },
+ }
+
+ _, err := checker.fetchDigest(context.Background(), "registry-1.docker.io", "library/nginx", "latest")
+ if err == nil || err.Error() != "auth: token request failed: 500" {
+ t.Fatalf("Expected auth error, got %v", err)
+ }
+ })
+
+ t.Run("auth token header set", func(t *testing.T) {
+ var gotAuth string
+ checker := &RegistryChecker{
+ httpClient: &http.Client{
+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ switch req.URL.Host {
+ case "auth.docker.io":
+ return newStringResponse(http.StatusOK, nil, `{"token":"token123"}`), nil
+ case "registry-1.docker.io":
+ gotAuth = req.Header.Get("Authorization")
+ headers := map[string]string{
+ "Docker-Content-Digest": "sha256:latest",
+ }
+ return newStringResponse(http.StatusOK, headers, ""), nil
+ default:
+ return nil, errors.New("unexpected host")
+ }
+ }),
+ },
+ }
+
+ digest, err := checker.fetchDigest(context.Background(), "registry-1.docker.io", "library/nginx", "latest")
+ if err != nil {
+ t.Fatalf("Expected digest, got error %v", err)
+ }
+ if digest != "sha256:latest" {
+ t.Fatalf("Expected digest sha256:latest, got %q", digest)
+ }
+ if gotAuth != "Bearer token123" {
+ t.Fatalf("Expected Authorization header, got %q", gotAuth)
+ }
+ })
+}
+
+func TestRegistryChecker_GetAuthToken(t *testing.T) {
+ t.Run("docker hub", func(t *testing.T) {
+ var gotURL string
+ checker := &RegistryChecker{
+ httpClient: &http.Client{
+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ gotURL = req.URL.String()
+ return newStringResponse(http.StatusOK, nil, `{"token":"dockertoken"}`), nil
+ }),
+ },
+ }
+
+ token, err := checker.getAuthToken(context.Background(), "registry-1.docker.io", "library/nginx")
+ if err != nil {
+ t.Fatalf("Expected token, got error %v", err)
+ }
+ if token != "dockertoken" {
+ t.Fatalf("Expected dockertoken, got %q", token)
+ }
+ if !strings.Contains(gotURL, "service=registry.docker.io") || !strings.Contains(gotURL, "scope=repository:library/nginx:pull") {
+ t.Fatalf("Unexpected token URL %q", gotURL)
+ }
+ })
+
+ t.Run("ghcr", func(t *testing.T) {
+ var gotURL string
+ checker := &RegistryChecker{
+ httpClient: &http.Client{
+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ gotURL = req.URL.String()
+ return newStringResponse(http.StatusOK, nil, `{"token":"ghcrtoken"}`), nil
+ }),
+ },
+ }
+
+ token, err := checker.getAuthToken(context.Background(), "ghcr.io", "owner/repo")
+ if err != nil {
+ t.Fatalf("Expected token, got error %v", err)
+ }
+ if token != "ghcrtoken" {
+ t.Fatalf("Expected ghcrtoken, got %q", token)
+ }
+ if !strings.Contains(gotURL, "service=ghcr.io") || !strings.Contains(gotURL, "scope=repository:owner/repo:pull") {
+ t.Fatalf("Unexpected token URL %q", gotURL)
+ }
+ })
+
+ t.Run("other registry", func(t *testing.T) {
+ checker := &RegistryChecker{}
+ token, err := checker.getAuthToken(context.Background(), "example.test", "repo")
+ if err != nil {
+ t.Fatalf("Expected nil error, got %v", err)
+ }
+ if token != "" {
+ t.Fatalf("Expected empty token, got %q", token)
+ }
+ })
+}
+
+func TestRegistryChecker_FetchAuthToken(t *testing.T) {
+ t.Run("bad url", func(t *testing.T) {
+ checker := &RegistryChecker{httpClient: &http.Client{}}
+ _, err := checker.fetchAuthToken(context.Background(), "http://bad host")
+ if err == nil {
+ t.Fatal("Expected error for bad URL")
+ }
+ })
+
+ t.Run("request error", func(t *testing.T) {
+ checker := &RegistryChecker{
+ httpClient: &http.Client{
+ Transport: roundTripFunc(func(_ *http.Request) (*http.Response, error) {
+ return nil, errors.New("transport failure")
+ }),
+ },
+ }
+
+ _, err := checker.fetchAuthToken(context.Background(), "https://auth.example.test/token")
+ if err == nil {
+ t.Fatal("Expected request error")
+ }
+ })
+
+ t.Run("status error", func(t *testing.T) {
+ checker := &RegistryChecker{
+ httpClient: &http.Client{
+ Transport: roundTripFunc(func(_ *http.Request) (*http.Response, error) {
+ return newStringResponse(http.StatusInternalServerError, nil, ""), nil
+ }),
+ },
+ }
+
+ _, err := checker.fetchAuthToken(context.Background(), "https://auth.example.test/token")
+ if err == nil || err.Error() != "token request failed: 500" {
+ t.Fatalf("Expected status error, got %v", err)
+ }
+ })
+
+ t.Run("read error", func(t *testing.T) {
+ checker := &RegistryChecker{
+ httpClient: &http.Client{
+ Transport: roundTripFunc(func(_ *http.Request) (*http.Response, error) {
+ resp := &http.Response{
+ StatusCode: http.StatusOK,
+ Header: make(http.Header),
+ Body: errReadCloser{err: errors.New("read failure")},
+ }
+ return resp, nil
+ }),
+ },
+ }
+
+ _, err := checker.fetchAuthToken(context.Background(), "https://auth.example.test/token")
+ if err == nil {
+ t.Fatal("Expected read error")
+ }
+ })
+
+ t.Run("invalid json", func(t *testing.T) {
+ checker := &RegistryChecker{
+ httpClient: &http.Client{
+ Transport: roundTripFunc(func(_ *http.Request) (*http.Response, error) {
+ return newStringResponse(http.StatusOK, nil, "{"), nil
+ }),
+ },
+ }
+
+ _, err := checker.fetchAuthToken(context.Background(), "https://auth.example.test/token")
+ if err == nil {
+ t.Fatal("Expected JSON error")
+ }
+ })
+
+ t.Run("success", func(t *testing.T) {
+ checker := &RegistryChecker{
+ httpClient: &http.Client{
+ Transport: roundTripFunc(func(_ *http.Request) (*http.Response, error) {
+ return newStringResponse(http.StatusOK, nil, `{"token":"ok"}`), nil
+ }),
+ },
+ }
+
+ token, err := checker.fetchAuthToken(context.Background(), "https://auth.example.test/token")
+ if err != nil {
+ t.Fatalf("Expected token, got error %v", err)
+ }
+ if token != "ok" {
+ t.Fatalf("Expected token ok, got %q", token)
+ }
+ })
+}
diff --git a/internal/dockeragent/registry_http_test.go b/internal/dockeragent/registry_http_test.go
index 7b6734364e..18f61c246b 100644
--- a/internal/dockeragent/registry_http_test.go
+++ b/internal/dockeragent/registry_http_test.go
@@ -3,6 +3,7 @@ package dockeragent
import (
"context"
"fmt"
+ "net/http"
"testing"
"time"
@@ -11,18 +12,18 @@ import (
func TestRegistryChecker_CheckImageUpdate_Behavior(t *testing.T) {
logger := zerolog.Nop()
- checker := NewRegistryChecker(logger)
t.Run("disabled checker returns nil", func(t *testing.T) {
+ checker := NewRegistryChecker(logger)
checker.SetEnabled(false)
result := checker.CheckImageUpdate(context.Background(), "nginx:latest", "sha256:current")
if result != nil {
t.Error("Expected nil result when checker is disabled")
}
- checker.SetEnabled(true)
})
t.Run("digest-pinned image skipped", func(t *testing.T) {
+ checker := NewRegistryChecker(logger)
result := checker.CheckImageUpdate(context.Background(), "nginx@sha256:abc123", "sha256:abc123")
if result == nil {
t.Fatal("Expected result for digest-pinned image")
@@ -36,11 +37,27 @@ func TestRegistryChecker_CheckImageUpdate_Behavior(t *testing.T) {
})
t.Run("empty image name", func(t *testing.T) {
+ checker := NewRegistryChecker(logger)
+ checker.httpClient = &http.Client{
+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ switch req.URL.Host {
+ case "auth.docker.io":
+ return newStringResponse(http.StatusOK, nil, `{"token":"token"}`), nil
+ case "registry-1.docker.io":
+ return newStringResponse(http.StatusNotFound, nil, ""), nil
+ default:
+ return nil, fmt.Errorf("unexpected host %s", req.URL.Host)
+ }
+ }),
+ }
+
result := checker.CheckImageUpdate(context.Background(), "", "sha256:current")
if result == nil {
t.Fatal("Expected result for empty image")
}
- // Should have an error since we can't parse empty image
+ if result.Error == "" {
+ t.Fatal("Expected error for empty image")
+ }
})
}
@@ -193,63 +210,6 @@ func TestParseImageReference_EdgeCases(t *testing.T) {
}
}
-// TestRegistryChecker_FetchDigest documents the fetchDigest behavior
-// Note: This function requires HTTPS, so we can't easily mock it with httptest
-// The function is tested via integration tests with real registries
-func TestRegistryChecker_FetchDigest_Documentation(t *testing.T) {
- // fetchDigest:
- // - Always uses HTTPS
- // - Sets Accept headers for manifest types (OCI, Docker V2, V1)
- // - Uses Docker-Content-Digest header if available
- // - Falls back to Etag header if Docker-Content-Digest is missing
- // - Returns error for 4xx/5xx status codes
- // - Caches errors for rate limiting scenarios
-
- t.Run("documents expected behavior", func(t *testing.T) {
- logger := zerolog.Nop()
- checker := NewRegistryChecker(logger)
-
- // Attempting to fetch from an invalid registry should fail
- ctx := context.Background()
- _, err := checker.fetchDigest(ctx, "invalid.registry.test", "library/nginx", "latest")
- if err == nil {
- t.Error("Expected error when fetching from invalid registry")
- }
- })
-
- t.Run("context cancellation", func(t *testing.T) {
- logger := zerolog.Nop()
- checker := NewRegistryChecker(logger)
-
- ctx, cancel := context.WithCancel(context.Background())
- cancel() // Cancel before fetching
-
- _, err := checker.fetchDigest(ctx, "registry-1.docker.io", "library/nginx", "latest")
- if err == nil {
- t.Error("Expected error when context is cancelled")
- }
- })
-}
-
-// TestRegistryChecker_AuthToken_Documentation documents the auth token behavior
-// Note: We can't easily test this with a mock server since the auth URL is hardcoded
-// The auth flow is tested via integration tests with real registries
-func TestRegistryChecker_AuthToken_Documentation(t *testing.T) {
- t.Run("auth token documentation", func(t *testing.T) {
- // Auth token flow for Docker Hub:
- // 1. Request manifest without token
- // 2. Receive 401 with Www-Authenticate header
- // 3. Request token from auth.docker.io
- // 4. Retry manifest request with Bearer token
-
- // For GHCR:
- // 1. Request token from ghcr.io/token
- // 2. Use token for manifest request
-
- // This behavior is tested via integration tests
- t.Log("Auth token flow is verified via integration tests with real registries")
- })
-}
func TestImageUpdateResult_Fields(t *testing.T) {
result := ImageUpdateResult{
diff --git a/internal/dockeragent/system.go b/internal/dockeragent/system.go
index 73c5239709..a16c39bee9 100644
--- a/internal/dockeragent/system.go
+++ b/internal/dockeragent/system.go
@@ -3,13 +3,12 @@ package dockeragent
import (
"bufio"
"errors"
- "os"
"strconv"
"strings"
)
func readProcUptime() (float64, error) {
- f, err := os.Open("/proc/uptime")
+ f, err := openProcUptime()
if err != nil {
return 0, err
}