actions

package
v0.0.0-...-5840427 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 21, 2026 License: Apache-2.0 Imports: 39 Imported by: 0

Documentation

Overview

Package actions provides core logic for Watchtower’s container update operations. It handles container staleness checks, updates, and lifecycle management.

Key components:

  • Update: Scans and updates containers based on parameters.
  • ValidateRollingRestartDependencies: Validates environment for rolling restarts.
  • CheckForMultipleWatchtowerInstances: Ensures single Watchtower instance.
  • RunUpdatesWithNotifications: Performs container updates and sends notifications about the results.
  • CleanupImages: Removes specified image IDs from the Docker environment.
  • UpdateImplicitRestart: Marks containers linked to restarting ones for proper restart order.

Usage example:

report, err := actions.Update(client, params)
if err != nil {
    logrus.WithError(err).Error("Update failed")
}
err = actions.ValidateRollingRestartDependencies(client, filter)
if err != nil {
    logrus.WithError(err).Error("Sanity check failed")
}
params := actions.RunUpdatesWithNotificationsParams{
	Client:                       client,
	Notifier:                     notifier,
	NotificationSplitByContainer: false,
	NotificationReport:           false,
	Filter:                       filter,
	Cleanup:                      true,
	NoRestart:                    false,
	MonitorOnly:                  false,
	LifecycleHooks:               false,
	RollingRestart:               false,
	LabelPrecedence:              false,
	NoPull:                       false,
	Timeout:                      30 * time.Second,
	LifecycleUID:                 0,
	LifecycleGID:                 0,
	CPUCopyMode:                  "",
}
metric := actions.RunUpdatesWithNotifications(params)

The package integrates with the container package for Docker operations, session package for update reporting, sorter package for container ordering, and lifecycle package for pre/post-update hooks, using logrus for logging operations and errors.

Index

Constants

View Source
const (
	// FoundNewImageMessage is the message logged when a new image is found for a container.
	FoundNewImageMessage = "Found new image"
	// StoppingContainerMessage is the message logged when stopping a container for update.
	StoppingContainerMessage = "Stopping container"
	// StartedNewContainerMessage is the message logged when a new container is started after update.
	StartedNewContainerMessage = "Started new container"
	// StoppingLinkedContainerMessage is the message logged when stopping a linked container for restart.
	StoppingLinkedContainerMessage = "Stopping linked container"
	// StartedLinkedContainerMessage is the message logged when a linked container is started after restart.
	StartedLinkedContainerMessage = "Started linked container"
	// UpdateSkippedMessage is the message logged when an update is skipped in monitor-only mode.
	UpdateSkippedMessage = "Update available but skipped (monitor-only mode)"
	// ContainerRemainsRunningMessage is the message logged when a container remains running in monitor-only mode.
	ContainerRemainsRunningMessage = "Container remains running (monitor-only mode)"
)

Exported constants for update message literals to ensure consistency across the codebase. These constants define the standard messages used in container update logging and notifications.

Variables

This section is empty.

Functions

func ApplyLocalUpdates

func ApplyLocalUpdates(
	ctx context.Context,
	filter types.Filter,
	cleanup bool,
	monitorOnly bool,
	runUpdates func(context.Context, types.Filter, types.UpdateParams) *metrics.Metric,
) *metrics.Metric

ApplyLocalUpdates runs the standard Watchtower update procedure using already-downloaded images only. Explicitly sets NoPull to true to prevent any image pulls, and RunOnce to true to ensure the update process runs only once.

func CheckForUpdates

func CheckForUpdates(
	ctx context.Context,
	client container.Client,
	filter types.Filter,
) (*checkAPI.Result, error)

CheckForUpdates inspects filtered containers and returns only those with newer upstream images.

func DownloadImages

func DownloadImages(
	ctx context.Context,
	client container.Client,
	filter types.Filter,
	images []string,
) (*downloadAPI.Result, error)

DownloadImages pulls unique image references either from the request directly or from the filtered set of monitored containers when no explicit images are provided.

func RemoveExcessWatchtowerInstances

func RemoveExcessWatchtowerInstances(
	ctx context.Context,
	client container.Client,
	cleanupImages bool,
	scope string,
	removeImageInfos *[]types.RemovedImageInfo,
	currentContainer types.Container,
) (int, error)

RemoveExcessWatchtowerInstances ensures a single Watchtower instance within the same scope.

