updater

package module
v0.14.2 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: BSD-3-Clause Imports: 45 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Arcane Updater

Portable Docker auto-update orchestration for Go applications.

CI Go Reference License

Arcane Updater is the standalone Go module behind Arcane's Docker auto-updater. It pulls newer images, recreates the containers running them, and restarts whatever depended on those containers — with Compose awareness, registry digest checks, and a path for containers that must update themselves.

It works out of the box against the local Docker environment. Persistence, notifications, and self-upgrade behavior stay adapter-driven, so a host application plugs in only the parts it owns.

[!IMPORTANT] This module is in early development. The API is not stable and may change without notice.

Install

go get kit.getarcane.app/updater@latest

Quick start

Everything runs through a Service. The zero Config is valid:

import "kit.getarcane.app/updater"

service, err := updater.New(updater.Config{})
if err != nil {
	return err
}
defer service.Close()

result, err := service.UpdateContainer(ctx, containerID, updater.Options{})

To work through recorded pending updates instead of one named container:

store := updater.NewMemoryPendingStore(updater.ImageUpdateRecord{
	ID:         "sha256:old-image-id",
	Repository: "nginx",
	Tag:        "1.27",
	HasUpdate:  true,
	UpdateType: updater.UpdateTypeDigest,
})

service, err := updater.New(updater.Config{PendingStore: store})
if err != nil {
	return err
}
defer service.Close()

result, err := service.ApplyPending(ctx, updater.Options{})

ApplyPending applies each pending update and then restarts the containers still running the images it replaced. Options{DryRun: true} reports what would change without touching anything.

Configuring

Every Config field is a seam. Leave one nil and the updater supplies a Docker-backed default — or, for the purely optional ones, skips that behavior entirely. Override only what you own:

service, err := updater.New(updater.Config{
	// Replace a default.
	DockerClientProvider: updater.NewDockerClientProvider(client.WithHost("tcp://docker-proxy:2375")),
	PendingStore:         myStore,

	// Add optional behavior.
	Notifier:      myNotifier,   // told about each successful update
	EventRecorder: myEvents,     // receives lifecycle events
	SelfUpdater:   myUpgrader,   // handles the container we run in

	// Restrict which containers are in scope.
	LabelPolicy: updater.LabelPolicy{
		IsUpdateDisabledFunc: func(l map[string]string) bool { return l["updates"] == "off" },
	},

	OperationTimeout: 30 * time.Second,
})

LabelPolicy merges per field: overriding IsUpdateDisabledFunc above keeps the default behavior for self-update, agent, server, swarm, and stop-signal detection. See DefaultLabelPolicy.

Service.Close shuts down the Docker client New created. If you supplied your own DockerClientProvider, its lifecycle stays yours and Close is a no-op.

How it works

  1. Resolve a pullable image reference for each in-scope container, skipping image IDs and digest-pinned references — re-pulling those can never yield a newer image.
  2. Skip containers the LabelPolicy disables, containers the host excludes via SettingsProvider, and Swarm tasks.
  3. Select a newer eligible version tag, or compare the configured tag's digest. Options{Force: true} bypasses unchanged-image checks while preserving the selection policy.
  4. Pull the target image.
  5. Recreate the container — through the ProjectUpdater for Compose services (grouped by project, then verified to no longer run the old image), or by a direct stop/create/start with rollback for standalone containers.
  6. Restart containers that depend on what just changed, in dependency order.
  7. Hand self-update targets to the SelfUpdater, last, since updating them may stop the calling process.

Scheduling, durable persistence, and user-facing notifications are not the module's job; supply adapters for those.

Package layout

Package Contents
updater The Service, Config, the port interfaces, and the result types. Everything a host application normally needs.
updater/refs Image reference normalization and pullability checks.
updater/digest OCI digest parsing and canonicalization.
updater/labels The Arcane container labels and the predicates that read them.
updater/registry Registry HTTP digest and pull-rate-limit lookups.

Implementation details live under internal/ and are not part of the public API.

Migrating from v0.6.x

v0.7.0 collapses api and types into the module root, so one import replaces two.

Before After
api.NewService(cfg) updater.New(cfg), which now returns (*Service, error)
api.NewDefaultService() updater.New(updater.Config{})
api.Service, api.Config, the port interfaces same names in updater
types.Options, types.Result, types.Status, … same names in updater
api.ResolvePullableImageRef refs.PullableImageRef, without the second return
api.UpdateStandaloneContainer unexported; use UpdateContainer
pkg/digest.RemoteResolver (GetImageDigest) updater.RegistryDigestResolver (ImageDigest)
pkg/labels.DefaultLabelPolicy updater.DefaultLabelPolicy
pkg/labels.GetStopSignal labels.StopSignal
pkg/registry.NewRegistryHTTPClient removed; pass any *http.Client (or nil) to the registry functions
pkg/{refs,digest,labels,registry} {refs,digest,labels,registry} — drop the pkg/
pkg/{match,deps,utils}, digest Checker/RefIDCache moved to internal/; no longer public
pkg/logs removed
types.HistoryRecord, types.ContextHook removed; nothing consumed them

Reshaped data types:

  • Result.StartTime/EndTime are now time.Time; the pre-formatted Duration string is now the Duration() method. ActivityID is gone.
  • ResourceResult.OldImages/NewImages maps are now the OldImage/NewImage strings they always held.
  • Options.Type and Options.ResourceIDs are gone; nothing read them.
  • ResourceType, ResourceStatus, and UpdateType are now named string types. The constant values are unchanged, so persisted data stays valid.

New also fixes a trap: LabelPolicy now merges per field, so overriding one func no longer silently drops the defaults for the others.

Development

just format all
just test all
just lint all

Tag-based updates

The default digest strategy keeps the configured tag and follows only its digest. Set strategy: auto to discover newer tags for stable, complete semantic versions such as 3.1.2 and v3.1.2. Under auto, moving tags (latest), partial versions (3 or 3.1), and ambiguous prerelease or variant tags keep using digest checks.

Add a constraint or pattern to control selection for a container or Compose service:

services:
  app:
    image: example/app:3.1.2-alpine
    labels:
      com.getarcaneapp.arcane.updater.strategy: tag
      com.getarcaneapp.arcane.updater.constraint: '3.x'
      com.getarcaneapp.arcane.updater.tag-pattern: '(?P<version>\d+\.\d+\.\d+)-alpine'

An omitted strategy follows the digest. A constraint or pattern without a strategy, or with auto, requests tag selection; invalid rules or an incompatible current tag return an error. Explicit strategy: tag always requires a valid tag policy. Without an explicit constraint, tag updates stay within the current major, or the current minor for 0.x. An explicit constraint replaces that range. Version comparison uses complete semantic versions with an optional v prefix. Prereleases require an explicit constraint that admits them, such as >=3.1.2-0 <4.0.0.

Patterns match the entire tag. A named version capture extracts the semantic version from a variant tag; otherwise the entire matched tag must be a semantic version. Use a capture for tags such as 3.1.2-alpine to keep the selected variant. The updater preserves the exact registry tag when pulling. Equivalent candidate versions use the lexically smallest tag, and never replace the current version with an equal or older one. Invalid current versions or rules return an error. If no newer tag qualifies, the current tag is still checked for digest changes. Image IDs and digest-pinned references are ineligible, including with Force.

Checking and recording candidates

CheckContainerUpdate returns a candidate without pulling, recreating, or writing pending records. CheckImageUpdate accepts a types.CheckRequest for callers that already have an image reference and policy. Supplying CurrentDigest avoids a local Docker lookup for digest checks. Errors from tag listing are returned; partial listings are never treated as an up-to-date result.

check, err := service.CheckContainerUpdate(ctx, containerID)
if err != nil {
    return err
}
if check.UpdateAvailable {
    current, err := refs.NormalizeReference(check.CurrentRef)
    if err != nil {
        return err
    }
    target, err := refs.NormalizeReference(check.TargetRef)
    if err != nil {
        return err
    }
    record := updater.ImageUpdateRecord{
        ContainerID: check.ContainerID,
        Repository: current.RegistryHost + "/" + current.Repository,
        Tag: current.Tag,
        HasUpdate: true,
        UpdateType: updater.UpdateType(check.UpdateType),
        CurrentVersion: check.CurrentVersion,
        LatestVersion: &target.Tag,
    }
    // Persist record in your application's PendingStore, or pass it to
    // updater.NewMemoryPendingStore(record) when constructing a service.
    _ = record
}

Import kit.getarcane.app/updater/refs for reference parsing and kit.getarcane.app/updater/types for check requests and policies. A host can replace Config.RegistryTagLister to supply registry credentials or its own registry client. The default uses Docker configuration credentials and handles registry pagination, requesting 1000 tags per page and honoring the caller's deadline across every page (falling back to 120 seconds when none is set).

ImageUpdateRecord.ContainerID scopes a candidate to one container. ID retains its existing image/store meaning. Durable stores must include ContainerID in record identity so two containers sharing an image can follow different rules. The built-in memory store already does this. Check results do not contain the image ID; a host that keys records by image ID should supply it separately.

ApplyPending rechecks current references, eligibility, and constraints before pulling. It pulls each distinct target once and retains records after failure or stale configuration. Pending runs only update running containers; use UpdateContainer for an explicit update of a stopped container. Legacy unscoped tag records match the configured old reference, never every container sharing its image ID. Conflicting pending targets for one container or Compose service fail before pulls. Digest-only pending runs retain their existing behavior.

UpdateContainer uses the same tag selection. DryRun resolves and reports the candidate without pulling or changing resources. Force can recreate an unchanged image but cannot bypass eligibility or version rules. A tag change still updates the configured reference when both tags share the same image ID. Options{IgnoreSettingsExclusions: true} lets the explicitly requested container update even when the SettingsProvider excludes it from automatic updates or its updater label disables them. It applies only to that target and leaves the exclusion and label in place; ApplyPending and the restart pass keep honoring both, and Swarm tasks and immutable references stay ineligible.

Compose host adapters

For Compose tag changes, implement types.ProjectImageUpdater on the configured ProjectUpdater:

UpdateServiceImages(ctx context.Context, projectID string,
    changes map[string]types.ServiceImageChange) error

Each service change contains ExpectedRef and TargetRef. The adapter must check that the persisted service image still matches ExpectedRef, persist TargetRef, and recreate the service. Return success only after persistence and recreation succeed. The module groups changes by project and verifies every running service container against the target reference and pulled image ID. An adapter error retains the pending records even if some services changed.

The built-in CLI adapter supports digest updates only. Compose tag changes fail before pulling unless a host adapter implements this interface, and never fall back to standalone recreation. Self-update targets continue receiving the chosen reference through SelfUpdater.

License

Arcane Updater is released under the BSD 3-Clause License.

Documentation

Overview

Package updater keeps Docker containers running current images: it pulls newer images, recreates the containers using them, and restarts whatever depended on those containers.

Getting started

Everything runs through a Service. The zero Config is valid and produces a service backed entirely by the local Docker environment:

service, err := updater.New(updater.Config{})
if err != nil {
	return err
}
defer service.Close()

result, err := service.UpdateContainer(ctx, containerID, updater.Options{})

Service.UpdateContainer updates one container by ID. Service.ApplyPending works through every update recorded in the configured PendingStore, and restarts the containers still running the images it replaced.

Configuring

Each field of Config is a seam the host application can take over. Leave a field nil and the updater supplies a Docker-backed default for it — or, for the purely optional ones, simply skips the behavior. So a caller can replace just the pieces they care about:

service, err := updater.New(updater.Config{
	PendingStore: myStore,       // where pending updates come from
	Notifier:     myNotifier,    // told about each successful update
	SelfUpdater:  myUpgrader,    // handles the container we run in
})

LabelPolicy decides which containers are in scope, using container labels. It merges per field, so overriding one behavior keeps the defaults for the rest. See DefaultLabelPolicy.

Compose and self-update

Containers carrying Docker Compose labels are grouped by project and updated through the configured ProjectUpdater rather than being recreated individually, then verified to no longer run the old image. Containers the LabelPolicy marks as self-update targets — including the one named by Config.SelfContainerID — are handed to the configured SelfUpdater instead, last in the run, since updating them may stop this process.

Building

This module uses the experimental encoding/json/v2 package. Build and test it with GOEXPERIMENT=jsonv2 set.

Index

Examples

Constants

View Source
const (

	// UpdateTypeDigest identifies an image update where the tag is unchanged but the digest changed.
	UpdateTypeDigest UpdateType = "digest"
	// UpdateTypeTag identifies an image update where the target tag changes.
	UpdateTypeTag UpdateType = "tag"

	// ResourceTypeImage is the result resource type for image pull/check work.
	ResourceTypeImage ResourceType = "image"
	// ResourceTypeContainer is the result resource type for container update work.
	ResourceTypeContainer ResourceType = "container"
	// ResourceTypeProject is the result resource type for compose project update work.
	ResourceTypeProject ResourceType = "project"

	// StatusChecked indicates a resource was checked.
	StatusChecked ResourceStatus = "checked"
	// StatusUpdated indicates a resource was updated.
	StatusUpdated ResourceStatus = "updated"
	// StatusRestarted indicates a resource was restarted because a dependency changed.
	StatusRestarted ResourceStatus = "restarted"
	// StatusSkipped indicates a resource was skipped.
	StatusSkipped ResourceStatus = "skipped"
	// StatusFailed indicates a resource failed to update.
	StatusFailed ResourceStatus = "failed"
	// StatusUpToDate indicates a resource is already up to date.
	StatusUpToDate ResourceStatus = "up_to_date"
	// StatusUpdateAvailable indicates an update is available.
	StatusUpdateAvailable ResourceStatus = "update_available"
)

Variables

View Source
var (
	// ErrDockerClientProviderRequired is returned when no Docker client
	// provider is configured.
	ErrDockerClientProviderRequired = errors.New("docker client provider is required")
	// ErrImagePullerRequired is returned when an update needs to pull an image
	// but no image puller is configured.
	ErrImagePullerRequired = errors.New("image puller is required")
	// ErrPendingStoreRequired is returned by ApplyPending when no pending store
	// is configured.
	ErrPendingStoreRequired = errors.New("pending store is required")
	// ErrSelfUpdaterRequired is returned when a container must be handled by
	// the host application but no SelfUpdater is configured.
	ErrSelfUpdaterRequired = errors.New("self-update requires a SelfUpdater")
	// ErrSelfUpdateContainer is returned when a self-update target reaches the
	// standalone recreate path, which must never recreate it.
	ErrSelfUpdateContainer = errors.New("self-update containers must use SelfUpdater")
	// ErrNilDockerClient is returned when the configured provider hands back a
	// nil Docker client.
	ErrNilDockerClient = errors.New("docker client unavailable")
	// ErrContainerNotFound is returned when the requested container does not
	// exist. Use errors.Is to detect it; the returned error names the container.
	ErrContainerNotFound = errors.New("container not found")
	// ErrUpdateInProgress is returned by BeginContainerUpdate, and reported as a skip reason, while
	// another update holds the same container.
	ErrUpdateInProgress = errors.New("container update already in progress")
)

Functions

func NewRegistryTagLister

func NewRegistryTagLister() types.RegistryTagLister

NewRegistryTagLister lists registry tags using local Docker credentials.

Types

type ComposeProject

type ComposeProject struct {
	ID   string
	Name string
}

ComposeProject identifies a compose project known to the host application.

type Config

type Config struct {
	// DockerClientProvider supplies the Docker client every operation uses. Defaults to
	// NewDockerClientProvider(), which reads the standard Docker environment variables.
	DockerClientProvider DockerClientProvider
	// ImagePuller pulls images. Defaults to NewImagePuller(DockerClientProvider).
	ImagePuller ImagePuller
	// PendingStore supplies the pending updates ApplyPending works through.
	// Defaults to NewMemoryPendingStore(), which starts empty.
	PendingStore PendingStore
	// RegistryDigestResolver checks registries for newer digests. Defaults to
	// NewRegistryDigestResolver(), which uses the local Docker credentials.
	RegistryDigestResolver RegistryDigestResolver
	// RegistryTagLister discovers version tags. Defaults to Docker-config credentials.
	RegistryTagLister types.RegistryTagLister
	// ProjectUpdater updates Docker Compose services. Defaults to
	// NewDockerComposeProjectUpdater(DockerClientProvider), which runs the docker compose CLI.
	ProjectUpdater ProjectUpdater
	// LabelPolicy decides which containers the updater may touch. New merges it over
	// DefaultLabelPolicy, so each nil func keeps the default; UnmanagedReasonFunc has none.
	LabelPolicy LabelPolicy

	// RunRecorder is optional; when nil, per-resource results are not recorded.
	RunRecorder RunRecorder
	// Settings is optional; when nil, no containers are excluded.
	Settings SettingsProvider
	// SelfUpdater is optional. When nil, containers that need host self-update
	// handling fail with an error instead of being updated.
	SelfUpdater SelfUpdater
	// Notifier is optional; when nil, successful updates are not announced.
	Notifier Notifier
	// EventRecorder is optional; when nil, lifecycle events are dropped.
	EventRecorder EventRecorder
	// UsedImageCollector is optional. When nil, ApplyPending discovers active
	// images by listing running containers.
	UsedImageCollector UsedImageCollector
	// TagCandidateFilter is optional; when nil, every selected tag is used.
	TagCandidateFilter types.TagCandidateFilter

	// Logger receives the updater's diagnostics. Defaults to slog.Default().
	Logger *slog.Logger
	// SelfContainerID is the ID (or ID prefix) of the container the host application runs in.
	// When set, that container always goes through the SelfUpdater, whatever its labels.
	SelfContainerID string
	// OperationTimeout optionally bounds individual Docker mutation operations
	// and compose project updates. Zero leaves caller context deadlines unchanged.
	OperationTimeout time.Duration
}

Config configures a Service. Every field is optional: New fills in a Docker-backed default for each port that has one, and a nil optional port disables the behavior it provides.

type ConfigError

