Documentation
¶
Index ¶
- Constants
- Variables
- func ApplySelfUpdate(ctx context.Context, dockerCli command.Cli, opts ApplySelfOptions) error
- func ArtifactStoreBase(path string, revision store.Revision) (string, bool)
- func AutoDiscoveryConfigsEqual(a, b deployConfig.AutoDiscoveryConfig) bool
- func BuildSelfApplierCreate(inspect container.InspectResponse, journalID, stack string, drift bool) client.ContainerCreateOptions
- func CheckDefaultComposeFiles(composeFiles []string, workingDir string) ([]string, error)
- func CheckMountPointWriteable(mountPoint container.MountPoint) error
- func ClearDeploymentFailure(repoName, stack string)
- func ComposeSignal(ctx context.Context, dockerCli command.Cli, project *types.Project, ...) error
- func ConfigureSelfUpdate(o SelfUpdateOptions)
- func ConnectToSocketContext(ctx context.Context) (net.Conn, error)
- func CreateDockerCli(quiet bool) (command.Cli, error)
- func CreateDockerCliWithContext(quiet bool, dockerContext string) (command.Cli, error)
- func DataMountPath(hostPath, dataMountSource, dataMountDestination string) (string, bool)
- func DecryptProjectFiles(repoPath string, p *types.Project) ([]string, error)
- func DeployStack(ctx context.Context, req DeployRequest) error
- func DeploySwarmStack(ctx context.Context, dockerCli command.Cli, cfg *composetypes.Config, ...) error
- func DeployedArtifactDirs(labels Labels, dataMountSource, dataMountDestination string) []string
- func DeployedServicesWithChangedDesiredImageDigests(ctx context.Context, dockerCli command.Cli, swarmMode bool, ...) ([]string, error)
- func DeployedServicesWithChangedImageDigests(ctx context.Context, dockerCli command.Cli, swarmMode bool, ...) ([]string, error)
- func DeployedServicesWithChangedImageRefs(ctx context.Context, dockerCli command.Cli, swarmMode bool, ...) ([]string, error)
- func DeploymentModeMigrationRequired(ctx context.Context, dockerCli command.Cli, ...) (bool, error)
- func DesiredProjectImageDigests(ctx context.Context, dockerCli command.Cli, project *types.Project, ...) map[string]string
- func DestroyStack(jobLog *slog.Logger, ctx *context.Context, dockerCli *command.Cli, ...) error
- func DisplayContextName(name string) string
- func Exec(apiClient client.APIClient, containerID string, cmd ...string) (out string, err error)
- func ExecContext(ctx context.Context, apiClient client.APIClient, containerID string, ...) (out string, err error)
- func ExtractOciArtifactTag(reference string) string
- func FailSelfUpdate(ctx context.Context, dockerCli command.Cli, store *selfupdate.Store, ...) error
- func FindOneOffContainer(ctx context.Context, apiClient client.APIClient, runID string) (string, error)
- func FindSelfAppliers(ctx context.Context, apiClient client.APIClient, stack string) ([]container.Summary, error)
- func FindSwarmOneOffService(ctx context.Context, dockerCLI command.Cli, runID string) (string, error)
- func FormatPinnedRevisions(revisions []string) string
- func GetAutoDiscoveryServices(ctx context.Context, cli client.APIClient, swarmMode bool) (map[Service]map[string]string, error)
- func GetContainerID(apiClient client.APIClient, name string) (id string, err error)
- func GetDeploymentServices(ctx context.Context, cli client.APIClient, swarmMode bool, stackName string) (map[Service]map[string]string, error)
- func GetLabeledConfigs(ctx context.Context, cli client.APIClient, key, value string) (configs []swarm.Config, err error)
- func GetLabeledContainers(ctx context.Context, cli client.APIClient, key, value string, all bool) (containers []container.Summary, err error)
- func GetLabeledSecrets(ctx context.Context, cli client.APIClient, key, value string) (secrets []swarm.Secret, err error)
- func GetLabeledServices(ctx context.Context, cli client.APIClient, swarmMode bool, key, value string) (map[Service]map[string]string, error)
- func GetLabeledVolumes(ctx context.Context, cli client.APIClient, key, value string) (volumes []volume.Volume, err error)
- func GetMountPointByDestination(ctx context.Context, cli client.APIClient, containerID, destination string) (container.MountPoint, error)
- func GetPathsFromGitChangedFiles(changedFiles []gitInternal.ChangedFile, basePath string) []string
- func GetProjectContainers(ctx context.Context, dockerCli command.Cli, projectName string) ([]api.ContainerSummary, error)
- func GetProjects(ctx context.Context, dockerCli command.Cli, showDisabled bool) ([]api.Stack, error)
- func GetServiceLabels(ctx context.Context, cli client.APIClient, swarmMode bool, stackName string) (map[Service]Labels, error)
- func GetServicesWithLabelKey(ctx context.Context, cli client.APIClient, swarmMode bool, labelKey string) (map[Service]map[string]string, error)
- func HasChangedBindMounts(repoPathExternal string, paths []string, project *types.Project, ...) ([]string, []string)
- func HasChangedBuildFiles(repoPathExternal string, paths []string, project *types.Project, ...) ([]string, []string)
- func HasChangedConfigs(repoPathExternal string, paths []string, project *types.Project, ...) ([]string, []string)
- func HasChangedEnvFiles(repoPathExternal string, paths []string, project *types.Project, ...) ([]string, []string)
- func HasChangedSecrets(repoPathExternal string, paths []string, project *types.Project, ...) ([]string, []string)
- func HasComposeHooks(service types.ServiceConfig, phase ComposeHookPhase) bool
- func InspectContainerState(ctx context.Context, apiClient client.APIClient, containerID string) (*container.State, error)
- func IsComposeHookContainerUnavailable(err error) bool
- func IsSelfStack(dc *deploy.Config) bool
- func ListManagedRepositoryContainers(ctx context.Context, apiClient client.APIClient, repository string, all bool) ([]container.Summary, error)
- func ListManagedRepositoryServices(ctx context.Context, apiClient client.APIClient, repository string) ([]swarm.Service, error)
- func LoadCompose(ctx context.Context, dockerCli command.Cli, ...) (*types.Project, error)
- func LoadSwarmStack(dockerCli command.Cli, project *types.Project, deployConfig *deploy.Config, ...) (*composetypes.Config, *options.Deploy, error)
- func MarshalAutoDiscoveryConfig(cfg deployConfig.AutoDiscoveryConfig) string
- func MayHaveComposeHooks(labels map[string]string, phases ...ComposeHookPhase) bool
- func MigrateDeploymentMode(ctx context.Context, log *slog.Logger, dockerCli command.Cli, ...) (bool, error)
- func NewHttpClient() *http.Client
- func NormalizeContextName(name string) string
- func NormalizeRepositoryLabel(repository string) string
- func ParseAutoDiscoveryConfig(labelValue string) deployConfig.AutoDiscoveryConfig
- func ParseJobScheduleExpression(spec string) (gocron.Cron, error)
- func ParsePinnedRevisions(value string) []string
- func ProjectFilesHaveChanges(repoPathExternal string, changePaths []string, project *types.Project) ([]Change, IgnoredInfo, error)
- func ProjectHash(p *types.Project, sourceRoot string) (string, error)
- func ProjectPathFilter(repoPath string, p *types.Project, extraRepoPaths ...string) (func(string) bool, error)
- func PruneStackConfigs(ctx context.Context, client dockerClient.APIClient, namespace string, ...) error
- func PruneStackSecrets(ctx context.Context, client dockerClient.APIClient, namespace string, ...) error
- func PullImages(ctx context.Context, dockerCli command.Cli, projectName string) error
- func RecordDeployStatus(repoName, stack, commitSHA, composeHash string)
- func RecordDeploymentFailure(repoName, stack string, failure DeploymentFailure)
- func RecreateProject(ctx context.Context, contextName string, dockerCli command.Cli, ...) error
- func ReleaseSelfApplierRestartLimit(ctx context.Context, apiClient client.APIClient, applierID string) error
- func RemoveLabeledVolumes(ctx context.Context, dockerClient client.APIClient, swarmMode bool, ...) error
- func RemoveOneOffContainer(ctx context.Context, apiClient client.APIClient, containerID string) error
- func RemoveProject(ctx context.Context, dockerCli command.Cli, projectName string, ...) error
- func RemoveSelfApplier(ctx context.Context, apiClient client.APIClient, containerID string) error
- func RemoveSwarmOneOffService(ctx context.Context, dockerCLI command.Cli, serviceID string, ...) error
- func RemoveSwarmStack(ctx context.Context, dockerCli command.Cli, namespace string) error
- func RemoveSwarmStackWithLogger(ctx context.Context, dockerCli command.Cli, namespace string, log *slog.Logger) error
- func RepoRelativePath(repoPath, absPath string) (rel string, ok bool)
- func RepositoryLabelMatches(label string, repositories ...string) bool
- func RerunJobService(ctx context.Context, cli dockerClient.APIClient, serviceName string) error
- func RestartContainer(ctx context.Context, apiClient client.APIClient, containerID string) error
- func RestartContainerAndWait(ctx context.Context, apiClient client.APIClient, containerID string) error
- func RestartProject(ctx context.Context, dockerCli command.Cli, projectName string, ...) error
- func RestartScheduledSwarmService(ctx context.Context, dockerCLI command.Cli, serviceName string) error
- func RestartService(ctx context.Context, cli dockerClient.APIClient, serviceName string) error
- func RestoreCreateFromSnapshot(snap container.InspectResponse) client.ContainerCreateOptions
- func RotateProjectCertificates(ctx context.Context, contextName string, dockerCli command.Cli, ...) error
- func RunComposeHooks(ctx context.Context, apiClient client.APIClient, containerID string, ...) error
- func RunComposeOneOffFromServiceDefinition(ctx context.Context, dockerCli command.Cli, labels map[string]string, ...) error
- func RunComposeOneOffFromServiceDefinitionWithOptions(ctx context.Context, dockerCli command.Cli, labels map[string]string, ...) error
- func RunComposeScheduledContainer(ctx context.Context, dockerCli command.Cli, containerID string, ...) error
- func RunContainerOneOffFromExisting(ctx context.Context, apiClient client.APIClient, containerID string) error
- func RunContainerOneOffFromExistingWithOptions(ctx context.Context, apiClient client.APIClient, containerID string, ...) error
- func RunImagePruneJob(ctx context.Context, dockerCLI command.Cli, logs ...*slog.Logger) error
- func RunImageRemoveJob(ctx context.Context, dockerCLI command.Cli, images []string, ...) error
- func RunSwarmJob(ctx context.Context, dockerCLI command.Cli, mode swarm.DeployMode, ...) error
- func RunSwarmOneOffFromService(ctx context.Context, dockerCLI command.Cli, serviceName string, ...) (err error)
- func SetConfigHashPrefixes(stack *composetypes.Config, namespace string) error
- func SetSecretHashPrefixes(stack *composetypes.Config, namespace string) error
- func SourceTypeLabelValue(primary, fallback string) string
- func StartProject(ctx context.Context, dockerCli command.Cli, projectName string, ...) error
- func StartProjectServices(ctx context.Context, dockerCli command.Cli, projectName string, ...) error
- func StartSwarmService(ctx context.Context, dockerCLI command.Cli, serviceName string, ...) error
- func StopProject(ctx context.Context, dockerCli command.Cli, projectName string, ...) error
- func StopProjectServices(ctx context.Context, dockerCli command.Cli, projectName string, ...) error
- func StopSwarmService(ctx context.Context, dockerCLI command.Cli, serviceName string, ...) (originalReplicas uint64, err error)
- func SwarmServiceReplicas(ctx context.Context, dockerCLI command.Cli, serviceName string) (uint64, error)
- func ValidateStopServicesSelfReference(project, service string, refs []StopServiceRef) error
- func VerifyDockerAPIAccess() (error, error)
- func VerifyDockerAPIAccessContext(ctx context.Context) (error, error)
- func VerifyDockerHostConnectionContext(ctx context.Context, dockerHost string) error
- func VerifySocketConnection() error
- func VerifySocketConnectionContext(ctx context.Context) error
- func VerifySocketReadContext(ctx context.Context, httpClient *http.Client) error
- func WaitOnOneOffContainer(ctx context.Context, apiClient client.APIClient, containerID string) error
- func WaitOnSwarmOneOffService(ctx context.Context, dockerCLI command.Cli, serviceID string, ...) error
- func WithNormalizedEnvValues(p *types.Project, normMap map[string]string) *types.Project
- type ApplySelfOptions
- type CertificateRotationOptions
- type Change
- type ComposeHookLoader
- type ComposeHookPhase
- type ComposeLoadOptions
- type ComposeOneOffOptions
- type ContainerExitError
- type ContextClient
- type ContextClientResult
- type ContextRegistry
- func (r *ContextRegistry) Close() error
- func (r *ContextRegistry) Get(ctx context.Context, name string) (ContextClient, error)
- func (r *ContextRegistry) List(ctx context.Context) ([]ContextClientResult, error)
- func (r *ContextRegistry) Names() ([]string, error)
- func (r *ContextRegistry) Refresh() error
- type ContextRegistryOptions
- type DeployRequest
- type DeploymentAttempt
- type DeploymentDesiredState
- type DeploymentFailure
- type DeploymentFailureStore
- func (s *DeploymentFailureStore) Acquire(ctx context.Context, target DeploymentTarget) (func(), error)
- func (s *DeploymentFailureStore) Admit(target DeploymentTarget, desired DeploymentDesiredState, ...) (*DeploymentAttempt, *DeploymentRetrySuppression)
- func (s *DeploymentFailureStore) Clear(target DeploymentTarget)
- func (s *DeploymentFailureStore) Get(target DeploymentTarget) (DeploymentFailure, bool)
- type DeploymentRetrySuppression
- type DeploymentTarget
- type IgnoredInfo
- type JobExecutionMode
- type JobNotifyOn
- type JobScheduleConfig
- type Labels
- type LatestServiceStatus
- type OneOffContainerOptions
- type PhaseReporter
- type ScheduledComposeOptions
- type SelfDeployInput
- type SelfUpdateOptions
- type Service
- type ServiceMismatch
- type ServiceMismatchReason
- type ServiceStatus
- type SignalService
- type StopServiceRef
- type SwarmOneOffFromServiceOptions
- type SwarmRetentionOptions
Constants ¶
const ( RetryReasonDelay = "delay" RetryReasonBudgetExhausted = "budget_exhausted" )
const ( ServiceMismatchReasonNotDeployed = "service not deployed" ServiceMismatchReasonUnnecessary = "service is unnecessary" ServiceMismatchReasonSwarmMode = "swarm mode mismatch" ServiceMismatchReasonReplicas = "replicas mismatch" ServiceMismatchReasonContainers = "containers mismatch" )
const ( // ChangeTypeFailedDeployRetry marks a deployment retry after a recorded // failure. A Change of this type carries no service scope: the whole // project is force-recreated, because the failed part (e.g. a lifecycle // hook) is not attributable to one service. ChangeTypeFailedDeployRetry = "failed_deploy_retry" )
const ChangeTypeStaleArtifact = "stale_artifact"
ChangeTypeStaleArtifact marks services whose containers no longer see the artifact directory they were created from, because it was removed or published again since.
const DefaultContextName = "default"
const DefaultStopServicesTimeout = 30 * time.Second
DefaultStopServicesTimeout is the fallback timeout used when stopping a target declared via cd.doco.job.stop_services and neither an explicit cd.doco.job.stop_services.timeout override nor the target's own configured grace period (container StopTimeout / stop_grace_period, or Swarm service StopGracePeriod) is available.
const SelfApplierLabel = "cd.doco.self.applier"
SelfApplierLabel marks a throwaway applier container with its journal ID.
const SelfStackLabel = "cd.doco.self.stack"
SelfStackLabel names the stack an applier container is updating.
const (
SocketPath = "/var/run/docker.sock"
)
const ( // TestRemoteDockerImage is the Docker-in-Docker image version used in e2e tests. // Tracked by Renovate for automated updates . // Needs to be outside of test/ directory because Renovate ignores test/ by default. TestRemoteDockerImage = "docker:29-dind@sha256:0b6d18a4a222e71c88be6034926b4f6cde2fc33c2218643d03ccfddc65995470" )
Variables ¶
var ( ErrNoContainerToStart = errors.New("no container to start") ErrIsInUse = errors.New("is in use") ComposeVersion string // Version of the docker compose module, will be set at runtime )
var ( ErrComposeScheduledServiceReplicated = errors.New("standalone scheduled compose service must have exactly one replica") ErrComposeOneOffPreStartUnsupported = errors.New("pre_start hooks are not supported for Compose one_off jobs; use cd.doco.job.execution_mode=restart") // This can occur before the first poll fetches it, so timer-based callers should retry rather // than treat it as a deployment failure. ErrComposeScheduledSourceUnavailable = errors.New("deployment source not available on disk") )
var ( ErrDockerContextNotFound = errors.New("docker context not found") ErrContextRegistryClosed = errors.New("docker context registry is closed") )
var ( ErrNotAJobService = errors.New("service is not a job-mode service") ErrJobServiceRestartNotSupported = errors.New("restart not supported for job services") // ErrGlobalSwarmServiceNotScalable indicates a global/global-job service was // targeted by an operation that scales replicas, which Swarm does not allow. ErrGlobalSwarmServiceNotScalable = errors.New("global-mode swarm service cannot be scaled") )
var ( ErrMountPointNotFound = errors.New("mount point not found") ErrMountPointNotWriteable = errors.New("mount point is not writeable") ErrContainerIDNotFound = errors.New("container ID not found") )
var ( ErrDockerSocketConnectionFailed = errors.New("failed to connect to docker socket") ErrDockerHostConnectionFailed = errors.New("failed to connect to docker host") )
var DeploymentFailures = NewDeploymentFailureStore(nil)
DeploymentFailures is the process-local store shared by all trigger paths.
var DocoCDJobLabels = docoCDJobLabelNames
DocoCDJobLabels exposes the scheduler/job labels for consumers outside this package.
var DocoCDLabels = docoCdLabelNames{
Metadata: docoCDLabelNamesMetadata{
Manager: "cd.doco.metadata.manager",
Version: "cd.doco.metadata.version",
},
Deployment: docoCdLabelNamesDeployment{
Name: "cd.doco.deployment.name",
Timestamp: "cd.doco.deployment.timestamp",
ComposeHash: "cd.doco.deployment.compose.sha",
WorkingDir: "cd.doco.deployment.working_dir",
ConfigTarget: "cd.doco.deployment.config.target",
TargetRef: "cd.doco.deployment.target.ref",
CommitSHA: "cd.doco.deployment.target.sha",
Trigger: "cd.doco.deployment.trigger",
ConfigHash: "cd.doco.deployment.config.sha",
AutoDiscovery: "cd.doco.deployment.auto_discovery",
AutoDiscoveryConfig: "cd.doco.deployment.auto_discovery.config",
Autostart: "cd.doco.deployment.autostart",
OneShot: "cd.doco.deployment.one_shot",
RecreateIgnore: "cd.doco.deployment.recreate.ignore",
RecreateIgnoreSignal: "cd.doco.deployment.recreate.ignore.signal",
CertExpiry: "cd.doco.deployment.cert.expiry",
CertRotatable: "cd.doco.deployment.cert.rotatable",
CertState: "cd.doco.deployment.cert.state",
PinnedRevisions: "cd.doco.deployment.pinned_revisions",
LiveResources: "cd.doco.deployment.live_resources",
LifecycleHooks: "cd.doco.deployment.lifecycle_hooks",
},
Source: docoCdLabelNamesSource{
Type: "cd.doco.source",
Name: "cd.doco.source.name",
URL: "cd.doco.source.url",
ConfigRevision: "cd.doco.source.config.revision",
ConfigWorkingDir: "cd.doco.source.config.working_dir",
},
}
DocoCDLabels contains the label key names used by DocoCD to identify deployed containers and their metadata.
var ErrCertificateRotationPaused = errors.New("certificate rotation paused")
ErrCertificateRotationPaused marks a rotation intentionally skipped by admission.
var ErrComposeHookFailed = errors.New("compose lifecycle hook failed")
ErrComposeHookFailed reports that a Compose lifecycle hook did not complete successfully.
var ErrComposeServiceNotFound = errors.New("compose service not found")
ErrComposeServiceNotFound indicates that the requested service is not declared by the project.
var ErrComposeSourceRevisionConflict = errors.New("compose source revision conflict")
ErrComposeSourceRevisionConflict indicates that managed recreation cannot use the deployed source revision.
var ErrDeploymentModeConflict = errors.New("deployment mode migration conflicts with existing resources")
ErrDeploymentModeConflict means resources in the old deployment mode cannot safely be replaced because doco-cd cannot prove that it owns them.
var ErrIgnoreCfgInvalid = errors.New("ignore config is invalid")
var ErrNoSuchImage = errors.New("no such image") // Image does not exist
var ErrSwarmServiceAlreadyStopped = errors.New("swarm service is already scaled to 0 replicas")
ErrSwarmServiceAlreadyStopped indicates a replicated service was already scaled to 0 replicas, so there is nothing to stop or restore.
Functions ¶
func ApplySelfUpdate ¶ added in v0.122.0
ApplySelfUpdate replaces the doco-cd container named by the journal record. It runs inside a throwaway clone, so it survives the predecessor being stopped halfway through its own recreate.
func ArtifactStoreBase ¶ added in v0.124.0
ArtifactStoreBase returns the store of revision that path is nested under.
func AutoDiscoveryConfigsEqual ¶ added in v0.116.0
func AutoDiscoveryConfigsEqual(a, b deployConfig.AutoDiscoveryConfig) bool
AutoDiscoveryConfigsEqual reports whether two auto-discovery configs are equivalent. Compare normalized label values to support future complex fields (#1818).
func BuildSelfApplierCreate ¶ added in v0.122.0
func BuildSelfApplierCreate(inspect container.InspectResponse, journalID, stack string, drift bool) client.ContainerCreateOptions
BuildSelfApplierCreate derives the create options for a throwaway clone of the running doco-cd container that finishes the self-update from outside. drift reports whether the update recreates project networks.
func CheckDefaultComposeFiles ¶ added in v0.73.0
CheckDefaultComposeFiles checks if the default compose files are used and returns them if true.
func CheckMountPointWriteable ¶ added in v0.13.0
func CheckMountPointWriteable(mountPoint container.MountPoint) error
CheckMountPointWriteable checks if a mount point is writable by attempting to create a file in it.
func ClearDeploymentFailure ¶ added in v0.112.0
func ClearDeploymentFailure(repoName, stack string)
ClearDeploymentFailure removes the recorded failure for a given repository and stack, if any.
func ComposeSignal ¶ added in v0.77.0
func ComposeSignal(ctx context.Context, dockerCli command.Cli, project *types.Project, signal []SignalService) error
ComposeSignal will send signal to service.
func ConfigureSelfUpdate ¶ added in v0.122.0
func ConfigureSelfUpdate(o SelfUpdateOptions)
ConfigureSelfUpdate installs the process-wide self-update configuration.
func ConnectToSocketContext ¶ added in v0.114.0
ConnectToSocketContext connects to the Docker socket with context cancellation.
func CreateDockerCliWithContext ¶ added in v0.100.0
func DataMountPath ¶ added in v0.124.0
DataMountPath translates a Docker host path below the data mount into this container.
func DecryptProjectFiles ¶ added in v0.74.0
DecryptProjectFiles decrypts all files used in the compose project that are encrypted using doco-cd's encryption mechanism. This includes configs, secrets, bind mounts, env files and build contexts. Since absolute file paths in types.Project are paths on the docker host, repoPath also needs to be the external path to the repository. We use the symlink inside the container to follow the external path to the correct internal path.
func DeployStack ¶ added in v0.14.0
func DeployStack(ctx context.Context, req DeployRequest) error
DeployStack performs shared deployment lifecycle work and dispatches to the selected runtime.
func DeploySwarmStack ¶ added in v0.31.0
func DeploySwarmStack(ctx context.Context, dockerCli command.Cli, cfg *composetypes.Config, opts *options.Deploy) error
DeploySwarmStack deploys a Docker Swarm stack using the provided project and deploy configuration.
func DeployedArtifactDirs ¶ added in v0.124.0
DeployedArtifactDirs translates a service's mounted artifact paths into the data mount.
func DeployedServicesWithChangedDesiredImageDigests ¶ added in v0.128.0
func DeployedServicesWithChangedDesiredImageDigests(ctx context.Context, dockerCli command.Cli, swarmMode bool, project *types.Project, desired map[string]string, logger *slog.Logger) ([]string, error)
DeployedServicesWithChangedDesiredImageDigests reuses desired registry results for drift detection and retry admission rather than inspecting mutable tags twice within one attempt.
func DeployedServicesWithChangedImageDigests ¶ added in v0.110.0
func DeployedServicesWithChangedImageDigests(ctx context.Context, dockerCli command.Cli, swarmMode bool, project *types.Project, logger *slog.Logger) ([]string, error)
DeployedServicesWithChangedImageDigests returns the sorted names of deployed services whose image digest differs from the registry digest of the configured image ref.
This compares:
- deployed service image digest (currently running/deployed)
- registry digest of configured service image reference (DistributionInspect)
A service without a deployed digest is treated as changed.
func DeployedServicesWithChangedImageRefs ¶ added in v0.112.0
func DeployedServicesWithChangedImageRefs(ctx context.Context, dockerCli command.Cli, swarmMode bool, project *types.Project, logger *slog.Logger) ([]string, error)
DeployedServicesWithChangedImageRefs returns the sorted names of services whose configured image reference differs from the one currently deployed.
This is the tag-level counterpart of DeployedServicesWithChangedImageDigests. It answers "which services does this deployment move" for the ordinary case of a tag bump in the deploy config, where the digest comparison never runs because force_image_pull is off. It is local only, so it costs no registry lookups.
It deliberately under-reports rather than guess, because it feeds a notification and a wrong service name is worse than a missing one:
- nothing deployed yet, i.e. the first deployment of this stack, yields no services; the stack level notification already says the whole stack came up
- a service whose deployed reference cannot be determined is skipped
A service that is configured but has no deployed counterpart while other services do IS reported: it is genuinely arriving with this deployment.
func DeploymentModeMigrationRequired ¶ added in v0.120.0
func DeploymentModeMigrationRequired(ctx context.Context, dockerCli command.Cli, contextName, stackName, source string, swarmMode, swarmAvailable bool) (bool, error)
DeploymentModeMigrationRequired checks whether the previous runtime mode must be removed without mutating Docker state.
func DesiredProjectImageDigests ¶ added in v0.128.0
func DesiredProjectImageDigests(ctx context.Context, dockerCli command.Cli, project *types.Project, logger *slog.Logger) map[string]string
DesiredProjectImageDigests resolves immutable desired image identities without pulling layers or changing the deployed services. Unavailable digests are omitted so an inspection failure cannot reset an exhausted retry budget.
func DestroyStack ¶ added in v0.14.0
func DestroyStack( jobLog *slog.Logger, ctx *context.Context, dockerCli *command.Cli, deployConfig *deploy.Config, swarmMode bool, ) error
DestroyStack destroys the stack using the provided deployment configuration.
func DisplayContextName ¶ added in v0.113.0
DisplayContextName returns the display name for the given context name. If the name is empty, it returns the default context name.
func ExecContext ¶ added in v0.114.0
func ExtractOciArtifactTag ¶ added in v0.89.0
ExtractOciArtifactTag extracts the tag from OCI artifact references (e.g., "main" from "ghcr.io/kimdre/doco-cd_tests:main"). For Git references (e.g., "refs/heads/main", "feat/app/this", "v1.0.0-rc.1", "my/app"), it returns them as-is. For OCI artifact references with explicit tags, it returns the tag portion after the colon. For OCI artifact references with digests, it extracts the digest hash. If the reference has no tag or digest, it returns the original reference as-is (treated as Git reference).
func FailSelfUpdate ¶ added in v0.122.0
func FailSelfUpdate( ctx context.Context, dockerCli command.Cli, store *selfupdate.Store, journalID string, cause error, log *slog.Logger, ) error
FailSelfUpdate recovers from applier setup errors before ApplySelfUpdate. Its caller must exit nonzero on recovery failure so Docker retries.
func FindOneOffContainer ¶ added in v0.116.0
func FindOneOffContainer(ctx context.Context, apiClient client.APIClient, runID string) (string, error)
FindOneOffContainer finds the one retained ephemeral container for runID.
func FindSelfAppliers ¶ added in v0.122.0
func FindSelfAppliers(ctx context.Context, apiClient client.APIClient, stack string) ([]container.Summary, error)
FindSelfAppliers lists the applier containers for a stack, including exited ones.
func FindSwarmOneOffService ¶ added in v0.116.0
func FindSwarmOneOffService(ctx context.Context, dockerCLI command.Cli, runID string) (string, error)
FindSwarmOneOffService finds the single retained temporary service for runID.
func FormatPinnedRevisions ¶ added in v0.122.0
FormatPinnedRevisions returns the pinned revisions label value for revisions.
func GetAutoDiscoveryServices ¶ added in v0.113.0
func GetAutoDiscoveryServices(ctx context.Context, cli client.APIClient, swarmMode bool) (map[Service]map[string]string, error)
GetAutoDiscoveryServices returns auto-discovered workloads and migrates legacy auto-discovery labels to the current representation. Swarm service labels can be updated in place; standalone containers persist the normalized labels during the deployment that follows reconciliation.
func GetContainerID ¶ added in v0.13.0
GetContainerID retrieves the container ID for a given service name.
func GetDeploymentServices ¶ added in v0.124.0
func GetDeploymentServices(ctx context.Context, cli client.APIClient, swarmMode bool, stackName string) (map[Service]map[string]string, error)
GetDeploymentServices returns the labels of every swarm service or container of the deployment stackName, including stopped containers.
func GetLabeledConfigs ¶ added in v0.31.0
func GetLabeledConfigs(ctx context.Context, cli client.APIClient, key, value string) (configs []swarm.Config, err error)
GetLabeledConfigs retrieves all configs with a specific label key and value.
func GetLabeledContainers ¶ added in v0.13.0
func GetLabeledContainers(ctx context.Context, cli client.APIClient, key, value string, all bool) (containers []container.Summary, err error)
GetLabeledContainers retrieves all containers with a specific label key and value.
func GetLabeledSecrets ¶ added in v0.31.0
func GetLabeledSecrets(ctx context.Context, cli client.APIClient, key, value string) (secrets []swarm.Secret, err error)
GetLabeledSecrets retrieves all secrets with a specific label key and value.
func GetLabeledServices ¶ added in v0.54.0
func GetLabeledServices(ctx context.Context, cli client.APIClient, swarmMode bool, key, value string) (map[Service]map[string]string, error)
GetLabeledServices retrieves all services with a specific label key and value, along with their labels.
func GetLabeledVolumes ¶ added in v0.31.0
func GetLabeledVolumes(ctx context.Context, cli client.APIClient, key, value string) (volumes []volume.Volume, err error)
GetLabeledVolumes retrieves all volumes with a specific label key and value.
func GetMountPointByDestination ¶ added in v0.13.0
func GetMountPointByDestination(ctx context.Context, cli client.APIClient, containerID, destination string) (container.MountPoint, error)
GetMountPointByDestination retrieves the mount point of a container volume/bind mount by its destination (mount point inside the container).
func GetPathsFromGitChangedFiles ¶ added in v0.77.0
func GetPathsFromGitChangedFiles(changedFiles []gitInternal.ChangedFile, basePath string) []string
func GetProjectContainers ¶ added in v0.55.0
func GetProjectContainers(ctx context.Context, dockerCli command.Cli, projectName string) ([]api.ContainerSummary, error)
GetProjectContainers returns the status of all services in the specified project.
func GetProjects ¶ added in v0.33.0
func GetProjects(ctx context.Context, dockerCli command.Cli, showDisabled bool) ([]api.Stack, error)
GetProjects returns a list of all projects.
func GetServiceLabels ¶ added in v0.54.0
func GetServiceLabels(ctx context.Context, cli client.APIClient, swarmMode bool, stackName string) (map[Service]Labels, error)
GetServiceLabels retrieves the Labels for each Service in a given stack.
func GetServicesWithLabelKey ¶ added in v0.120.0
func GetServicesWithLabelKey(ctx context.Context, cli client.APIClient, swarmMode bool, labelKey string) (map[Service]map[string]string, error)
GetServicesWithLabelKey retrieves every container or swarm service that carries labelKey, regardless of its value, along with its labels. Like getContainersWithLabelKey/swarm.GetServicesByLabelKey, this is for discovery scans (e.g. garbage collection) that need to enumerate every doco-cd-managed deployment without knowing any label's value - or the deployment's stack name - in advance.
Containers are listed with all=true, so a stopped-but-still-deployed stack is reported the same as a running one: it is still deployed and its on-disk source artifact is still in use.
func HasChangedBindMounts ¶ added in v0.29.0
func HasChangedBindMounts(repoPathExternal string, paths []string, project *types.Project, ignoreCfg projectIgnoreCfg) ([]string, []string)
HasChangedBindMounts checks if any files used in docker compose `volumes:` definitions with type `bind` have changed using the Git status.
func HasChangedBuildFiles ¶ added in v0.73.0
func HasChangedBuildFiles(repoPathExternal string, paths []string, project *types.Project, _ projectIgnoreCfg) ([]string, []string)
HasChangedBuildFiles checks if any files used as build context in docker compose `build:` definitions have changed using the Git status. This includes any file within the build context directory for each service. If a changed file is within a build context, it returns true.
func HasChangedConfigs ¶ added in v0.29.0
func HasChangedConfigs(repoPathExternal string, paths []string, project *types.Project, ignoreCfg projectIgnoreCfg) ([]string, []string)
HasChangedConfigs checks if any files used in docker compose `configs:` definitions have changed using the Git status.
func HasChangedEnvFiles ¶ added in v0.31.1
func HasChangedEnvFiles(repoPathExternal string, paths []string, project *types.Project, _ projectIgnoreCfg) ([]string, []string)
HasChangedEnvFiles checks if any files used in docker compose `env_file:` definitions have changed using the Git status.
func HasChangedSecrets ¶ added in v0.29.0
func HasChangedSecrets(repoPathExternal string, paths []string, project *types.Project, ignoreCfg projectIgnoreCfg) ([]string, []string)
HasChangedSecrets checks if any files used in docker compose `secrets:` definitions have changed using the Git status.
func HasComposeHooks ¶ added in v0.128.0
func HasComposeHooks(service types.ServiceConfig, phase ComposeHookPhase) bool
HasComposeHooks reports whether the service declares hooks for the phase.
func InspectContainerState ¶ added in v0.115.0
func InspectContainerState(ctx context.Context, apiClient client.APIClient, containerID string) (*container.State, error)
InspectContainerState inspects the state of a specific container.
func IsComposeHookContainerUnavailable ¶ added in v0.128.0
IsComposeHookContainerUnavailable reports whether a hook failed because its container is not running or no longer exists. Compose skips the stop of such a container, because the container is already stopped.
func IsSelfStack ¶ added in v0.122.0
IsSelfStack reports whether a deploy config targets the stack that contains this doco-cd instance.
func ListManagedRepositoryContainers ¶ added in v0.115.0
func ListManagedRepositoryContainers(ctx context.Context, apiClient client.APIClient, repository string, all bool) ([]container.Summary, error)
ListManagedRepositoryContainers lists all containers that belong to a specific repository.
func ListManagedRepositoryServices ¶ added in v0.115.0
func ListManagedRepositoryServices(ctx context.Context, apiClient client.APIClient, repository string) ([]swarm.Service, error)
ListManagedRepositoryServices lists all services that belong to a specific repository.
func LoadCompose ¶
func LoadCompose(ctx context.Context, dockerCli command.Cli, repoPath, workingDir, projectName string, composeFiles, envFiles, profiles []string, environment map[string]string, opts ComposeLoadOptions, ) (*types.Project, error)
LoadCompose parses and loads Compose files as specified by the Docker Compose specification. dockerCli is required to load OCI artifact includes. opts bundles the Docker-owned settings (env passthrough, Git/OCI remote include configuration) needed beyond the compose project parameters themselves; callers resolve it explicitly (see NewComposeLoadOptions) instead of LoadCompose reading the application configuration itself.
func LoadSwarmStack ¶ added in v0.73.0
func LoadSwarmStack(dockerCli command.Cli, project *types.Project, deployConfig *deploy.Config, externalWorkingDir string, ) (*composetypes.Config, *options.Deploy, error)
LoadSwarmStack loads a Docker Swarm stack using the provided project and deploy configuration.
func MarshalAutoDiscoveryConfig ¶ added in v0.89.0
func MarshalAutoDiscoveryConfig(cfg deployConfig.AutoDiscoveryConfig) string
MarshalAutoDiscoveryConfig serializes an AutoDiscoveryConfig to a single-line YAML flow-style string for use as a container label.
func MayHaveComposeHooks ¶ added in v0.128.0
func MayHaveComposeHooks(labels map[string]string, phases ...ComposeHookPhase) bool
MayHaveComposeHooks reports whether the service of a container can have hooks of one of the phases. Loading the deployed project to find the hooks is costly, because it resolves external secrets. The lifecycle hooks label lets doco-cd skip the load for services without hooks. Containers that older doco-cd versions created do not have the label. Their hooks are known only after the load.
Compose recreates a container when its hooks change, so the label always matches the deployed hooks.
func MigrateDeploymentMode ¶ added in v0.114.0
func MigrateDeploymentMode(ctx context.Context, log *slog.Logger, dockerCli command.Cli, contextName, stackName, source string, swarmMode, swarmAvailable bool) (bool, error)
MigrateDeploymentMode removes a previous deployment in the other runtime mode, but only after proving every discovered resource belongs to this doco-cd deployment. Volumes are deliberately retained for the new mode. It reports whether previous-mode resources were removed.
func NewHttpClient ¶
func NormalizeContextName ¶ added in v0.113.0
NormalizeContextName normalizes the given context name by trimming whitespace and converting the default context name to an empty string.
func NormalizeRepositoryLabel ¶ added in v0.120.0
NormalizeRepositoryLabel exposes normalizeRepositoryForLabelMatch for callers outside this package that need to map a deployed container or service's cd.doco.source.name label back to the on-disk repository directory name (git.GetRepoName for Git sources, the repository portion of an OCI artifact reference for OCI sources) - the same normalization GetLatestDeployStatus already relies on for label matching. Used by artifact garbage collection (internal/gc) to build its live-revision set.
func ParseAutoDiscoveryConfig ¶ added in v0.89.0
func ParseAutoDiscoveryConfig(labelValue string) deployConfig.AutoDiscoveryConfig
ParseAutoDiscoveryConfig deserializes an AutoDiscoveryConfig from a YAML container label value. An empty or invalid label returns a config that deletes and removes nothing: the label decides whether a stack may be removed, so a label that cannot be read must not allow it.
func ParseJobScheduleExpression ¶ added in v0.86.0
ParseJobScheduleExpression parses a job schedule in the local timezone (TZ). It uses the 5-field cron format with descriptors and @every durations; seconds are intentionally unsupported.
func ParsePinnedRevisions ¶ added in v0.122.0
ParsePinnedRevisions returns the revisions listed in a pinned revisions label value (see DocoCDLabels.Deployment.PinnedRevisions), ignoring empty entries.
func ProjectFilesHaveChanges ¶ added in v0.31.1
func ProjectFilesHaveChanges(repoPathExternal string, changePaths []string, project *types.Project) ([]Change, IgnoredInfo, error)
ProjectFilesHaveChanges checks if any files related to the compose project have changed.
func ProjectHash ¶ added in v0.73.0
ProjectHash generates a SHA256 hash of the project configuration to be used for detecting changes in the project that may require a redeployment.
sourceRoot is the on-disk directory the project was loaded from. When set, absolute paths below it are normalized so the hash stays stable across revisions of the same unchanged stack.
func ProjectPathFilter ¶ added in v0.118.1
func ProjectPathFilter(repoPath string, p *types.Project, extraRepoPaths ...string) (func(string) bool, error)
ProjectPathFilter builds a filter for git.LogOptions.PathFilter that matches the file set of a compose project, so a commit log can be reduced to the commits that touch this stack. go-git reports paths relative to the root of the repository, so the file set is converted to that form. Files match exactly, directories match everything below them.
repoPath is the path to the repository on the docker host, like the absolute paths in types.Project.
extraRepoPaths are files that belong to the stack without being part of the compose project, relative to the repository root. The deployment configuration is the motivating case: it declares the stack and carries its image tags, so a commit that changes only it is the reason the deploy happened, but the project never names it. They are relative and not absolute because the deployment configuration is read inside the doco-cd container, while the project lives on the docker host: /data/... never matches /var/lib/docker/....
The returned filter is nil when the project covers the repository root or resolves to no path inside the repository. Both match every path, so filtering would only cost tree diffs, and callers read a nil filter as "do not filter".
func PruneStackConfigs ¶ added in v0.31.0
func PruneStackConfigs(ctx context.Context, client dockerClient.APIClient, namespace string, keepOldRevisions int) error
PruneStackConfigs removes old revisions of configs in a Docker Swarm stack, keeping only the specified number of recent revisions.
func PruneStackSecrets ¶ added in v0.31.0
func PruneStackSecrets(ctx context.Context, client dockerClient.APIClient, namespace string, keepOldRevisions int) error
PruneStackSecrets removes old revisions of secrets in a Docker Swarm stack, keeping only the specified number of recent revisions.
func PullImages ¶ added in v0.55.0
PullImages pulls all images defined in the named compose project.
func RecordDeployStatus ¶ added in v0.122.0
func RecordDeployStatus(repoName, stack, commitSHA, composeHash string)
RecordDeployStatus lets a successor record the deploy status of a handover it finished on behalf of the process that started it.
func RecordDeploymentFailure ¶ added in v0.112.0
func RecordDeploymentFailure(repoName, stack string, failure DeploymentFailure)
RecordDeploymentFailure is a convenience function to record a failure without going through the full DeploymentAttempt lifecycle. It is used for immediate failure recording scenarios.
func RecreateProject ¶ added in v0.117.0
func RecreateProject( ctx context.Context, contextName string, dockerCli command.Cli, projectName string, serviceName string, timeout time.Duration, secretProvider secretprovider.SecretProvider, opts ScheduledComposeOptions, ) error
RecreateProject recreates services in the specified project. If serviceName is empty, all services are recreated. If serviceName is specified, only that service is recreated.
func ReleaseSelfApplierRestartLimit ¶ added in v0.122.0
func ReleaseSelfApplierRestartLimit(ctx context.Context, apiClient client.APIClient, applierID string) error
ReleaseSelfApplierRestartLimit lets Docker restart the applier without a bound. The predecessor calls it right before it drains, after which only the applier can finish or roll back the handover.
func RemoveLabeledVolumes ¶ added in v0.31.0
func RemoveOneOffContainer ¶ added in v0.116.0
func RemoveOneOffContainer(ctx context.Context, apiClient client.APIClient, containerID string) error
RemoveOneOffContainer removes a retained one-off container after reporting.
func RemoveProject ¶ added in v0.33.0
func RemoveProject(ctx context.Context, dockerCli command.Cli, projectName string, timeout time.Duration, removeVolumes, removeImages bool) error
RemoveProject removes the entire project including containers, networks, volumes and images.
func RemoveSelfApplier ¶ added in v0.122.0
RemoveSelfApplier deletes a finished applier container.
func RemoveSwarmOneOffService ¶ added in v0.116.0
func RemoveSwarmOneOffService(ctx context.Context, dockerCLI command.Cli, serviceID string, logs ...*slog.Logger) error
RemoveSwarmOneOffService removes a retained temporary job service.
func RemoveSwarmStack ¶ added in v0.31.0
RemoveSwarmStack removes a Docker Swarm stack using the provided deploy configuration.
func RemoveSwarmStackWithLogger ¶ added in v0.123.0
func RemoveSwarmStackWithLogger(ctx context.Context, dockerCli command.Cli, namespace string, log *slog.Logger) error
RemoveSwarmStackWithLogger records per-service removal details with the caller's logger.
func RepoRelativePath ¶ added in v0.122.0
RepoRelativePath converts an absolute path to the repository-relative, slash-separated form go-git reports in a commit log. ok is false when the path is not inside repoPath, which is how a host path or a remote include is dropped.
repoPath and absPath must be on the same side of the data mount: both on the docker host, or both inside the doco-cd container.
func RepositoryLabelMatches ¶ added in v0.124.0
RepositoryLabelMatches reports whether label, a cd.doco.source.name label value, names one of repositories, matched like GetLatestDeployStatus matches it. A repository can be a repository name or URL, or an OCI artifact reference whose tag or digest is ignored.
func RerunJobService ¶ added in v0.62.0
RerunJobService attempts to retrigger a Swarm job service (`replicated-job` or `global-job`) by updating the service spec (bumping a dummy label), causing Swarm to create new job tasks.
Note: Swarm does not allow UpdateConfig / RollbackConfig on job-mode services, so we must strip those fields before calling ServiceUpdate.
func RestartContainer ¶ added in v0.86.0
func RestartContainerAndWait ¶ added in v0.104.0
func RestartContainerAndWait(ctx context.Context, apiClient client.APIClient, containerID string) error
RestartContainerAndWait starts or restarts the container (identically to RestartContainer) and then blocks until the container exits. This is the blocking variant of RestartContainer used when stop_services requires knowing when the job has finished.
For a stopped container the wait is subscribed BEFORE starting to avoid racing with a fast-exiting container. For a running container, ContainerRestart is called first (it blocks until the container is running again after the restart cycle), and then the wait includes an exit that happened before the restart request returned.
func RestartProject ¶ added in v0.33.0
func RestartProject(ctx context.Context, dockerCli command.Cli, projectName string, timeout time.Duration) error
RestartProject restarts all services in the specified project.
func RestartScheduledSwarmService ¶ added in v0.101.0
func RestartScheduledSwarmService(ctx context.Context, dockerCLI command.Cli, serviceName string) error
RestartScheduledSwarmService runs a restart-mode scheduled Swarm service on its schedule. Classic replicated scheduled services are deployed at 0 replicas so they do not run on deployment; this scales them up to their intended replica count (forcing a task re-run) when the schedule fires. Services that cannot be scaled to 0 (e.g. global) fall back to a ForceUpdate bump.
func RestartService ¶ added in v0.62.0
RestartService restarts long-running Swarm services by bumping ForceUpdate. For job-mode services (replicated-job/global-job), it returns ErrJobServiceRestartNotSupported.
func RestoreCreateFromSnapshot ¶ added in v0.122.0
func RestoreCreateFromSnapshot(snap container.InspectResponse) client.ContainerCreateOptions
RestoreCreateFromSnapshot derives create options that bring back the exact container a self-update replaced. The image is pinned to the snapshot's image ID, not its tag, so a moved tag cannot change what comes back.
func RotateProjectCertificates ¶ added in v0.110.0
func RotateProjectCertificates( ctx context.Context, contextName string, dockerCli command.Cli, labels map[string]string, secretProvider secretprovider.SecretProvider, swarmMode bool, opts CertificateRotationOptions, ) error
RotateProjectCertificates reloads the deploy config for a rotatable deployment (identified by its doco-cd labels, see DocoCDLabels.Deployment.CertRotatable), re-resolves its external secrets (reissuing any pki-role certificates through the configured secret provider), and redeploys so the fresh values take effect.
contextName identifies the Docker context dockerCli was created for (empty for the local default context, see NormalizeContextName/DisplayContextName); it namespaces the per-stack scheduler/deploy lock (see lock.StackKey) and identifies the target to opts.Admission. Discovered resources need no extra "context" label: the caller (certrotation.Watcher) already knows which context's client produced labels, since it scans one context's resources at a time.
Compose deployments only recreate the services actually consuming a rotated certificate/key. Swarm stacks redeploy the whole stack, but Swarm's own spec diffing (see stableSwarmMetadataLabels) still limits recreation to the affected services.
func RunComposeHooks ¶ added in v0.128.0
func RunComposeHooks(ctx context.Context, apiClient client.APIClient, containerID string, service types.ServiceConfig, phase ComposeHookPhase) error
RunComposeHooks runs the pre_stop or post_start hooks of a service in a running container. doco-cd calls it when it stops, starts, or restarts a container through the Docker API. Like Compose, each hook runs as an exec process, and the first failed hook stops the sequence.
func RunComposeOneOffFromServiceDefinition ¶ added in v0.107.0
func RunComposeOneOffFromServiceDefinition( ctx context.Context, dockerCli command.Cli, labels map[string]string, secretProvider secretprovider.SecretProvider, opts ScheduledComposeOptions, ) error
func RunComposeOneOffFromServiceDefinitionWithOptions ¶ added in v0.116.0
func RunComposeOneOffFromServiceDefinitionWithOptions( ctx context.Context, dockerCli command.Cli, labels map[string]string, secretProvider secretprovider.SecretProvider, opts ScheduledComposeOptions, runOpts ComposeOneOffOptions, ) error
RunComposeOneOffFromServiceDefinitionWithOptions runs a Compose service as a retained one-off when RunID is set, allowing a replacement process to inspect and finalize it after a forced termination.
func RunComposeScheduledContainer ¶ added in v0.107.0
func RunComposeScheduledContainer( ctx context.Context, dockerCli command.Cli, containerID string, labels map[string]string, waitForExit bool, secretProvider secretprovider.SecretProvider, opts ScheduledComposeOptions, ) error
func RunContainerOneOffFromExisting ¶ added in v0.88.0
func RunContainerOneOffFromExistingWithOptions ¶ added in v0.116.0
func RunContainerOneOffFromExistingWithOptions(ctx context.Context, apiClient client.APIClient, containerID string, opts OneOffContainerOptions) error
RunContainerOneOffFromExistingWithOptions starts a disposable clone of containerID. A run ID retains the completed clone for crash recovery; callers must remove it with RemoveOneOffContainer when finalization is complete.
func RunImagePruneJob ¶ added in v0.54.0
RunImagePruneJob runs a Docker Swarm global job to prune unused images on all nodes.
func RunImageRemoveJob ¶ added in v0.54.0
func RunImageRemoveJob(ctx context.Context, dockerCLI command.Cli, images []string, logs ...*slog.Logger) error
RunImageRemoveJob runs a Docker Swarm global job to remove specified images.
func RunSwarmJob ¶ added in v0.54.0
func RunSwarmJob(ctx context.Context, dockerCLI command.Cli, mode swarm.DeployMode, command []string, title string, logs ...*slog.Logger) error
RunSwarmJob runs a Docker Swarm job container with the specified mode and command. https://docs.docker.com/reference/cli/docker/service/create/#running-as-a-job
func RunSwarmOneOffFromService ¶ added in v0.88.0
func RunSwarmOneOffFromService(ctx context.Context, dockerCLI command.Cli, serviceName string, opts SwarmOneOffFromServiceOptions) (err error)
RunSwarmOneOffFromService creates a temporary job service from an existing service spec and waits for completion.
func SetConfigHashPrefixes ¶ added in v0.31.0
func SetConfigHashPrefixes(stack *composetypes.Config, namespace string) error
SetConfigHashPrefixes generates hashes for the config definitions in the stack config and adds them to the config names as suffixes to trigger a redeployment when they change (Only works in Docker Swarm mode).
func SetSecretHashPrefixes ¶ added in v0.31.0
func SetSecretHashPrefixes(stack *composetypes.Config, namespace string) error
SetSecretHashPrefixes generates hashes for the secret definitions in the stack config and adds them to the secret names as suffixes to trigger a redeployment when they change (Only works in Docker Swarm mode).
func SourceTypeLabelValue ¶ added in v0.89.0
SourceTypeLabelValue resolves a stable label value ("git" or "oci") from a primary source, with a fallback (e.g. deploy config source) when the primary is empty or unknown.
func StartProject ¶ added in v0.33.0
func StartProject(ctx context.Context, dockerCli command.Cli, projectName string, timeout time.Duration) error
StartProject starts all services in the specified project.
func StartProjectServices ¶ added in v0.104.0
func StartProjectServices(ctx context.Context, dockerCli command.Cli, projectName string, services []string, hooks *ComposeHookLoader) error
StartProjectServices starts specific named services within a compose project. Services are identified by their service name as declared in the compose file (the map key under `services:`), not by container_name.
Note: the compose Start API ignores StartOptions.Services, so containers are looked up directly by the com.docker.compose.project and com.docker.compose.service labels and started individually. Compose lifecycle-hook runner containers are skipped.
This is best-effort: if starting one container fails, the remaining containers are still attempted, and all failures are aggregated into the returned error.
When hooks is not nil, a service with pre_start or post_start hooks starts through Compose, like with `docker compose start`. doco-cd prepares fresh pre_start runners for it first. Services without these hooks still start directly.
func StartSwarmService ¶ added in v0.104.0
func StartSwarmService(ctx context.Context, dockerCLI command.Cli, serviceName string, replicas uint64) error
StartSwarmService restores a previously stopped swarm service to the given replica count. It is the counterpart to StopSwarmService and is typically called in a deferred function to guarantee the service is restarted even when the scheduled job fails.
A replicas value of 0 means StopSwarmService never actually stopped the service (global-mode, or already scaled to 0), so there is nothing to restore.
The serviceName must be the full swarm-scoped name (e.g. "mystack_myservice").
func StopProject ¶ added in v0.33.0
func StopProject(ctx context.Context, dockerCli command.Cli, projectName string, timeout time.Duration) error
StopProject stops all services in the specified project.
func StopProjectServices ¶ added in v0.104.0
func StopProjectServices(ctx context.Context, dockerCli command.Cli, projectName string, services []string, timeoutOverride *time.Duration, hooks *ComposeHookLoader) error
StopProjectServices stops specific named services within a compose project. Services are identified by their service name as declared in the compose file (the map key under `services:`), not by container_name.
Containers are stopped directly via the Docker API (instead of compose Stop with a services filter) to ensure only explicitly targeted services are affected, without implicit dependency traversal.
timeoutOverride, when non-nil, is used explicitly for every targeted container (this is how cd.doco.job.stop_services.timeout is applied). When nil, each container's own configured stop timeout (populated from the compose file's stop_grace_period) is honored by leaving the stop request's timeout unset, letting the Docker engine apply it; DefaultStopServicesTimeout is only used explicitly as a fallback for containers that have no stop timeout configured.
This is best-effort: if stopping one container fails, the remaining containers are still attempted, and all failures are aggregated into the returned error.
When hooks is not nil, the pre_stop hooks of each service run before its containers stop, like with `docker compose stop`. A failed hook keeps its container running and is reported as an error.
func StopSwarmService ¶ added in v0.104.0
func StopSwarmService(ctx context.Context, dockerCLI command.Cli, serviceName string, timeoutOverride *time.Duration) (originalReplicas uint64, err error)
StopSwarmService temporarily stops a swarm service by scaling it to 0 replicas and waiting until its tasks have actually terminated. It returns the original replica count so the caller can restore it later via StartSwarmService.
Waiting matters for the primary use case of this feature (consistent cold backups): ServiceUpdate only records the intent to scale down, so without waiting the scheduled job would start while the target's containers are still shutting down and flushing to disk.
timeoutOverride, when non-nil, is used explicitly as the wait deadline (this is how cd.doco.job.stop_services.timeout is applied). When nil, the service's own configured Spec.TaskTemplate.ContainerSpec.StopGracePeriod is honored (plus a small buffer for scheduling overhead), falling back to DefaultStopServicesTimeout if the service has no grace period configured. This prevents a service declaring a long grace period from having its shutdown wait time out prematurely.
Global-mode services cannot be scaled to 0; the function returns (0, ErrGlobalSwarmServiceNotScalable) so the caller can skip them gracefully. A replicated service that is already at 0 replicas returns (0, ErrSwarmServiceAlreadyStopped).
The serviceName must be the full swarm-scoped name (e.g. "mystack_myservice"). In the cd.doco.job.stop_services label, cross-stack services are expressed as "stack/service" and resolved to "stack_service" before calling this function.
func SwarmServiceReplicas ¶ added in v0.116.0
func SwarmServiceReplicas(ctx context.Context, dockerCLI command.Cli, serviceName string) (uint64, error)
SwarmServiceReplicas returns the desired replica count before a service is scaled down. Global services return ErrGlobalSwarmServiceNotScalable.
func ValidateStopServicesSelfReference ¶ added in v0.104.0
func ValidateStopServicesSelfReference(project, service string, refs []StopServiceRef) error
ValidateStopServicesSelfReference returns an error if refs contains an entry that resolves to the job's own project/stack and service name, which would cause the scheduler to stop the job's own service right before running it.
This cannot be checked inside ParseJobScheduleLabels because it only has access to the raw label map: standalone/compose containers always carry com.docker.compose.project/com.docker.compose.service labels, but Swarm services deployed by doco-cd do not carry those labels on the task spec, so the job's own project/service identity must be resolved by the caller (which knows how to derive it for both compose and Swarm jobs) and passed in explicitly.
func VerifyDockerAPIAccess ¶ added in v0.58.0
VerifyDockerAPIAccess verifies access to the Docker API either via DOCKER_HOST or the default socket.
func VerifyDockerAPIAccessContext ¶ added in v0.114.0
VerifyDockerAPIAccessContext verifies access to the Docker API with context cancellation.
func VerifyDockerHostConnectionContext ¶ added in v0.114.0
VerifyDockerHostConnectionContext verifies the connection to the specified DOCKER_HOST with context cancellation.
func VerifySocketConnection ¶
func VerifySocketConnection() error
VerifySocketConnection verifies whether the application can connect to the docker socket.
func VerifySocketConnectionContext ¶ added in v0.114.0
VerifySocketConnectionContext verifies whether the application can connect to the Docker socket with context cancellation.
func VerifySocketReadContext ¶ added in v0.114.0
VerifySocketReadContext verifies whether the application can read from the Docker socket with context cancellation.
func WaitOnOneOffContainer ¶ added in v0.116.0
func WaitOnOneOffContainer(ctx context.Context, apiClient client.APIClient, containerID string) error
WaitOnOneOffContainer waits for a retained container to stop and returns its exit result. It is safe to call for an already-exited container.
func WaitOnSwarmOneOffService ¶ added in v0.116.0
func WaitOnSwarmOneOffService(ctx context.Context, dockerCLI command.Cli, serviceID string, logs ...*slog.Logger) error
WaitOnSwarmOneOffService adopts a retained temporary job service.
func WithNormalizedEnvValues ¶ added in v0.110.0
WithNormalizedEnvValues returns a copy of the project where any service environment value or top-level config/secret content matching a key in normMap is replaced with the corresponding placeholder. Use this to produce a stable project hash when secrets are re-issued on every resolution (e.g. pki-role certs), so the hash only changes when the ref itself changes.
Types ¶
type ApplySelfOptions ¶ added in v0.122.0
type ApplySelfOptions struct {
Store *selfupdate.Store
JournalID string
SecretProvider secretprovider.SecretProvider
Scheduled ScheduledComposeOptions
Log *slog.Logger
DataMountPath string
}
ApplySelfOptions configures a single run of the self-update applier.
type CertificateRotationOptions ¶ added in v0.115.0
type CertificateRotationOptions struct {
Scheduled ScheduledComposeOptions
SwarmRetention SwarmRetentionOptions
// Admission is checked under the stack lock before source loading or certificate reissuance.
// Nil permits rotation; false intentionally skips it.
Admission func(contextName string, labels map[string]string) bool
}
CertificateRotationOptions bundles the settings needed by RotateProjectCertificates to reload the project and apply the shared Swarm retention policy after a rotation redeploy.
func NewCertificateRotationOptions ¶ added in v0.115.0
func NewCertificateRotationOptions(c *app.Config) CertificateRotationOptions
NewCertificateRotationOptions builds CertificateRotationOptions from the application configuration. Call this once at a composition/stage boundary and pass the result down explicitly.
type ComposeHookLoader ¶ added in v0.128.0
type ComposeHookLoader struct {
SecretProvider secretprovider.SecretProvider
Options ScheduledComposeOptions
Logger *slog.Logger
// contains filtered or unexported fields
}
ComposeHookLoader loads deployed Compose service definitions for lifecycle hooks. Container labels do not contain hook definitions, so doco-cd reloads the deployed project.
func (*ComposeHookLoader) HookService ¶ added in v0.128.0
func (l *ComposeHookLoader) HookService(ctx context.Context, dockerCli command.Cli, labels map[string]string) (types.ServiceConfig, bool)
HookService returns the deployed service definition of the container that the labels describe. If the definition cannot be loaded, it logs the reason and returns false. The caller then continues without lifecycle hooks, as before.
func (*ComposeHookLoader) LoadServiceProject ¶ added in v0.128.0
func (l *ComposeHookLoader) LoadServiceProject(ctx context.Context, dockerCli command.Cli, labels map[string]string) (*types.Project, error)
LoadServiceProject loads the deployed project of the container that the labels describe. The returned project contains only the service of that container.
type ComposeHookPhase ¶ added in v0.128.0
type ComposeHookPhase string
ComposeHookPhase identifies a Compose lifecycle hook phase. pre_start hooks run in separate runner containers. post_start and pre_stop hooks run in the service container.
const ( ComposeHookPreStart ComposeHookPhase = "pre_start" ComposeHookPostStart ComposeHookPhase = "post_start" ComposeHookPreStop ComposeHookPhase = "pre_stop" )
type ComposeLoadOptions ¶ added in v0.115.0
type ComposeLoadOptions struct {
// PassEnv controls whether the doco-cd process's own OS environment variables are passed
// through to the compose project for variable interpolation.
PassEnv bool
// SkipTLSVerify skips TLS verification when following Git remote includes.
SkipTLSVerify bool
// HttpProxy configures the proxy used when following Git remote includes.
HttpProxy transport.ProxyOptions
// GitCloneSubmodules controls whether submodules are cloned for Git remote includes.
GitCloneSubmodules bool
// GitCloneDepth limits the number of commits fetched for Git remote includes. 0 means a full clone.
GitCloneDepth int
// SSHPrivateKey and SSHPrivateKeyPassphrase configure SSH authentication for Git remote includes.
SSHPrivateKey string
SSHPrivateKeyPassphrase string
// GitAccessToken configures HTTP(S) authentication for Git remote includes.
GitAccessToken string
// OciInsecureRegistries lists registries for OCI Compose includes with TLS verification disabled.
OciInsecureRegistries []string
// DataHostPath and DataMountPath are used as a fallback base directory for the Git include
// cache when the repository path passed to LoadCompose is empty. DataHostPath (the Docker
// daemon host path) is preferred since the cache must be reachable outside the container by
// the daemon performing the checkout.
DataHostPath string
DataMountPath string
// MutationLock, when non-nil, serializes in-place SOPS decryption. Project parsing,
// referenced-file decryption, and the conditional reload form one atomic phase so
// every caller observes the files it parsed in a consistent state.
//
// Callers that need cross-goroutine mutual exclusion (e.g. multiple deployments touching
// the same repository checkout concurrently) should supply a shared lock such as a
// *sync.Mutex or the repository-scoped lock.GetRepoLock(repoName). LoadCompose does not
// require any particular lock granularity and does not create or own the lock itself.
// If nil, no locking is performed.
MutationLock sync.Locker
}
ComposeLoadOptions bundles the Docker-owned settings LoadCompose needs beyond the individual compose project parameters (compose/env files, profiles, environment). These settings originate in the application configuration, but callers resolve and pass them in explicitly at a composition/stage boundary (see NewComposeLoadOptions) instead of letting LoadCompose read the application configuration itself. This keeps LoadCompose free of hidden environment reads.
func NewComposeLoadOptions ¶ added in v0.115.0
func NewComposeLoadOptions(c *app.Config) ComposeLoadOptions
NewComposeLoadOptions builds the ComposeLoadOptions LoadCompose needs from the application configuration. Call this once at a composition/stage boundary and pass the result down explicitly, rather than letting deep Docker helpers read the application configuration themselves.
type ComposeOneOffOptions ¶ added in v0.116.0
type ContainerExitError ¶ added in v0.101.0
ContainerExitError reports that a container finished with a non-zero exit code. Callers can use errors.As to recover the exit code without parsing error strings.
func (*ContainerExitError) Error ¶ added in v0.101.0
func (e *ContainerExitError) Error() string
type ContextClient ¶ added in v0.113.0
func (ContextClient) DisplayName ¶ added in v0.113.0
func (c ContextClient) DisplayName() string
type ContextClientResult ¶ added in v0.113.0
type ContextClientResult struct {
ContextClient
Err error
}
type ContextRegistry ¶ added in v0.113.0
type ContextRegistry struct {
// contains filtered or unexported fields
}
func NewContextRegistry ¶ added in v0.113.0
func NewContextRegistry(baseCli command.Cli, options ContextRegistryOptions) *ContextRegistry
NewContextRegistry creates a new ContextRegistry for the configured Docker runtime features.
func (*ContextRegistry) Close ¶ added in v0.113.0
func (r *ContextRegistry) Close() error
Close closes all docker clients in the registry and marks the registry as closed.
func (*ContextRegistry) Get ¶ added in v0.113.0
func (r *ContextRegistry) Get(ctx context.Context, name string) (ContextClient, error)
Get returns a ContextClient for the given context name.
func (*ContextRegistry) List ¶ added in v0.113.0
func (r *ContextRegistry) List(ctx context.Context) ([]ContextClientResult, error)
List returns a list of ContextClientResult for all available docker contexts in the registry.
func (*ContextRegistry) Names ¶ added in v0.113.0
func (r *ContextRegistry) Names() ([]string, error)
Names returns the names of all available docker contexts in the registry.
func (*ContextRegistry) Refresh ¶ added in v0.113.0
func (r *ContextRegistry) Refresh() error
Refresh refreshes the list of available docker contexts in the registry.
type ContextRegistryOptions ¶ added in v0.115.0
type DeployRequest ¶ added in v0.115.0
type DeployRequest struct {
JobLog *slog.Logger `validate:"required,nostructlevel"`
ExternalRepoPath string `validate:"required"`
// InternalRepoPath is the repository's container-internal path.
// For a prepared deployment this is the published artifact directory for the deployed revision (Result.PathInternal),
// not the repository's top-level directory whose GC gate Prepare holds
// (see sourcecache.AcquireSharedGCPathLock). DeployStack takes an exclusive lock on this path while loading
// the Compose project (which decrypts files in place), so two deployments landing on the exact same
// revision never race on the same in-place decryption. Optional: falls back to ExternalRepoPath when empty.
InternalRepoPath string
DockerCLI command.Cli `validate:"required,nostructlevel"`
Payload *webhook.ParsedPayload
// RepositoryName is the active source identity used by pre-deploy state
// lookups, after URL rewrites or repository_url overrides. Optional for
// direct callers that rely on the legacy payload-derived identity.
RepositoryName string
// SourceURL is the resolved URL used to fetch/name the source containing
// the deploy config. It may differ from Payload.WebURL when a Git host
// serves HTTP(S) and SSH on different hosts/ports, and from the active
// deployment source when repository_url selects another repository.
// It is recorded as cd.doco.source.url so consumers can reconstruct
// the config source path without relying on the transient webhook/poll
// payload URL.
SourceURL string
DeployConfig *deploy.Config `validate:"required,nostructlevel"`
DetectedChanges []Change
NeedSignal []SignalService
LatestCommit string
AppVersion string `validate:"required"`
ComposeLoad ComposeLoadOptions
SwarmRetention SwarmRetentionOptions
SwarmMode bool
HashNormMap map[string]string
Project *types.Project
ProjectHash string
// CommitStatus is the commit status left pending for this deployment. A
// self-update records it so the process that resolves the handover can
// post the final state.
CommitStatus *selfupdate.CommitStatusInfo
// PhaseReporter optionally receives the deployment's phase changes. It is
// stopped before a self-update hands over, so it never reports past the
// point where a successor takes over the commit status.
PhaseReporter PhaseReporter
}
DeployRequest bundles DeployStack's per-deployment input.
type DeploymentAttempt ¶ added in v0.128.0
type DeploymentAttempt struct {
// contains filtered or unexported fields
}
DeploymentAttempt is an admitted lifecycle. Admission alone does not spend a retry; Start marks entry into the mutating deploy stage.
func (*DeploymentAttempt) Cancel ¶ added in v0.128.0
func (a *DeploymentAttempt) Cancel()
Cancel refunds entry into deploy when it ends in a lifecycle cancellation, ordinary skip, or self-update handover rather than an actual failure.
func (*DeploymentAttempt) Fail ¶ added in v0.128.0
func (a *DeploymentAttempt) Fail(failure DeploymentFailure, interrupted bool)
Fail updates an actual failure without refilling the automatic budget. Shutdown interruptions retain any existing failure unchanged; a first interruption creates only a recovery marker, not a timed/budgeted failure.
func (*DeploymentAttempt) Start ¶ added in v0.128.0
func (a *DeploymentAttempt) Start()
Start marks the attempt as spent and increments the retry count if applicable.
type DeploymentDesiredState ¶ added in v0.128.0
type DeploymentDesiredState struct {
Revision string
ConfigHash string
ProjectHash string
ImageDigests map[string]string
}
DeploymentDesiredState stores fingerprints, not configuration or resolved secrets. ImageDigests contains only service names and immutable digests.
type DeploymentFailure ¶ added in v0.112.0
type DeploymentFailure struct {
Repository string
Stack string
CommitSHA string
Stage string
Error string
FailedAt time.Time
RetriesUsed int
}
DeploymentFailure records a failed deployment attempt of one stack.
func GetDeploymentFailure ¶ added in v0.112.0
func GetDeploymentFailure(repoName, stack string) (DeploymentFailure, bool)
GetDeploymentFailure retrieves the recorded failure for a given repository and stack, if any.
type DeploymentFailureStore ¶ added in v0.128.0
type DeploymentFailureStore struct {
// contains filtered or unexported fields
}
DeploymentFailureStore owns the recovery marker and retry budget together. Its target lock precedes the scheduler/deploy lock, and must be held from pre-deploy inspection through outcome recording for policy-managed runs.
func NewDeploymentFailureStore ¶ added in v0.128.0
func NewDeploymentFailureStore(now func() time.Time) *DeploymentFailureStore
func (*DeploymentFailureStore) Acquire ¶ added in v0.128.0
func (s *DeploymentFailureStore) Acquire(ctx context.Context, target DeploymentTarget) (func(), error)
func (*DeploymentFailureStore) Admit ¶ added in v0.128.0
func (s *DeploymentFailureStore) Admit(target DeploymentTarget, desired DeploymentDesiredState, policy deploy.RetryConfig, manual bool) (*DeploymentAttempt, *DeploymentRetrySuppression)
Admit checks exhaustion before retry delay. The caller must hold Acquire's target lock for configured policies until this attempt finishes.
func (*DeploymentFailureStore) Clear ¶ added in v0.128.0
func (s *DeploymentFailureStore) Clear(target DeploymentTarget)
Clear removes the recorded failure for a target, if any.
func (*DeploymentFailureStore) Get ¶ added in v0.128.0
func (s *DeploymentFailureStore) Get(target DeploymentTarget) (DeploymentFailure, bool)
Get returns the recorded failure for a target, if any.
type DeploymentRetrySuppression ¶ added in v0.128.0
type DeploymentRetrySuppression struct {
Reason string
NextRetry time.Time
Failure DeploymentFailure
RetryLimit *int
First bool
}
DeploymentRetrySuppression is a read-only gate decision for a failed state.
type DeploymentTarget ¶ added in v0.128.0
type DeploymentTarget struct {
Context string
Stack string
Repository string
ConfigSource string
ConfigTarget string
}
DeploymentTarget isolates an outcome from identically named deployments in other contexts, repositories, or configuration targets.
type IgnoredInfo ¶ added in v0.77.0
type IgnoredInfo struct {
// Ignored services name
Ignored []string `json:"ignored"`
// Ignored services need to send signal
NeedSendSignal []SignalService `json:"need_signal"`
}
func (IgnoredInfo) IsEmpty ¶ added in v0.77.0
func (i IgnoredInfo) IsEmpty() bool
func (IgnoredInfo) IsNeedSignal ¶ added in v0.78.0
func (i IgnoredInfo) IsNeedSignal() bool
type JobExecutionMode ¶ added in v0.86.0
type JobExecutionMode string
const ( JobExecutionModeRestart JobExecutionMode = "restart" JobExecutionModeOneOff JobExecutionMode = "one_off" )
type JobNotifyOn ¶ added in v0.86.0
type JobNotifyOn string
const ( JobNotifyNone JobNotifyOn = "none" JobNotifySuccess JobNotifyOn = "success" JobNotifyFailure JobNotifyOn = "failure" JobNotifyAll JobNotifyOn = "all" )
type JobScheduleConfig ¶ added in v0.86.0
type JobScheduleConfig struct {
Schedule string
ExecutionMode JobExecutionMode
NotifyOn JobNotifyOn
StopServices []StopServiceRef
SwarmReplicas uint64
Enabled bool
SkipRunning bool
// StopServicesTimeout is an explicit, user-configured timeout (in seconds)
// used when stopping the targets listed in StopServices.
// When nil, the target's own configured grace period is honored instead
// (falling back to a default if the target has none configured).
// See docker.DefaultStopServicesTimeout.
StopServicesTimeout *int
}
func ParseJobScheduleLabels ¶ added in v0.86.0
func ParseJobScheduleLabels(labels map[string]string) (JobScheduleConfig, bool, error)
func (JobScheduleConfig) ShouldNotifyFailure ¶ added in v0.86.0
func (c JobScheduleConfig) ShouldNotifyFailure() bool
func (JobScheduleConfig) ShouldNotifySuccess ¶ added in v0.86.0
func (c JobScheduleConfig) ShouldNotifySuccess() bool
type Labels ¶ added in v0.54.0
func SwarmJobLabels ¶ added in v0.107.0
SwarmJobLabels returns the labels of a swarm service with the job configuration taken from the task template only.
Job configuration labels are authored by the user as service labels in the compose file and are therefore part of the task template, which is also where the deploy path reads them from. Honoring them from the service spec here would schedule services that are not set up as jobs during deployment.
Job runtime metadata (last/next run timestamps) is written by doco-cd itself to the service spec, so it is exempt from this rule.
func SwarmServiceLabels ¶ added in v0.107.0
SwarmServiceLabels returns the labels of a swarm service.
Deployment metadata is stored in the service spec labels, because labels in the task template are part of the service definition and changing them makes swarm recreate all tasks of the service on every deployment.
type LatestServiceStatus ¶ added in v0.78.0
type LatestServiceStatus struct {
DeployedStatus map[Service]ServiceStatus
// contains filtered or unexported fields
}
func GetLatestDeployStatus ¶ added in v0.78.0
func GetLatestDeployStatus(ctx context.Context, client client.APIClient, swarmMode bool, cloneURL string, deployName string) (LatestServiceStatus, error)
GetLatestDeployStatus retrieves the deployed status for a given repository and deploy name.
func (LatestServiceStatus) GetDeploymentCommitSHA ¶ added in v0.83.0
func (l LatestServiceStatus) GetDeploymentCommitSHA() string
func (LatestServiceStatus) GetDeploymentComposeHash ¶ added in v0.83.0
func (l LatestServiceStatus) GetDeploymentComposeHash() string
type OneOffContainerOptions ¶ added in v0.116.0
type PhaseReporter ¶ added in v0.124.0
type PhaseReporter interface {
// Report is called whenever the phase changes. It must not block.
Report(phase string)
// Stop ends reporting and waits for any report in flight. Reports after
// Stop are ignored, and calling Stop more than once is safe.
Stop()
}
PhaseReporter receives the phases of a running deployment, for example to publish them in a commit status.
type ScheduledComposeOptions ¶ added in v0.115.0
type ScheduledComposeOptions struct {
// ComposeLoad is passed through to the LoadCompose call used to reload the project.
ComposeLoad ComposeLoadOptions
// DeployConfigBaseDir is the base directory (relative to the repository root) where
// deployment configuration files are searched for.
DeployConfigBaseDir string
// InterpolateExternalSecrets enables Compose-style interpolation in legacy external secret
// references using the doco-cd process environment.
InterpolateExternalSecrets bool
// InterpolateResolvedSecrets enables Compose-style interpolation of one resolved external
// secret's value referencing another. Only other external secrets are consulted.
InterpolateResolvedSecrets bool
}
ScheduledComposeOptions bundles the Docker-owned settings needed to reload the Compose project for a scheduled job (see RunComposeScheduledContainer/RunComposeOneOffFromServiceDefinition) or for certificate rotation (see CertificateRotationOptions), beyond what LoadCompose itself needs.
func NewScheduledComposeOptions ¶ added in v0.115.0
func NewScheduledComposeOptions(c *app.Config) ScheduledComposeOptions
NewScheduledComposeOptions builds ScheduledComposeOptions from the application configuration. Call this once at a composition/stage boundary and pass the result down explicitly.
type SelfDeployInput ¶ added in v0.122.0
type SelfDeployInput struct {
RepoName string
SourceURL string
FullName string
SourceType string
Reference string
ConfigTarget string
CommitSHA string
ProjectHash string
JobID string
Trigger string
TimeoutSeconds int
RecreateMode string
Services []string
RemoveOrphans bool
CommitStatus *selfupdate.CommitStatusInfo
Log *slog.Logger
// StopPhaseReports stops publishing deployment phases before the
// successor takes over the commit status. Optional.
StopPhaseReports func()
}
SelfDeployInput carries the deploy context a successor needs to report a deployment it did not run itself.
func SelfDeployInputFromLabels ¶ added in v0.122.0
func SelfDeployInputFromLabels(labels map[string]string) *SelfDeployInput
SelfDeployInputFromLabels rebuilds the deploy context from a deployed stack's labels, for the redeploy paths that have no webhook payload.
type SelfUpdateOptions ¶ added in v0.122.0
type SelfUpdateOptions struct {
Enabled bool
Identity selfupdate.Identity
Strategy selfupdate.Strategy
Store *selfupdate.Store
DataMountPath string
AppVersion string
}
SelfUpdateOptions configures how this instance replaces its own container.
func SelfUpdateConfig ¶ added in v0.122.0
func SelfUpdateConfig() SelfUpdateOptions
SelfUpdateConfig returns the current self-update configuration.
type ServiceMismatch ¶ added in v0.78.0
type ServiceMismatch struct {
ServiceName string `json:"service_name"`
Reasons []ServiceMismatchReason `json:"reasons"`
}
func CheckServiceMismatch ¶ added in v0.78.0
func CheckServiceMismatch(swarmModeEnabled bool, deployed map[Service]ServiceStatus, services types.Services) ([]ServiceMismatch, error)
CheckServiceMismatch checks replicas, Swarm modes, and service presence. In standalone mode, services with autostart disabled may remain stopped, but all of their containers must exist. Invalid autostart labels return an error in standalone mode.
type ServiceMismatchReason ¶ added in v0.78.0
type ServiceStatus ¶ added in v0.78.0
type ServiceStatus struct {
// Swarm service identity, unavailable for Compose containers.
ID string
Name string
// In non-Swarm mode:
// Labels may differ between containers within a service, but most of them should be identical for the same service,
// except for com.docker.compose.container-number, com.docker.compose.replace, and potentially others.
Labels Labels
// swarm deploy mode.
// Empty if not in swarm mode.
SwarmMode swarmInternal.DeployMode
// Non-swarm mode: number of running containers
// Swarm mode: number of service replicas
Replicas uint64
// Non-swarm mode: number of containers in any state.
// Swarm mode: not used.
Containers uint64
}
type SignalService ¶ added in v0.77.0
type StopServiceRef ¶ added in v0.104.0
type StopServiceRef struct {
Project string // empty = same project/stack as the job
Service string
}
StopServiceRef identifies a compose service (or swarm service) to be temporarily stopped before a scheduled job runs and restarted after it completes.
In standalone (compose) mode:
- Service is the compose service name as declared in the compose file (the map key under `services:`). It is always the service name, never the container_name.
- Project identifies the compose project. When empty, the job's own project is used.
In swarm mode:
- Service is the short service name as declared in the compose file.
- Project is the stack name. When empty, the job's own stack is used.
- The full swarm service name is resolved as "<project>_<service>".
type SwarmOneOffFromServiceOptions ¶ added in v0.88.0
type SwarmRetentionOptions ¶ added in v0.115.0
type SwarmRetentionOptions struct {
// Config is the global default number of old Swarm config revisions to
// keep per resource (excluding the active one). -1 disables automatic pruning.
Config int
// Secret is the global default number of old Swarm secret revisions to
// keep per resource (excluding the active one). -1 disables automatic pruning.
Secret int
}
SwarmRetentionOptions holds the global defaults for pruning superseded Swarm config and secret revisions after a deployment.
func NewSwarmRetentionOptions ¶ added in v0.115.0
func NewSwarmRetentionOptions(c *app.Config) SwarmRetentionOptions
NewSwarmRetentionOptions builds SwarmRetentionOptions from the application configuration.
Source Files
¶
- artifact_recovery.go
- auto_discovery_migration.go
- cert_rotation_labels.go
- cert_rotation_redeploy.go
- cli_config.go
- commands.go
- compose_artifact_pinning.go
- compose_change.go
- compose_cli.go
- compose_deploy.go
- compose_hooks.go
- compose_jobs.go
- compose_kill.go
- compose_labels.go
- compose_lifecycle.go
- compose_live_resources.go
- compose_load.go
- compose_load_options.go
- compose_project_change.go
- compose_runtime_deployer.go
- compose_scheduled_run.go
- container_run.go
- context_registry.go
- deployment.go
- deployment_mode_migration.go
- failure_state.go
- git_resource_loader.go
- images.go
- job_schedule.go
- job_schedule_validation.go
- labels.go
- project.go
- project_files.go
- runtime_queries.go
- self_applier.go
- self_apply.go
- self_network_drift.go
- self_predecessor_policy.go
- self_rollback.go
- self_update.go
- self_update_deploy.go
- self_update_labels.go
- self_update_volumes.go
- service_utils.go
- state.go
- swarm.go
- swarm_artifact_pinning.go
- swarm_job.go
- swarm_runtime_deployer.go
- utils.go
- verify.go
- volumes.go