It identifies multiple Watchtower containers within the same scope, stops all but the current, and collects removed images for deferred removal if enabled, preventing conflicts from concurrent instances. Chain identification uses the current container's labels to determine old containers to remove. Scoped instances only remove other instances in the same scope, allowing coexistence with different scopes. Removal operations respect scope boundaries to prevent cross-scope interference.

Parameters:

  • ctx: Context for cancellation and timeouts.
  • client: Container client for Docker operations.
  • cleanupImages: Remove images if true.
  • watchtowerScope: Scope to filter Watchtower instances.
  • removeImageInfos: Pointer to slice of images to remove after stopping excess instances.
  • currentContainer: The current running Watchtower container.

Returns:

  • int: Number of removed Watchtower instances.
  • error: Non-nil if removal fails, nil if single instance or successful removal.

func RemoveImages

func RemoveImages(
	ctx context.Context,
	client container.Client,
	images []types.RemovedImageInfo,
) ([]types.RemovedImageInfo, error)

RemoveImages removes specified images and returns successfully removed ones.

It iterates through the provided images, attempting to remove each from the Docker environment, logging successes or failures for debugging and monitoring. Tracks successfully removed image info. If no images are provided, it returns an empty slice and no error.

Parameters:

  • ctx: Context for cancellation and timeouts.
  • client: Container client for Docker operations.
  • images: Slice of images to remove.

Returns:

  • []RemovedImageInfo: Slice of successfully removed image info.
  • error: Non-nil if any image removal failed, nil otherwise.

func RunUpdatesWithNotifications

func RunUpdatesWithNotifications(
	ctx context.Context,
	params RunUpdatesWithNotificationsParams,
) *metrics.Metric

RunUpdatesWithNotifications performs container updates and sends notifications about the results.

It executes the update action with configured parameters, batches notifications, and returns a metric summarizing the session for monitoring purposes, ensuring users are informed of update outcomes.

Parameters:

  • ctx: Context for cancellation and timeouts.
  • params: The RunUpdatesWithNotificationsParams struct containing all configuration parameters.

Returns:

  • *metrics.Metric: A pointer to a metric object summarizing the update session (scanned, updated, failed counts).

func StreamLogs

func StreamLogs(ctx context.Context, target types.ServiceTarget, window LogWindow, out chan<- LogLine) error

StreamLogs streams log lines for all containers matching target to out. It always closes out before returning, whether due to completion or error.

func Update

Update scans and updates containers based on parameters.

It checks container staleness, sorts by dependencies, and updates or restarts containers as needed, collecting cleaned image info for cleanup. Non-stale linked containers are restarted but not marked as updated. Containers with pinned images (referenced by digest) are skipped to preserve immutability.

Parameters:

  • ctx: Context for cancellation and timeouts.
  • client: Container client for interacting with Docker API.
  • config: UpdateParams specifying behavior like cleanup, restart, and filtering.

Returns:

  • types.Report: Session report summarizing scanned, updated, and failed containers.
  • []types.RemovedImageInfo: Slice of cleaned image info to clean up after updates.
  • error: Non-nil if listing or sorting fails, nil on success.

func UpdateImplicitRestart

func UpdateImplicitRestart(allContainers, containers []types.Container)

UpdateImplicitRestart marks containers linked to restarting ones.

It uses a multi-pass algorithm to ensure transitive propagation through the dependency chain, continuing until no more containers are marked for restart.

Parameters:

  • allContainers: List of all containers.
  • containers: List of containers to update.

func ValidateRollingRestartDependencies

func ValidateRollingRestartDependencies(ctx context.Context, client container.Client, filter types.Filter) error

ValidateRollingRestartDependencies validates the environment for rolling restart updates.

It iterates through the filtered containers and returns an error if any container has a linked dependency, which is incompatible with the use of a rolling restart update policy.

Parameters:

  • ctx: Context for cancellation and timeouts.
  • client: Container client for Docker operations.
  • filter: Container filter to select relevant containers.

Returns:

  • error: Non-nil if dependencies conflict with rolling restarts, nil otherwise.

Types

type ContainerLogs

type ContainerLogs struct {
	Container string   `json:"container"`
	Service   string   `json:"service,omitempty"`
	Stdout    []string `json:"stdout"`
	Stderr    []string `json:"stderr"`
}

ContainerLogs holds the log output for a single container.

type LogLine