type ConfigError struct {
	// Reason is the underlying cause.
	Reason error
	// Field is the Config field at fault, as written in Go source.
	Field string
}

ConfigError reports a Config field that New could not accept.

func (*ConfigError) Error

func (e *ConfigError) Error() string

Error implements error.

func (*ConfigError) Unwrap

func (e *ConfigError) Unwrap() error

Unwrap returns the underlying cause, so errors.Is can match the sentinel.

type DockerClient

type DockerClient struct {
	// contains filtered or unexported fields
}

DockerClient is the built-in DockerClientProvider: it lazily opens one client, pings it on every hand-out, and reconnects after the daemon goes away. Construct one with NewDockerClientProvider.

func NewDockerClientProvider

func NewDockerClientProvider(options ...client.Opt) *DockerClient

NewDockerClientProvider returns a provider for the local Docker environment plus options. The caller owns it and should Close it, unless New built it, in which case Service.Close does.

func (*DockerClient) Close

func (p *DockerClient) Close() error

Close shuts down the Docker client, if one is open. It is safe to call more than once, and a later DockerClient call opens a fresh connection.

func (*DockerClient) DockerClient

func (p *DockerClient) DockerClient(ctx context.Context) (*client.Client, error)

DockerClient returns a live Docker client, opening or reopening one as needed. It implements DockerClientProvider.

type DockerClientProvider

type DockerClientProvider interface {
	DockerClient(ctx context.Context) (*client.Client, error)
}

DockerClientProvider provides Docker clients. The provider owns their lifecycle, so Service never closes them, and it may return the same client across calls.

type Event

type Event struct {
	Metadata     map[string]any
	Phase        string
	Severity     string
	ResourceID   string
	ResourceName string
	ResourceType ResourceType
}

Event describes a generic updater event for host applications.

type EventRecorder

type EventRecorder interface {
	RecordEvent(ctx context.Context, event Event) error
}

EventRecorder receives updater lifecycle events.

type ImagePuller

type ImagePuller interface {
	PullImage(ctx context.Context, imageRef string, progress io.Writer) error
}

ImagePuller pulls images and may write progress to progress. A nil progress writer means the caller does not want progress output.

func NewImagePuller

func NewImagePuller(provider DockerClientProvider) ImagePuller

NewImagePuller returns an image puller backed by Docker's ImagePull API.

type ImageUpdateRecord

type ImageUpdateRecord struct {
	LatestVersion *string
	CurrentDigest *string
	LatestDigest  *string
	LastError     *string
	CheckTime     time.Time
	// ContainerID scopes this record to one container; ID remains the image/store ID.
	ContainerID    string
	ID             string
	Repository     string
	Tag            string
	UpdateType     UpdateType
	CurrentVersion string
	HasUpdate      bool
}

ImageUpdateRecord is a pending image update known to a caller-provided store.

func (ImageUpdateRecord) ImageRef

func (i ImageUpdateRecord) ImageRef() string

ImageRef returns the current image reference represented by the record.

func (ImageUpdateRecord) IsDigestUpdate

func (i ImageUpdateRecord) IsDigestUpdate() bool

IsDigestUpdate reports whether the update is digest-based.

func (ImageUpdateRecord) IsTagUpdate

func (i ImageUpdateRecord) IsTagUpdate() bool

IsTagUpdate reports whether the update is tag-based.

func (ImageUpdateRecord) NeedsUpdate

func (i ImageUpdateRecord) NeedsUpdate() bool

NeedsUpdate reports whether the record indicates a pending update.

func (ImageUpdateRecord) NewImageRef

func (i ImageUpdateRecord) NewImageRef() string

NewImageRef returns the image reference the updater should pull for the record.

type LabelPolicy

type LabelPolicy struct {
	TagPolicyFunc          func(map[string]string) types.Policy
	IsUpdateDisabledFunc   func(map[string]string) bool
	IsSelfUpdateTargetFunc func(map[string]string) bool
	IsAgentFunc            func(map[string]string) bool
	IsServerFunc           func(map[string]string) bool
	IsSwarmTaskFunc        func(map[string]string) bool
	StopSignalFunc         func(map[string]string) string
	UnmanagedReasonFunc    func(map[string]string) string
}

LabelPolicy decides from a container's labels whether the updater may touch it, whether the host must update it itself, and how to stop it. New fills nil funcs from DefaultLabelPolicy.

func DefaultLabelPolicy

func DefaultLabelPolicy() LabelPolicy

DefaultLabelPolicy returns the Arcane-compatible label behavior New uses for any field a caller leaves nil. It sets no UnmanagedReasonFunc, so by default no container is reported as managed by another tool.

func (LabelPolicy) IsAgent

func (p LabelPolicy) IsAgent(containerLabels map[string]string) bool

IsAgent reports whether labels identify an agent self-update target.

func (LabelPolicy) IsSelfUpdateTarget

func (p LabelPolicy) IsSelfUpdateTarget(containerLabels map[string]string) bool

IsSelfUpdateTarget reports whether labels require host self-update handling.

func (LabelPolicy) IsServer

func (p LabelPolicy) IsServer(containerLabels map[string]string) bool

IsServer reports whether labels identify a server self-update target.

func (LabelPolicy) IsSwarmTask

func (p LabelPolicy) IsSwarmTask(containerLabels map[string]string) bool

IsSwarmTask reports whether labels identify a Docker Swarm task container.

func (LabelPolicy) IsUpdateDisabled

func (p LabelPolicy) IsUpdateDisabled(containerLabels map[string]string) bool

IsUpdateDisabled reports whether labels opt the container out of updates.

func (LabelPolicy) Merge

func (p LabelPolicy) Merge(o LabelPolicy) LabelPolicy

Merge returns p with every non-nil func from o laid over it. Neither p nor o is changed, so DefaultLabelPolicy().Merge(custom) overrides only the behaviors custom sets.

func (LabelPolicy) StopSignal

func (p LabelPolicy) StopSignal(containerLabels map[string]string) string

StopSignal returns the configured stop signal for a container, or "" when the policy declares none.

func (LabelPolicy) TagPolicy

func (p LabelPolicy) TagPolicy(containerLabels map[string]string) types.Policy

TagPolicy returns the image selection policy for a container.

func (LabelPolicy) UnmanagedReason

func (p LabelPolicy) UnmanagedReason(containerLabels map[string]string) string

UnmanagedReason reports why another tool owns the container's updates, or "" when the updater may.

type Notification

type Notification struct {
	ContainerID   string
	ContainerName string
	ImageRef      string
	OldImage      string
	NewImage      string
}

Notification describes a successful container update notification.

type Notifier

type Notifier interface {
	Notify(ctx context.Context, notification Notification) error
}

Notifier receives successful update notifications.

type Options

type Options struct {
	// Force applies updates even when the digest check says the image is
	// already current.
	Force bool `json:"forceUpdate,omitempty"`
	// DryRun reports what would be updated without pulling or recreating
	// anything.
	DryRun bool `json:"dryRun,omitempty"`
	// IgnoreSettingsExclusions lets a user-requested run update the containers it targets despite a settings
	// exclusion or updater opt-out label. Implicit dependency restarts still honor both, and Swarm, unmanaged,
	// and immutability checks still apply.
	IgnoreSettingsExclusions bool `json:"ignoreSettingsExclusions,omitempty"`
}

Options configures an updater run.

type PendingStore

type PendingStore interface {
	PendingImageUpdates(ctx context.Context) ([]ImageUpdateRecord, error)
	ClearImageUpdateRecord(ctx context.Context, record ImageUpdateRecord) error
}

PendingStore provides pending update records and clears applied records.

func NewMemoryPendingStore

func NewMemoryPendingStore(records ...ImageUpdateRecord) PendingStore

NewMemoryPendingStore returns an in-memory pending update store.

type ProjectUpdater

type ProjectUpdater interface {
	ProjectByComposeName(ctx context.Context, composeName string) (ComposeProject, error)
	UpdateServices(ctx context.Context, projectID string, services []string) error
}

ProjectUpdater updates Docker Compose services owned by a host application.

func NewDockerComposeProjectUpdater

func NewDockerComposeProjectUpdater(provider DockerClientProvider) ProjectUpdater

NewDockerComposeProjectUpdater returns a Docker Compose CLI project updater.

type RegistryDigestResolver

type RegistryDigestResolver interface {
	ImageDigest(ctx context.Context, imageRef string) (string, error)
}

RegistryDigestResolver resolves an image's current digest from its registry, without pulling it.

func NewRegistryDigestResolver

func NewRegistryDigestResolver() RegistryDigestResolver

NewRegistryDigestResolver returns a registry HTTP digest resolver.

type ResourceResult

type ResourceResult struct {
	ResourceID      string         `json:"resourceId"`
	ResourceName    string         `json:"resourceName,omitempty"`
	ResourceType    ResourceType   `json:"resourceType"`
	Status          ResourceStatus `json:"status"`
	OldImage        string         `json:"oldImage,omitempty"`
	NewImage        string         `json:"newImage,omitempty"`
	Details         map[string]any `json:"details,omitempty"`
	Error           string         `json:"error,omitempty"`
	UpdateAvailable bool           `json:"updateAvailable,omitempty"`
	UpdateApplied   bool           `json:"updateApplied,omitempty"`
}

ResourceResult represents the result of an update operation on one resource.

type ResourceStatus

type ResourceStatus string

ResourceStatus is the outcome recorded for one resource in a run. It is distinct from Status, which reports the work a Service has in flight.

type ResourceType

type ResourceType string

ResourceType names the kind of thing a ResourceResult describes.

type RestartTargets

type RestartTargets struct {
	// ByOldID maps a replaced image ID to the ref its containers move to.
	ByOldID map[string]string
	// ByOldRef maps a replaced image ref to the ref its containers move to.
	ByOldRef map[string]string
	// IgnoreSettingsExclusions restarts matching containers despite a settings exclusion or updater
	// opt-out label, as Options.IgnoreSettingsExclusions does for a run.
	IgnoreSettingsExclusions bool
}

RestartTargets selects the running containers RestartContainersUsingOldImages restarts.

type Result

type Result struct {
	StartTime time.Time        `json:"startTime,omitzero"`
	EndTime   time.Time        `json:"endTime,omitzero"`
	Items     []ResourceResult `json:"items"`
	Checked   int              `json:"checked"`
	Updated   int              `json:"updated"`
	Restarted int              `json:"restarted,omitempty"`
	Skipped   int              `json:"skipped"`
	Failed    int              `json:"failed"`
	Success   bool             `json:"success,omitempty"`
}

Result represents a complete updater run.

func (Result) Duration

func (r Result) Duration() time.Duration

Duration reports how long the run took. It is zero until the run finishes.

type RunRecorder

type RunRecorder interface {
	RecordUpdateRun(ctx context.Context, result ResourceResult) error
}

RunRecorder records per-resource updater results.

type SelfUpdateTarget

type SelfUpdateTarget struct {
	ContainerID   string
	ContainerName string
	InstanceType  string
	Labels        map[string]string
	// NewImageRef is the resolved image reference the self-updater should
	// upgrade the container to. Empty when the updater could not resolve one.
	NewImageRef string
	// PullImageRef is an immutable reference the host froze the update to; the container is still
	// recreated as NewImageRef. Empty when the host pulls NewImageRef directly.
	PullImageRef string
}

SelfUpdateTarget describes a container that should be handled by a host self-updater.

type SelfUpdater

type SelfUpdater interface {
	TriggerSelfUpdate(ctx context.Context, target SelfUpdateTarget) error
}

SelfUpdater handles host-specific self-update targets: containers the updater must not recreate itself, typically because the host application runs in one.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service coordinates Docker image updates, container recreation, and the host adapters configured through Config. A Service is safe for concurrent use.

func New

func New(config Config) (*Service, error)

New constructs an updater service; the zero Config is valid and uses the local Docker environment. Nil ports get their Docker-backed defaults and Config.LabelPolicy is merged over DefaultLabelPolicy.

Example

The zero Config gives a service backed entirely by the local Docker environment.

service, err := New(Config{})
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := service.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()

result, err := service.UpdateContainer(context.Background(), "my-container-id", Options{})
if err != nil {
	log.Print(err)
	return
}
fmt.Printf("updated %d of %d containers in %s\n", result.Updated, result.Checked, result.Duration())

func (*Service) ApplyPending

func (s *Service) ApplyPending(ctx context.Context, opts Options) (out *Result, err error)

ApplyPending applies pending image updates from the configured PendingStore.

Example

ApplyPending works through the updates a PendingStore reports, then restarts the containers still running the images it replaced.

store := NewMemoryPendingStore(ImageUpdateRecord{
	ID:         "sha256:old-image-id",
	Repository: "nginx",
	Tag:        "1.27",
	HasUpdate:  true,
	UpdateType: UpdateTypeDigest,
})

service, err := New(Config{PendingStore: store})
if err != nil {
	log.Fatal(err)
}
defer func() {
	if closeErr := service.Close(); closeErr != nil {
		log.Print(closeErr)
	}
}()

// DryRun reports what would change without pulling or recreating anything.
result, err := service.ApplyPending(context.Background(), Options{DryRun: true})
if err != nil {
	log.Print(err)
	return
}
for _, item := range result.Items {
	fmt.Printf("%s %s: %s -> %s\n", item.ResourceType, item.Status, item.OldImage, item.NewImage)
}

func (*Service) BeginContainerUpdate

func (s *Service) BeginContainerUpdate(containerID string) (func(), error)

BeginContainerUpdate claims a container for updating and returns the callback that releases it. It returns ErrUpdateInProgress, with a no-op callback, while another update holds the same container.

