promotion

package
v1.8.13 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ReservedStepAliasRegex = regexp.MustCompile(`^(step|task)-\d+$`)

ReservedStepAliasRegex is a regular expression that matches step aliases that are reserved for internal use.

Functions

func ConfigToStruct

func ConfigToStruct[T any](c Config) (T, error)

ConfigToStruct converts a Config to a (typed) configuration struct.

func DefaultExprDataCacheFn

func DefaultExprDataCacheFn() *gocache.Cache

DefaultExprDataCacheFn returns a new gocache.Cache instance with default expiration and cleanup intervals. This is used as the default ExprDataCacheFn for the Engine.

func IsTerminal

func IsTerminal(err error) bool

IsTerminal returns true if the error is a terminal error or wraps one and false otherwise.

func RegisterStepRunner

func RegisterStepRunner(
	stepKind string,
	registration StepRunnerRegistration,
)

RegisterStepRunner adds a StepRunnerRegistration to the package's internal registry.

Types

type Config

type Config map[string]any

Config is an opaque map of configuration values for a Step. The keys and values are arbitrary and implementations of StepRunner are responsible for interpreting them.

func (Config) DeepCopy

func (c Config) DeepCopy() Config

DeepCopy returns a deep copy of the configuration.

func (Config) ToJSON

func (c Config) ToJSON() []byte

ToJSON marshals the configuration to JSON.

type Context

type Context struct {
	// UIBaseURL may be used to construct deeper URLs for interacting with the
	// Kargo UI.
	UIBaseURL string
	// WorkDir is the working directory to use for the Promotion.
	WorkDir string
	// Project is the Project that the Promotion is associated with.
	Project string
	// Stage is the Stage that the Promotion is targeting.
	Stage string
	// Promotion is the name of the Promotion.
	Promotion string
	// FreightRequests is the list of Freight from various origins that is
	// requested by the Stage targeted by the Promotion.
	//
	// This information is sometimes useful to Steps that reference a particular
	// artifact. When explicit information about the artifact's origin is absent,
	// Steps may need to examine FreightRequests.
	// This examination helps determine whether any ambiguity exists regarding
	// the artifact's origin. If ambiguity is found, a user may need to resolve
	// it.
	FreightRequests []kargoapi.FreightRequest
	// Freight is the collection of all Freight referenced by the Promotion. This
	// collection contains both the Freight that is actively being promoted and
	// any Freight that has been inherited from the target Stage's current
	// state.
	Freight kargoapi.FreightCollection
	// TargetFreightRef is the actual Freight that triggered this Promotion.
	TargetFreightRef kargoapi.FreightReference
	// StartFromStep is the index of the step from which the promotion should
	// begin execution.
	StartFromStep int64
	// StepExecutionMetadata tracks metadata pertaining to the execution
	// of individual promotion steps.
	StepExecutionMetadata kargoapi.StepExecutionMetadataList
	// State is the current state of the promotion process.
	State State
	// Vars is a list of variable definitions that can be used by the
	// Steps.
	Vars []kargoapi.ExpressionVariable
	// Actor is the name of the actor triggering the Promotion.
	Actor string
}

Context is the context of a user-defined promotion process that is executed by the Engine.

func (Context) DeepCopy

func (c Context) DeepCopy() Context

DeepCopy creates a deep copy of the Context. It can be used to ensure that modifications to the Context do not affect the original Context.

type Engine

type Engine interface {
	// Promote executes the specified sequence of Steps and returns a Result
	// that aggregates the results of all steps.
	Promote(context.Context, Context, []Step) (Result, error)
}

Engine is an interface for executing a sequence of promotion steps.

func NewSimpleEngine

func NewSimpleEngine(
	kargoClient client.Client,
	argocdClient client.Client,
	credsDB credentials.Database,
	cacheFunc ExprDataCacheFn,
) Engine

NewSimpleEngine returns a simple implementation of the Engine interface that uses built-in StepRunners.

type ExprDataCacheFn

type ExprDataCacheFn func() *gocache.Cache

ExprDataCacheFn is a function that returns a new cache to use in expression functions that consult the Kubernetes API.

A new cache is created for each step execution, so that the cache is shared between all expression functions that are executed in the same step. This is important for performance, as our Kubernetes API client does not cache Secrets and ConfigMaps, but also for correctness, as the data may change between calls.

It is allowed for the cache to be nil, in which case the expression functions will not cache their results.

type MockEngine

type MockEngine struct {
	PromoteFn func(context.Context, Context, []Step) (Result, error)
}

MockEngine is a mock implementation of the Engine interface that can be used to facilitate unit testing.

func (*MockEngine) Promote

func (m *MockEngine) Promote(
	ctx context.Context,
	promoCtx Context,
	steps []Step,
) (Result, error)

Promote implements the Engine interface.

type MockStepRunner

type MockStepRunner struct {
	// RunFunc is the function that this MockStepRunner should call when Run is
	// called. If set, this function will be called instead of returning RunResult
	// and RunErr.
	RunFunc func(context.Context, *StepContext) (StepResult, error)
	// RunResult is the result that this MockStepRunner should return when Run is
	// called.
	RunResult StepResult
	// RunErr is the error that this MockStepRunner should return when Run is
	// called.
	RunErr error
}

MockStepRunner is a mock implementation of the StepRunner interface, which can be used for testing.

func (*MockStepRunner) Run

func (m *MockStepRunner) Run(
	ctx context.Context,
	stepCtx *StepContext,
) (StepResult, error)

Run implements the StepRunner interface.

type Result

type Result struct {
	// Status is the high-level outcome of the user-defined promotion executed by
	// the Engine.
	Status kargoapi.PromotionPhase
	// Message is an optional message that provides additional context about the
	// outcome of the user-defined promotion executed by the Engine.
	Message string
	// HealthChecks collects health.Criteria returned from the execution of
	// individual Steps by their corresponding StepRunners. These criteria can
	// later be used as input to health.Checkers.
	HealthChecks []health.Criteria
	// If the promotion process remains in-progress, perhaps waiting for a change
	// in some external state, the value of this field will indicate where to
	// resume the process in the next reconciliation.
	CurrentStep int64
	// StepExecutionMetadata tracks metadata pertaining to the execution
	// of individual promotion steps.
	StepExecutionMetadata kargoapi.StepExecutionMetadataList
	// State is the current state of the promotion process.
	State State
	// RetryAfter is an optional, SUGGESTED duration after which a Promotion
	// reporting itself to be in a Running status should be retried. Note: This is
	// unrelated to retrying upon non-terminal failures.
	RetryAfter *time.Duration
}

Result is the result of a user-defined promotion process executed by the Engine. It aggregates the status and output of the individual StepResults returned by the StepRunner executing each Step.

type State

type State map[string]any

State is a type that represents state shared by Steps in a user-defined promotion process. It is not safe for concurrent use at present, as we expect Steps to be executed sequentially.

func (*State) DeepCopy

func (s *State) DeepCopy() State

DeepCopy returns a deep copy of the state.

func (State) Get

func (s State) Get(key string) (any, bool)

Get retrieves a value from the shared state.

func (State) Set

func (s State) Set(key string, value any)

Set stores a value in the shared state.

func (State) ToJSON

func (s State) ToJSON() []byte

ToJSON marshals the State to JSON.

type Step

type Step struct {
	// Kind identifies a registered StepRunner that implements the logic for this
	// step of the user-defined promotion process.
	Kind string
	// Alias is an optional identifier for this step of the use-defined promotion
	// process, which must be unique to the process. Output from execution of the
	// step will be keyed to this alias by the Engine and made accessible to
	// subsequent steps.
	Alias string
	// If is an optional expression that, if present, must evaluate to a boolean
	// value. If the expression evaluates to false, the step will be skipped.
	// If the expression does not evaluate to a boolean value, the step will
	// fail.
	If string
	// ContinueOnError is a boolean value that, if set to true, will cause the
	// Promotion to continue executing the next step even if this step fails. It
	// also will not permit this failure to impact the overall status of the
	// Promotion.
	ContinueOnError bool
	// Retry is the retry configuration for the Step.
	Retry *kargoapi.PromotionStepRetry
	// Vars is a list of variables definitions that can be used by the
	// Step.
	Vars []kargoapi.ExpressionVariable
	// Config is an opaque JSON to be passed to the StepRunner executing this
	// step.
	Config []byte
}

Step describes a single step in a user-defined promotion process. Steps are executed in sequence by the Engine, which delegates of each to a StepRunner.

func (*Step) BuildEnv

func (s *Step) BuildEnv(promoCtx Context, opts ...StepEnvOption) map[string]any

BuildEnv returns the environment for the Step. The environment includes the context of the Promotion and any additional options provided (e.g. outputs, task outputs, vars, secrets).

The environment is a (nested) map of string keys to any values. The keys are used as variables in the Step configuration.

func (*Step) GetConfig

func (s *Step) GetConfig(
	ctx context.Context,
	cl client.Client,
	cache *gocache.Cache,
	promoCtx Context,
) (Config, error)

GetConfig returns the Config unmarshalled into a map. Any expr-lang expressions are evaluated against the provided Context and State prior to unmarshaling.

func (*Step) GetVars

func (s *Step) GetVars(
	ctx context.Context,
	cl client.Client,
	cache *gocache.Cache,
	promoCtx Context,
) (map[string]any, error)

GetVars returns the variables defined in the Step. The variables are evaluated against the provided Context.

func (*Step) Skip

func (s *Step) Skip(
	ctx context.Context,
	cl client.Client,
	cache *gocache.Cache,
	promoCtx Context,
) (bool, error)

Skip returns true if the Step should be skipped based on the If condition. The If condition is evaluated against the provided Context.

type StepContext

type StepContext struct {
	// UIBaseURL may be used to construct deeper URLs for interacting with the
	// Kargo UI.
	UIBaseURL string
	// WorkDir is the root directory for the execution of a step.
	WorkDir string
	// SharedState is the state shared between steps.
	SharedState State
	// Alias is the alias of the step that is currently being executed.
	Alias string
	// Config is the configuration of the step that is currently being
	// executed.
	Config Config
	// Project is the Project that the Promotion is associated with.
	Project string
	// Stage is the Stage that the Promotion is targeting.
	Stage string
	// Promotion is the name of the Promotion.
	Promotion string
	// PromotionActor is the name of the actor triggering the Promotion.
	PromotionActor string
	// FreightRequests is the list of Freight from various origins that is
	// requested by the Stage targeted by the Promotion. This information is
	// sometimes useful to Step that reference a particular artifact and, in the
	// absence of any explicit information about the origin of that artifact, may
	// need to examine FreightRequests to determine whether there exists any
	// ambiguity as to its origin, which a user may then need to resolve.
	//
	// TODO: krancour: Longer term, if we can standardize the way that Steps
	// express the artifacts they need to work with, we can make the Engine
	// responsible for finding them and furnishing them directly to each
	// StepRunner.
	FreightRequests []kargoapi.FreightRequest
	// Freight is the collection of all Freight referenced by the Promotion. This
	// collection contains both the Freight that is actively being promoted as
	// well as any Freight that has been inherited from the target Stage's current
	// state.
	//
	// TODO: krancour: Longer term, if we can standardize the way that Steps
	// express the artifacts they need to work with, we can make the Engine
	// responsible for finding them and furnishing them directly to each
	// StepRunner.
	Freight kargoapi.FreightCollection
	// TargetFreightRef is the actual Freight that triggered this Promotion.
	TargetFreightRef kargoapi.FreightReference
}

StepContext is a type that represents the context in which a single promotion step is executed by a StepRunner.

type StepEnvOption

type StepEnvOption func(map[string]any)

StepEnvOption is a functional option for customizing the environment of a Step built by BuildEnv.

func StepEnvWithOutputs

func StepEnvWithOutputs(outputs State) StepEnvOption

StepEnvWithOutputs returns a StepEnvOption that adds the provided outputs to the environment of the Step.

func StepEnvWithStepMetas

func StepEnvWithStepMetas(promoCtx Context) StepEnvOption

StepEnvWithStepMetas returns a StepEnvOption that adds StepExecutionMetadata indexed by alias to the environment of the Step.

func StepEnvWithTaskOutputs

func StepEnvWithTaskOutputs(alias string, outputs State) StepEnvOption

StepEnvWithTaskOutputs returns a StepEnvOption that adds the provided task outputs to the environment of the Step.

func StepEnvWithVars

func StepEnvWithVars(vars map[string]any) StepEnvOption

StepEnvWithVars returns a StepEnvOption that adds the provided vars to the environment of the Step.

type StepResult

type StepResult struct {
	// Status is the high-level outcome of a Step executed by a StepRunner.
	Status kargoapi.PromotionStepStatus
	// Message is an optional message that provides additional context about the
	// outcome of a Step executed by a StepRunner.
	Message string
	// Output is the opaque output of a Step executed by a StepRunner. The Engine
	// will update the shared state with this output, making it available to the
	// StepRunners executing subsequent Steps.
	Output map[string]any
	// HealthCheck identifies criteria for a health check process. This is
	// returned by some StepRunner upon successful execution of a Step. These
	// criteria can be used later as input to a health.Checker.
	HealthCheck *health.Criteria
	// RetryAfter is an optional, SUGGESTED duration after which a step reporting
	// itself to be in a Running status should be retried. Note: This is unrelated
	// to retrying upon non-terminal failures.
	RetryAfter *time.Duration
}

StepResult represents the results of a single Step of a user-defined promotion process executed by a StepRunner.

type StepRunner

type StepRunner interface {
	// Run executes an individual Step from a user-defined promotion process using
	// the provided StepContext. Implementations may indirectly modify that
	// context through the returned StepResult to allow StepRunners for subsequent
	// Steps to access the results of this execution.
	Run(context.Context, *StepContext) (StepResult, error)
}

StepRunner is an interface for components that implement the logic for execution of an individual Step in a user-defined promotion process.

type StepRunnerCapabilities

type StepRunnerCapabilities struct {
	KargoClient  client.Client
	ArgoCDClient client.Client
	CredsDB      credentials.Database
}

StepRunnerCapabilities is a bundle of any special dependencies that may be injected into StepRunner implementations to grant them specific capabilities they may otherwise lack.

type StepRunnerCapability

type StepRunnerCapability string

StepRunnerCapability is a type representing special capabilities that may be required by a StepRunner in order to execute a step successfully. The engine executing a StepRunner is responsible for injecting corresponding dependencies into it when invoking its factory function.

const (
	// StepCapabilityAccessArgoCD represents the capability of interacting with
	// an Argo CD control plane via a Kubernetes client.
	StepCapabilityAccessArgoCD StepRunnerCapability = "access-argocd"
	// StepCapabilityAccessControlPlane represents the capability of interacting
	// with the Kargo control plane via a Kubernetes client.
	StepCapabilityAccessControlPlane StepRunnerCapability = "access-control-plane"
	// StepCapabilityAccessCredentials represents the capability to obtain
	// repository credentials through a lookup by credential type and repository
	// URL.
	StepCapabilityAccessCredentials StepRunnerCapability = "access-credentials"
	// StepCapabilityTaskOutputPropagation represents the capability of a step,
	// when executed as part of a task, to propagate its output directly to the
	// Promotion's shared state, in addition to the task's own state.
	StepCapabilityTaskOutputPropagation StepRunnerCapability = "task-output-propagation"
)

type StepRunnerMetadata

type StepRunnerMetadata struct {
	// DefaultTimeout is the default soft maximum interval in which a StepRunner
	// that returns a Running status (which typically indicates it's waiting for
	// something to happen) may be retried.
	//
	// The maximum is a soft one because the check for whether the interval has
	// elapsed occurs AFTER the step has run. This effectively means a step may
	// run ONCE beyond the close of the interval.
	//
	// A value of 0 will cause the step to be retried indefinitely unless the
	// ErrorThreshold is reached.
	//
	// This default can be overridden by step-level configuration.
	DefaultTimeout time.Duration
	// DefaultErrorThreshold is the number of consecutive times the step must fail
	// (for any reason) before retries are abandoned and the entire Promotion is
	// marked as failed.
	//
	// If this field is set to a non-positive value, it will be changed to the
	// system-wide default of 1 at registration time.
	//
	// A value of 1 will cause the Promotion to be marked as failed after just
	// a single failure; i.e. no retries will be attempted.
	//
	// This default can be overridden by step-level configuration.
	DefaultErrorThreshold uint32
	// RequiredCapabilities is a list of constants representing special
	// capabilities required by the StepRunner in order to execute a step
	// successfully. The engine executing the StepRunner is responsible for
	// injecting necessary dependencies into the StepRunner when invoking its
	// factory function. By default, StepRunners are not granted any special
	// capabilities.
	RequiredCapabilities []StepRunnerCapability
}

StepRunnerMetadata contains metadata about a StepRunner.

type StepRunnerRegistration

type StepRunnerRegistration struct {
	// Metadata is metadata about StepRunners for the kind of step specified by
	// StepKind.
	Metadata StepRunnerMetadata
	// Factory is a function for instantiating a StepRunner capable of executing
	// the kind of step specified by StepKind.
	Factory func(StepRunnerCapabilities) StepRunner
}

StepRunnerRegistration associates a kind of promotion step with optional metadata and a factory function for instantiating a StepRunner capable of executing that kind of step.

func GetStepRunnerRegistration

func GetStepRunnerRegistration(
	stepKind string,
) *StepRunnerRegistration

GetStepRunnerRegistration returns the StepRunnerRegistration for the specified promotion step kind from the package's internal registry. If no such registration exists, nil is returned instead.

type TerminalError

type TerminalError struct {
	Err error
}

TerminalError wraps another error to indicate to the step execution engine that the step that produced the error should not be retried.

func (*TerminalError) Error

func (e *TerminalError) Error() string

Error implements the error interface.

Directories

Path Synopsis
runner

Jump to

Keyboard shortcuts

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