type LogLine struct {
	Container string `json:"container"`
	Service   string `json:"service,omitempty"`
	Stream    string `json:"stream"` // "stdout" or "stderr"
	Line      string `json:"line"`
}

LogLine represents a single log line emitted by a container.

type LogWindow

type LogWindow string

LogWindow is a duration string specifying how far back in time to retrieve logs. Accepts Go duration strings (e.g. "30m", "2.5h") plus a "d" suffix for days (e.g. "1d", "5.6d"), and the special value "all" to retrieve all available logs.

const (
	// LogWindowAll is a special value meaning no time restriction — fetch all available logs.
	LogWindowAll LogWindow = "all"
)

func ParseLogWindow

func ParseLogWindow(s string) (LogWindow, error)

ParseLogWindow validates and normalises a log window string. Accepts:

  • "" or "24h" → defaults to 24h
  • "all" → no time restriction
  • Any Go duration string: "30m", "2.5h", "90s", etc.
  • A "d"-suffixed float for days: "1d", "5.6d", etc.

type LogsResult

type LogsResult struct {
	Logs       []ContainerLogs `json:"logs"`
	Containers int             `json:"containers"`
	TotalLines int             `json:"total_lines"`
	Window     LogWindow       `json:"window"`
}

LogsResult summarizes a log snapshot request.

func FetchLogs

func FetchLogs(ctx context.Context, target types.ServiceTarget, window LogWindow) (*LogsResult, error)

FetchLogs retrieves a snapshot of logs for containers matching the given target. The window controls how far back in time to look: a duration like "2.5h" or "5.6d", or "all".

type RunUpdatesWithNotificationsParams

type RunUpdatesWithNotificationsParams struct {
	Client                       container.Client  // Docker client for container operations
	Notifier                     types.Notifier    // Notification system for sending update status messages
	NotificationSplitByContainer bool              // Enable separate notifications for each updated container
	NotificationReport           bool              // Enable report-based notifications
	Filter                       types.Filter      // Container filter determining which containers are targeted
	Cleanup                      bool              // Remove old images after container updates
	NoRestart                    bool              // Prevent containers from being restarted after updates
	MonitorOnly                  bool              // Monitor containers without performing updates
	LifecycleHooks               bool              // Enable pre- and post-update lifecycle hook commands
	RollingRestart               bool              // Update containers sequentially rather than all at once
	LabelPrecedence              bool              // Give container label settings priority over global flags
	NoPull                       bool              // Skip pulling new images from registry during updates
	Timeout                      time.Duration     // Maximum duration for container stop operations
	LifecycleUID                 int               // Default UID to run lifecycle hooks as
	LifecycleGID                 int               // Default GID to run lifecycle hooks as
	CPUCopyMode                  string            // CPU settings handling when recreating containers
	PullFailureDelay             time.Duration     // Delay after failed Watchtower self-update pulls
	RunOnce                      bool              // Perform one-time update and exit
	SkipSelfUpdate               bool              // Skip Watchtower self-update
	CurrentContainerID           types.ContainerID // ID of the current Watchtower container for self-update logic
}

RunUpdatesWithNotificationsParams holds the parameters for RunUpdatesWithNotifications.

type ServicesActionSummary

type ServicesActionSummary struct {
	Name     string
	Service  string
	Affected int
}

ServicesActionSummary summarizes a lifecycle action request.

func RemoveServices

func RemoveServices(ctx context.Context, target types.ServiceTarget) (*ServicesActionSummary, error)

RemoveServices removes matched containers for an app or a specific service.

func RestartServices

func RestartServices(ctx context.Context, target types.ServiceTarget) (*ServicesActionSummary, error)

RestartServices restarts matched containers for a specific service.

func StartServices

func StartServices(ctx context.Context, target types.ServiceTarget) (*ServicesActionSummary, error)

StartServices starts matched containers for a specific service.

func StopServices

func StopServices(ctx context.Context, target types.ServiceTarget) (*ServicesActionSummary, error)

StopServices stops all matched containers for an app or a specific service.

type ServicesDeploySummary

type ServicesDeploySummary struct {
	Application string
	Services    []string
	Created     int
}

ServicesDeploySummary summarizes a deployment request.

func DeployServices

func DeployServices(ctx context.Context, spec types.AppSpec) (*ServicesDeploySummary, error)

DeployServices creates containers for the provided app spec.

Directories

Path Synopsis
Package mocks provides mock implementations for testing Watchtower components.
Package mocks provides mock implementations for testing Watchtower components.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL