controlplane

package
v0.124.0 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	// DefaultProjectActionTimeout is the default timeout, in seconds, for project actions.
	DefaultProjectActionTimeout = 30
	// MaxProjectActionTimeout is the largest whole-second timeout representable as time.Duration.
	MaxProjectActionTimeout = math.MaxInt64 / int64(time.Second)
)
View Source
const DefaultMirrorCompactionMaxSize int64 = 256 << 20

DefaultMirrorCompactionMaxSize is the size above which a repack skips a mirror unless the request sets its own limit. The encoder holds several times the size of a mirror's packfiles in memory.

View Source
const (
	// MaxTriggerPollConfigs limits the number of poll configurations accepted per request.
	MaxTriggerPollConfigs = 32
)

Variables

View Source
var (
	// ErrInvalidMirrorCompactionRequest indicates an unknown mode or a negative size limit.
	ErrInvalidMirrorCompactionRequest = errors.New("invalid mirror compaction request")
	// ErrNoMirrors indicates that no Git mirror matches a compaction request.
	ErrNoMirrors = errors.New("no git mirrors found")
	// ErrMirrorCompactionPanicked is recorded when a mirror compaction run panics.
	ErrMirrorCompactionPanicked = errors.New("mirror compaction run panicked")
)
View Source
var (
	// ErrNoPollConfiguration indicates an empty poll-trigger request.
	ErrNoPollConfiguration = errors.New("no poll configuration provided in request body")
	// ErrTooManyPollConfigurations indicates that a request exceeds MaxTriggerPollConfigs.
	ErrTooManyPollConfigurations = errors.New("too many poll configurations: maximum is 32")
	// ErrPollRunPanicked is recorded when a poll callback panics.
	ErrPollRunPanicked = errors.New("poll run panicked")
)
View Source
var (
	// ErrProjectNotFound indicates that no containers belong to the requested project.
	ErrProjectNotFound = errors.New("project not found")
	// ErrInvalidProjectTimeout indicates a timeout outside the supported duration range.
	ErrInvalidProjectTimeout = errors.New("invalid project timeout")
)
View Source
var (
	// ErrStackNotFound indicates that the requested stack has no services.
	ErrStackNotFound = errors.New("stack not found")
	// ErrNoApplicableStackServices indicates that all matched services were skipped.
	ErrNoApplicableStackServices = errors.New("no applicable services found")
)
View Source
var (
	// ErrInvalidRunStatus indicates an unsupported run status filter.
	ErrInvalidRunStatus = errors.New("invalid deployment run status")
	// ErrInvalidRunTrigger indicates an unsupported run trigger filter.
	ErrInvalidRunTrigger = errors.New("invalid deployment run trigger")
)
View Source
var ErrBackgroundWorkClosed = errors.New("application is shutting down")

ErrBackgroundWorkClosed indicates that shutdown has stopped accepting work.

View Source
var ErrScheduledJobRunPanicked = errors.New("scheduled job run panicked")

ErrScheduledJobRunPanicked is recorded when a scheduled-job callback panics.

Functions

func DeploymentOrigin added in v0.123.0

func DeploymentOrigin(ctx context.Context) syncwindow.Origin

DeploymentOrigin returns the origin set by WithDeploymentOrigin, or syncwindow.OriginAutomatic if there is none.

func GetStackServices

func GetStackServices(ctx context.Context, dockerCLI command.Cli, stack string) ([]dockerswarmtypes.Service, error)

GetStackServices returns the services belonging to a named Swarm stack.

func IsLifecycleCancellation

func IsLifecycleCancellation(err error) bool

IsLifecycleCancellation reports whether err represents context cancellation or timeout.

func NormalizeRunStatus

func NormalizeRunStatus(value string) (string, error)

NormalizeRunStatus validates and canonicalizes a run status filter.

func NormalizeRunTrigger

func NormalizeRunTrigger(value string) (string, error)

NormalizeRunTrigger validates and canonicalizes a run trigger filter.

func RemoveStack