func (*Service) BeginProjectUpdate

func (s *Service) BeginProjectUpdate(projectID string) func()

BeginProjectUpdate marks a project as updating and returns a completion callback.

func (*Service) CheckContainerUpdate

func (s *Service) CheckContainerUpdate(ctx context.Context, containerID string) (types.CheckResult, error)

CheckContainerUpdate inspects one container and returns its current policy's candidate. It does not write pending records or change Docker resources.

func (*Service) CheckImageUpdate

func (s *Service) CheckImageUpdate(ctx context.Context, request types.CheckRequest) (types.CheckResult, error)

CheckImageUpdate discovers an image update without pulling or changing state. CurrentDigest should describe the image in use, not a separately cached tag.

func (*Service) Close

func (s *Service) Close() error

Close releases the Docker client New created; a caller-supplied provider is left to its owner. Close is idempotent.

func (*Service) RestartContainersUsingOldImages

func (s *Service) RestartContainersUsingOldImages(ctx context.Context, targets RestartTargets) ([]ResourceResult, error)

RestartContainersUsingOldImages restarts running containers matching targets' old image IDs or refs, plus their dependents. A dependency cycle falls back to discovery order.

func (*Service) Status

func (s *Service) Status() Status

Status returns a point-in-time updater status snapshot.

func (*Service) UpdateContainer

func (s *Service) UpdateContainer(ctx context.Context, containerID string, opts Options) (out *Result, err error)

UpdateContainer updates a single Docker container by pulling its latest image and recreating it.

type SettingsProvider

type SettingsProvider interface {
	ExcludedContainers(ctx context.Context) ([]string, error)
}

SettingsProvider provides updater settings owned by the host application.

type Status

type Status struct {
	ContainerIDs       []string `json:"containerIds"`
	ProjectIDs         []string `json:"projectIds"`
	UpdatingContainers int      `json:"updatingContainers"`
	UpdatingProjects   int      `json:"updatingProjects"`
}

Status reports resources that are actively being updated by this service instance.

type UpdateType

type UpdateType string

UpdateType distinguishes the two kinds of image update the updater applies.

type UsedImageCollector

type UsedImageCollector interface {
	UsedImages(ctx context.Context) (map[string]struct{}, error)
}

UsedImageCollector allows callers to provide their own active-image discovery, replacing the default container-list scan.

type UsedImageCollectorFunc

type UsedImageCollectorFunc func(context.Context) (map[string]struct{}, error)

UsedImageCollectorFunc adapts a function to UsedImageCollector.

func (UsedImageCollectorFunc) UsedImages

func (f UsedImageCollectorFunc) UsedImages(ctx context.Context) (map[string]struct{}, error)

UsedImages calls f(ctx).

Directories

Path Synopsis
Package digest parses and canonicalizes the OCI content digests that identify an exact image, independent of the tag pointing at it.
Package digest parses and canonicalizes the OCI content digests that identify an exact image, independent of the tag pointing at it.
internal
compose
Package compose defines the additional Docker Compose label keys the updater relies on beyond the project and service labels in kit.getarcane.app/docker.
Package compose defines the additional Docker Compose label keys the updater relies on beyond the project and service labels in kit.getarcane.app/docker.
digestcheck
Package digestcheck compares local image digests with registry digests, so the updater can tell a real update from a no-op re-pull.
Package digestcheck compares local image digests with registry digests, so the updater can tell a real update from a no-op re-pull.
Package labels reads the container labels that tell the updater whether a container opts out, is an Arcane server or agent that updates itself, belongs to Swarm, and how it wants to be stopped.
Package labels reads the container labels that tell the updater whether a container opts out, is an Arcane server or agent that updates itself, belongs to Swarm, and how it wants to be stopped.
pkg
utils/tagpolicy
Package tagpolicy selects newer image tags using semantic version policies.
Package tagpolicy selects newer image tags using semantic version policies.
Package refs normalizes image references so every spelling of one image ("nginx", "nginx:latest", "docker.io/library/nginx:latest") compares equal, and flags references that cannot be updated.
Package refs normalizes image references so every spelling of one image ("nginx", "nginx:latest", "docker.io/library/nginx:latest") compares equal, and flags references that cannot be updated.
Package registry talks to container registries through go-containerregistry to list tags, resolve image digests and read pull rate limits.
Package registry talks to container registries through go-containerregistry to list tags, resolve image digests and read pull rate limits.
Package types contains tag update policies and adapter contracts.
Package types contains tag update policies and adapter contracts.

Jump to

Keyboard shortcuts

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