func RemoveStack(ctx context.Context, dockerCLI command.Cli, stack string, log *slog.Logger) error

RemoveStack removes all resources belonging to a Swarm stack.

func WithDeploymentOrigin added in v0.123.0

func WithDeploymentOrigin(ctx context.Context, origin syncwindow.Origin) context.Context

WithDeploymentOrigin returns a context whose deployments are attributed to origin, which decides how sync windows apply to them. It is carried on the context because poll runs reach Deployment.Deploy through the PollRunner, which does not know what started the run.

Types

type Dependencies

type Dependencies struct {
	MaxRunsPerTrigger map[RunTrigger]int     `validate:"omitempty,dive,keys,oneof=webhook poll scheduled_job mirror_compaction,endkeys,min=1"`
	ScheduledJobs     ScheduledJobOperations `validate:"required,nostructlevel"`
	SecretProvider    secretprovider.SecretProvider
	Poll              PollDependencies
	// StorageDir is the data directory holding the source stores whose Git
	// mirrors TriggerMirrorCompaction compacts.
	StorageDir string
}

Dependencies contains the operations and limits used by the run coordinator.

type Deployment

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

Deployment is the protocol-neutral deployment operation shared by the webhook and poll transports.

func NewDeployment

func NewDeployment(dependencies DeploymentDependencies) (*Deployment, error)

NewDeployment validates dependencies and creates a Deployment operation.

func (*Deployment) Deploy

func (d *Deployment) Deploy(ctx context.Context, req DeploymentRequest) error

Deploy runs a single protocol-neutral deployment: it validates req, prepares the source, adapts the result into a reconciliation.DeployRequest (notifying the deployment target observer for each resolved deploy config), and runs the reconciliation.

Errors are returned as DeploymentError so callers can preserve the exact HTTP status/message mapping the pre-refactor handler used. A For webhook requests, stages.ErrSkipDeployment from the reconciler is returned unwrapped so callers can report a skipped (not failed) deployment.

type DeploymentDependencies

type DeploymentDependencies struct {
	SourcePreparer SourcePreparer        `validate:"required"`
	Reconciler     Reconciler            `validate:"required"`
	Contexts       DockerContextResolver `validate:"required"`
	DataMountPoint container.MountPoint  `validate:"required"`
}

DeploymentDependencies configures the source preparer, reconciler, and data mount point used by the protocol-neutral deployment operation.

type DeploymentError

type DeploymentError struct {
	Response       error
	Cause          error
	HTTPStatusCode int
}

DeploymentError pairs a Deployment.Deploy failure with the HTTP status code transport layers (the webhook/poll handlers) should use to report it, preserving the exact message/status mapping the pre-refactor handler used.

func (DeploymentError) Error

func (e DeploymentError) Error() string

func (DeploymentError) Unwrap

func (e DeploymentError) Unwrap() []error

type DeploymentRequest

type DeploymentRequest struct {
	Logger       *slog.Logger      `validate:"required,nostructlevel"`
	JobTrigger   stages.JobTrigger `validate:"required,oneof=webhook poll"`
	SourceType   config.SourceType
	SourceRef    string `validate:"required"`
	Ref          string
	Private      bool
	Metadata     notification.Metadata
	CustomTarget string
	TestName     string
	PollConfig   poll.Config
	Deployments  []*deploy.Config
	Payload      webhook.ParsedPayload
}

DeploymentRequest bundles Deployment.Deploy's per-call, per-deployment-request input: the source location and its trigger/reference/visibility, notification metadata, an optional custom deploy target, an optional test identity, poll configuration, optional centrally supplied deployments, and the parsed webhook payload (zero value for non-webhook triggers).

type DestroyProjectResult

type DestroyProjectResult struct {
	ProjectName string
	Message     string
	Volumes     bool
	Images      bool
}

DestroyProjectResult describes a successful project removal.

func DestroyProject

func DestroyProject(
	ctx context.Context,
	dockerCLI command.Cli,
	projectName string,
	timeoutSeconds int,
	removeVolumes bool,
	removeImages bool,
	log *slog.Logger,
) (DestroyProjectResult, error)

DestroyProject removes a Compose project and optionally its volumes and images.

type DockerContextResolver

type DockerContextResolver interface {
	Get(ctx context.Context, name string) (docker.ContextClient, error)
}

DockerContextResolver is the capability-aware Docker context surface used by Deployment.

type MirrorCompactionActiveError added in v0.124.0

type MirrorCompactionActiveError struct {
	// JobID identifies the active run.
	JobID string
}

MirrorCompactionActiveError rejects a compaction request while another compaction run is active.

func (*MirrorCompactionActiveError) Error added in v0.124.0

Error names the active compaction run.

type MirrorCompactionRequest added in v0.124.0

type MirrorCompactionRequest struct {
	// Repository limits the run to the mirrors of one repository, given as
	// "<host>/<owner>/<repo>" or as a clone URL. Empty selects every mirror.
	Repository string
	// Mode defaults to git.MirrorCompactionRepack.
	Mode git.MirrorCompactionMode
	// MaxSizeBytes skips a repack of a mirror whose packfiles are larger. Nil
	// applies DefaultMirrorCompactionMaxSize, and zero disables the limit.
	MaxSizeBytes *int64
}

MirrorCompactionRequest selects the Git mirrors a compaction run processes.

type MirrorCompactionsFailedError added in v0.124.0

type MirrorCompactionsFailedError struct {
	Failed int
	Total  int
	Cause  error
}

MirrorCompactionsFailedError reports a compaction run in which mirrors failed or were cancelled.

func (*MirrorCompactionsFailedError) Error added in v0.124.0

Error reports the number of mirrors that were not compacted.

func (*MirrorCompactionsFailedError) Unwrap added in v0.124.0

func (e *MirrorCompactionsFailedError) Unwrap() error

Unwrap exposes the first failure, or the cancellation.

type PollConfigValidationError

type PollConfigValidationError struct {
	Index int
	Err   error
}

PollConfigValidationError identifies a malformed poll configuration by request index.

func (*PollConfigValidationError) Error

func (e *PollConfigValidationError) Error() string

Error identifies the invalid poll configuration by request index.

func (*PollConfigValidationError) Unwrap

func (e *PollConfigValidationError) Unwrap() error

Unwrap exposes the underlying poll configuration validation error.

type PollDependencies

type PollDependencies struct {
	AppConfig      *app.Config `validate:"required,nostructlevel"`
	DataMountPoint container.MountPoint
	DockerCLI      command.Cli
	Contexts       *docker.ContextRegistry
	Runner         PollRunner `validate:"required"`
}

PollDependencies contains the services required to execute poll configurations.

type PollRunner

type PollRunner func(ctx context.Context, pollConfig poll.Config, appConfig *app.Config, dataMountPoint container.MountPoint,
	dockerCli command.Cli, contexts *docker.ContextRegistry, logger *slog.Logger, metadata notification.Metadata, secretProvider secretprovider.SecretProvider,
	triggerReason string,
) error

PollRunner executes one validated poll configuration with application dependencies.

type PollRunsFailedError

type PollRunsFailedError struct {
	Failed int
	Total  int
	Cause  error
}

PollRunsFailedError summarizes failures from a batch of poll configurations.

func (*PollRunsFailedError) Error

func (e *PollRunsFailedError) Error() string

Error reports the number of failed poll runs.

func (*PollRunsFailedError) Unwrap

func (e *PollRunsFailedError) Unwrap() error

Unwrap exposes the first poll-run failure.

type ProjectAction

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

ProjectAction is a validated project operation ready to execute.

func ResolveProjectAction

func ResolveProjectAction(ctx context.Context, dockerCLI command.Cli, projectName, action string, opts ProjectActionOptions) (ProjectAction, error)

ResolveProjectAction validates a project and prepares its requested lifecycle action.

type ProjectActionOptions added in v0.117.0

type ProjectActionOptions struct {
	Context        string
	Service        string
	SecretProvider secretprovider.SecretProvider
	Compose        docker.ScheduledComposeOptions
}

ProjectActionOptions contains optional inputs for project lifecycle actions.

type ProjectActionResult

type ProjectActionResult struct {
	ProjectName string
	Action      string
	Message     string
}

ProjectActionResult describes a successful project lifecycle action.

func ExecuteProjectAction

func ExecuteProjectAction(ctx context.Context, operation ProjectAction, timeoutSeconds int, log *slog.Logger) (ProjectActionResult, error)

ExecuteProjectAction runs a previously resolved project action with a validated timeout.

func RunProjectAction

func RunProjectAction(
	ctx context.Context,
	dockerCLI command.Cli,
	contextName string,
	projectName string,
	action string,
	timeoutSeconds int,
	log *slog.Logger,
) (ProjectActionResult, error)

RunProjectAction resolves and executes a supported project lifecycle action.

type ProjectLookupError

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

ProjectLookupError wraps a Docker lookup failure with the requested project name.

func (*ProjectLookupError) Error

func (e *ProjectLookupError) Error() string

Error reports the project lookup failure.

func (*ProjectLookupError) Unwrap

func (e *ProjectLookupError) Unwrap() error

Unwrap exposes the underlying Docker lookup error.

type Reconciler

type Reconciler interface {
	Deploy(ctx context.Context, req reconciliation.DeployRequest) error
}

Reconciler is the minimal reconciliation surface the Deployment operation depends on. Satisfied by *reconciliation.Manager.

type Run

type Run struct {
	JobID       string      `json:"job_id"`
	Trigger     RunTrigger  `json:"trigger"`
	Status      RunStatus   `json:"status"`
	Repository  string      `json:"repository,omitempty"`
	Target      string      `json:"target,omitempty"`
	Revision    string      `json:"revision,omitempty"`
	Deployments []RunTarget `json:"deployments,omitempty"`
	Message     string      `json:"message,omitempty"`
	CreatedAt   time.Time   `json:"created_at"`
	StartedAt   *time.Time  `json:"started_at,omitempty"`
	FinishedAt  *time.Time  `json:"finished_at,omitempty"`
	UpdatedAt   time.Time   `json:"updated_at"`
}

Run is the serializable lifecycle record for one control-plane operation.

type RunExecution

type RunExecution struct {
	Mode         RunMode
	PanicContext string
	PanicError   error
}

RunExecution configures lifecycle behavior and panic reporting for one run.

type RunFunc

type RunFunc func(context.Context) (RunResult, error)

RunFunc performs the work associated with an accepted control-plane run.

type RunMetadata

type RunMetadata struct {
	Repository string
	Target     string
	Revision   string
}

RunMetadata describes the source and deployment target recorded for a run.

type RunMode

type RunMode uint8

RunMode controls whether a run blocks its caller and whether request cancellation propagates.

const (
	// RunSynchronous runs inline and stops when either the request or application is cancelled.
	RunSynchronous RunMode = iota
	// RunSynchronousDetached runs inline but ignores request cancellation.
	RunSynchronousDetached
	// RunAsynchronous runs in the background under the application lifecycle.
	RunAsynchronous
)

type RunResult

type RunResult struct {
	Status  RunStatus
	Message string
}

RunResult describes the terminal status and optional message produced by a run.

func FailedRun

func FailedRun(message string) RunResult

FailedRun creates a failed terminal result.

func SkippedRun

func SkippedRun(message string) RunResult

SkippedRun creates a skipped terminal result.

func SucceededRun

func SucceededRun(message string) RunResult

SucceededRun creates a successful terminal result.

type RunStatus

type RunStatus string

RunStatus is the lifecycle state recorded for a control-plane run.

const (
	// RunStatusAccepted indicates that a run has been admitted but not started.
	RunStatusAccepted RunStatus = "accepted"
	// RunStatusRunning indicates that a run is executing.
	RunStatusRunning RunStatus = "running"
	// RunStatusSucceeded indicates that a run completed successfully.
	RunStatusSucceeded RunStatus = "succeeded"
	// RunStatusFailed indicates that a run completed with an error.
	RunStatusFailed RunStatus = "failed"
	// RunStatusSkipped indicates that a run intentionally performed no work.
	RunStatusSkipped RunStatus = "skipped"
)

type RunTarget

type RunTarget struct {
	Stack   string `json:"stack,omitempty"`
	Context string `json:"context"`
}

RunTarget identifies a stack deployment observed during a run.

type RunTrigger

type RunTrigger string

RunTrigger identifies the entry point that created a control-plane run.

const (
	// RunTriggerWebhook identifies runs accepted from webhook requests.
	RunTriggerWebhook RunTrigger = "webhook"
	// RunTriggerPoll identifies runs accepted from poll operations.
	RunTriggerPoll RunTrigger = "poll"
	// RunTriggerScheduledJob identifies runs accepted from scheduled-job requests.
	RunTriggerScheduledJob RunTrigger = "scheduled_job"
	// RunTriggerMirrorCompaction identifies runs accepted from Git mirror compaction requests.
	RunTriggerMirrorCompaction RunTrigger = "mirror_compaction"
)

type Runs

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

Runs coordinates control-plane run admission and lifecycle while delegating storage and draining to their focused components.

func NewRuns

func NewRuns(applicationCtx context.Context, log *slog.Logger, dependencies Dependencies) *Runs

NewRuns validates dependencies and constructs a control-plane run coordinator.

func (*Runs) Accept

func (c *Runs) Accept(jobID string, trigger RunTrigger, metadata RunMetadata) string

Accept records a run in accepted state, generating a job ID when needed.

func (*Runs) AddDeployment

func (c *Runs) AddDeployment(jobID, stack, contextName string)

AddDeployment records a stack and Docker context observed during a run.

func (*Runs) CloseAndWait

func (c *Runs) CloseAndWait()

CloseAndWait rejects new work, cancels active runs, and waits for them to finish.

func (*Runs) DeploymentTargetObserver

func (c *Runs) DeploymentTargetObserver(jobID string) func(string, string)

DeploymentTargetObserver returns a callback that records deployments for jobID.

func (*Runs) Drain added in v0.122.0

func (c *Runs) Drain()

Drain rejects new work and waits for the runs already in flight to finish. Unlike CloseAndWait it does not cancel them: a self-update handover must not abort a deploy of another stack halfway through its recreate, which would leave that stack without containers. Only maintenance runs, such as a mirror compaction, are cancelled, since they are safe to abort and could otherwise hold up the handover for minutes.

func (*Runs) Drained added in v0.122.0

func (c *Runs) Drained() bool

Drained reports whether admission is closed. It cannot be reopened.

func (*Runs) Execute

func (c *Runs) Execute(
	requestCtx context.Context,
	jobID string,
	execution RunExecution,
	run RunFunc,
) error

Execute runs accepted work in the configured lifecycle mode.

func (*Runs) Get

func (c *Runs) Get(jobID string) (Run, bool)

Get returns a defensive copy of a run by job ID.

func (*Runs) List

func (c *Runs) List(limit int, trigger, status string) []Run

List returns filtered runs in reverse creation order.

func (*Runs) ListScheduledJobs

func (c *Runs) ListScheduledJobs(ctx context.Context, contextName, stackName string) ([]scheduler.JobInfo, error)

ListScheduledJobs returns scheduled jobs for an optional Docker context and stack.

func (*Runs) MarkFailed

func (c *Runs) MarkFailed(jobID, message string)

MarkFailed transitions a tracked run to failed with a message.

func (*Runs) MarkRunning

func (c *Runs) MarkRunning(jobID string)

MarkRunning transitions a tracked run to running.

func (*Runs) MarkSkipped

func (c *Runs) MarkSkipped(jobID, message string)

MarkSkipped transitions a tracked run to skipped with a message.

func (*Runs) RunConfiguredPoll

func (c *Runs) RunConfiguredPoll(
	ctx context.Context,
	pollConfig poll.Config,
	log *slog.Logger,
	triggerReason string,
) (string, error)

RunConfiguredPoll executes one prevalidated scheduled poll under the shared lifecycle.

func (*Runs) SetMetadata

func (c *Runs) SetMetadata(jobID string, metadata RunMetadata)

SetMetadata updates source and target metadata for a tracked run.

func (*Runs) TriggerMirrorCompaction added in v0.124.0

func (c *Runs) TriggerMirrorCompaction(ctx context.Context, jobID string, req MirrorCompactionRequest, wait bool) (string, error)

TriggerMirrorCompaction compacts the Git mirrors req selects, one at a time, in a tracked run. The run is cancelled when the runs are drained.

It returns ErrInvalidMirrorCompactionRequest for an invalid request and ErrNoMirrors if no mirror matches. While another compaction run is active, it returns that run's job ID and a *MirrorCompactionActiveError. With wait, a run in which mirrors failed or were cancelled returns a *MirrorCompactionsFailedError.

func (*Runs) TriggerPoll

func (c *Runs) TriggerPoll(ctx context.Context, configs []poll.Config, wait bool, jobLog *slog.Logger) (string, error)

TriggerPoll validates and executes a bounded batch of one-shot poll configurations. If sync windows deferred every configuration of a synchronous batch, it returns a *stages.SyncWindowBlockedError and the run is marked skipped.

func (*Runs) TriggerScheduledJob

func (c *Runs) TriggerScheduledJob(
	ctx context.Context,
	jobID string,
	contextName string,
	jobName string,
	stackName string,
	wait bool,
) (string, error)

TriggerScheduledJob accepts and executes one scheduled job under the shared run lifecycle.

type ScheduledJobOperations

type ScheduledJobOperations interface {
	ListJobs(context.Context, string, string) ([]scheduler.JobInfo, error)
	TriggerNow(context.Context, string, string, string, secretprovider.SecretProvider) (string, error)
}

ScheduledJobOperations is the scheduler surface required by the control plane.

type SourcePreparer

type SourcePreparer interface {
	Prepare(ctx context.Context, req source.Request) (source.Result, error)
}

SourcePreparer is the minimal source-preparation surface the Deployment operation depends on: resolving a deployment's source (Git repository or OCI artifact) into a ready-to-deploy local checkout. Satisfied by *source.Preparer.

type StackActionResult

type StackActionResult struct {
	Service string `json:"service"`
	Status  string `json:"status"`
	Reason  string `json:"reason,omitempty"`
}

StackActionResult reports the outcome for one service targeted by a stack action.

func RunStackAction

func RunStackAction(
	ctx context.Context,
	dockerCLI command.Cli,
	stack string,
	action string,
	service string,
	replicas int,
	wait bool,
	log *slog.Logger,
) ([]StackActionResult, error)

RunStackAction resolves a stack and applies an action to its matching services.

func RunStackActionOnServices

func RunStackActionOnServices(
	ctx context.Context,
	dockerCLI command.Cli,
	services []dockerswarmtypes.Service,
	stack string,
	action string,
	service string,
	replicas int,
	wait bool,
	log *slog.Logger,
) ([]StackActionResult, error)

RunStackActionOnServices applies an action and preserves partial results on failure.

type StackServiceActionError

type StackServiceActionError struct {
	Service string
	Cause   error
}

StackServiceActionError wraps an operational failure with its service name.

func (*StackServiceActionError) Error

func (e *StackServiceActionError) Error() string

Error reports the failed service action.

func (*StackServiceActionError) Unwrap

func (e *StackServiceActionError) Unwrap() error

Unwrap exposes the underlying service action error.

type StackServiceNotFoundError

type StackServiceNotFoundError struct {
	Service string
}

StackServiceNotFoundError identifies a requested service absent from its stack.

func (*StackServiceNotFoundError) Error

func (e *StackServiceNotFoundError) Error() string

Error reports the missing service.

Jump to

Keyboard shortcuts

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