triggerrun

package
v0.0.0-...-ec31798 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Overview

Package triggerrun implements a Kubernetes controller for managing TriggerRun resources.

This package provides scheduled and event-driven workflow execution through a state machine that manages the lifecycle of trigger runs. It supports multiple trigger types including cron schedules, backfill operations, interval-based triggers, and batch reruns.

Architecture:

The controller uses a Runner interface abstraction to support different trigger types:

  • CronTrigger: Recurring scheduled workflows using cron expressions
  • BackfillTrigger: One-time workflows for historical data backfilling
  • IntervalTrigger: Workflows triggered at fixed intervals
  • BatchRerunTrigger: Bulk reprocessing of previously executed workflows

State Machine:

TriggerRun resources transition through the following states:

  • INVALID → RUNNING: Initial workflow start
  • RUNNING → SUCCEEDED/FAILED/KILLED: Terminal states based on execution outcome
  • RUNNING/PAUSED → PENDING_KILL → KILLED: A kill stops the workflow, then waits for in-flight child PipelineRuns to stop before the run becomes terminal

The controller reconciles resources every 60 seconds to check workflow status and handle kill requests. Terminal states are marked immutable to prevent further modifications.

Workflow Integration:

The controller integrates with Cadence or Temporal workflow engines to execute scheduled workflows. Each Runner implementation manages workflow lifecycle operations including starting, monitoring, and terminating workflow executions.

Cascade delete: when the owning Pipeline is deleted, the controller drains the run's recurring cron/schedule before GC removes it. The drain finalizer is installed before the ownerReference so the run is never GC-eligible unprotected, and a deleting run can never re-arm its cron; a 24h timeout is the backstop.

Cascade cancel: killing or deleting a trigger run also requests a kill on every in-flight child PipelineRun it dispatched (found via TriggeredByLabel). A killed run stays PENDING_KILL, and a deleting run keeps its drain finalizer, until those children are terminal.

Index

Constants

View Source
const (
	TriggerTypeCron       = "cron"        // Recurring workflows based on cron expressions
	TriggerTypeBackfill   = "backfill"    // One-time workflows for historical data processing
	TriggerTypeBatchRerun = "batch_rerun" // Bulk reprocessing of previously executed workflows
	TriggerTypeInterval   = "interval"    // Workflows triggered at fixed intervals
	TriggerTypeUnknown    = "unknown"     // Unknown or unsupported trigger type
)

TriggerType constants define the supported trigger types.

These constants are used by GetTriggerType to determine which Runner implementation should handle a specific TriggerRun resource.

View Source
const TriggeredByLabel = "pipelinerun.michelangelo/triggered-by"

TriggeredByLabel is stamped on every PipelineRun a trigger dispatches, valued with the TriggerRun name. Child runs carry no ownerReference to their trigger, so this label is the only link used to find them when the trigger is killed or deleted.

Variables

View Source
var Module = fx.Options(
	fx.Invoke(register),
)

Module provides Uber FX dependency injection options for the TriggerRun controller.

This module registers the controller with the Kubernetes controller manager and initializes Runner implementations for supported trigger types (cron and backfill).

Usage:

fx.New(
    triggerrun.Module,
    // other modules...
)

Functions

func BackfillRunTimestamps

func BackfillRunTimestamps(start, end time.Time, cronExpr string) ([]time.Time, error)

BackfillRunTimestamps enumerates the occurrences of cronExpr that a backfill over [start, end] runs: every occurrence after start up to and including end, plus start itself when it falls exactly on the schedule. This is the enumeration the backfill worker executes, so a caller that validates a window ahead of time counts exactly the runs that would be created. A caller that only needs to know whether the window runs at all should use BackfillWindowHasRun, which does not build the slice.

Known limitation: whether start itself is an occurrence is derived from the gap between the next two occurrences, so an irregular schedule such as "0 9 * * 1,3,6" can be mis-detected at start. The occurrences after start are always exact.

func BackfillWindowHasRun

func BackfillWindowHasRun(start, end time.Time, cronExpr string) (bool, error)

BackfillWindowHasRun reports whether a backfill over [start, end] on cronExpr would run at least once, counted the same way as BackfillRunTimestamps. It looks at most two occurrences ahead of start, so it is safe to call in a request path for a window of any size.

func ForceKillWorkflow

func ForceKillWorkflow(ctx context.Context, triggerRun *v2pb.TriggerRun, log logr.Logger, workflowClient clientInterface.WorkflowClient) error

ForceKillWorkflow tears down a TriggerRun's workflow and schedule without persisting status, for the cascade safety-timeout path. It deletes the trigger (not just terminates it) so no schedule stays armed; idempotent, and returns nil when nothing is running.

func GetTriggerType

func GetTriggerType(tr *v2pb.TriggerRun) string

GetTriggerType determines the trigger type from a TriggerRun specification.

This function examines the TriggerRun spec to identify which trigger type should handle the resource. The determination is made by checking for specific fields in priority order:

  1. BatchRerun: Spec.Trigger.BatchRerun is set
  2. Backfill: Both Spec.StartTimestamp and Spec.EndTimestamp are set and Spec.Catchup is false. This keeps pre-catchup backfill specs on the one-shot backfill runner. With Spec.Catchup set, the timestamps are the schedule's window and the recurring runner below owns the object, so adding or removing an end date never changes its type.
  3. Interval: Spec.Trigger.IntervalSchedule is set
  4. Cron: Spec.Trigger.CronSchedule is set
  5. Unknown: None of the above conditions match

The returned type string is used by the Reconciler to select the appropriate Runner implementation.

Returns one of the TriggerType constants (TriggerTypeCron, TriggerTypeBackfill, TriggerTypeInterval, TriggerTypeBatchRerun, or TriggerTypeUnknown).

func IsTerminalState

func IsTerminalState(state v2pb.TriggerRunState) bool

IsTerminalState reports whether state is one a TriggerRun never leaves: FAILED, KILLED or SUCCEEDED.

Types

type CreateTriggerRequest

type CreateTriggerRequest struct {
	TriggerRun *v2pb.TriggerRun // The TriggerRun resource containing execution parameters
}

CreateTriggerRequest is a data transfer object for trigger workflow execution.

This struct is passed as the workflow input when starting trigger workflows (both cron and backfill). It contains the complete TriggerRun specification needed for workflow execution.

type Params

type Params struct {
	fx.In

	Logger            logr.Logger
	WorkflowClient    clientInterface.WorkflowClient
	APIHandlerFactory apiHandler.Factory

	CronTrigger       Runner `name:"cron-trigger"`        // Handles cron-based recurring workflows
	IntervalTrigger   Runner `name:"interval-trigger"`    // Handles interval-based workflows
	BackfillTrigger   Runner `name:"backfill-trigger"`    // Handles backfill workflows
	BatchRerunTrigger Runner `name:"batch-rerun-trigger"` // Handles batch rerun workflows
}

Params contains the dependencies required to instantiate the TriggerRun Reconciler.

This struct uses Uber FX dependency injection to wire controller dependencies. The Runner implementations are tagged by name to inject the correct trigger type.

type Reconciler

type Reconciler struct {
	api.Handler
	// contains filtered or unexported fields
}

Reconciler reconciles TriggerRun resources through a state machine.

All fields are unexported. Exported struct fields become permanent public API surface — external packages can depend on them directly, making future removal a breaking change. All dependencies are injected via NewReconciler() or Register() instead. This follows the same pattern used by controllers in kubernetes/kubernetes.

The reconciler manages the complete lifecycle of trigger runs, from initial workflow start through terminal states (SUCCEEDED, FAILED, or KILLED). It delegates execution to the appropriate Runner based on the trigger type.

State transitions are handled through a labeled switch statement that allows breaking out of the state machine once a terminal state is reached. The reconciler persists status updates to Kubernetes and requeues resources every 60 seconds for ongoing status checks.

The reconciler supports concurrent processing of multiple TriggerRun resources based on the maximumConcurrentReconciles setting.

func NewReconciler

func NewReconciler(p Params) *Reconciler

NewReconciler creates a new TriggerRun Reconciler with the provided dependencies.

The reconciler is initialized with Runner implementations for each supported trigger type. The API handler is configured during registration through the Register method.

func (*Reconciler) Reconcile

func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)

Reconcile implements the controller-runtime Reconciler interface for TriggerRun resources.

This method is invoked by the controller framework whenever a TriggerRun resource is created, updated, or periodically requeued. It fetches the resource from Kubernetes and delegates to the reconcile helper method for state machine processing.

If the resource has been deleted, reconciliation completes without error. Other fetch errors are returned to be retried by the controller framework.

func (*Reconciler) Register

func (r *Reconciler) Register(mgr ctrl.Manager) error

Register registers the TriggerRun controller with the controller manager.

This method configures the controller with:

  • API handler for Kubernetes operations
  • Structured logger with "triggerRun" prefix
  • TriggerRun resource watch
  • Maximum concurrent reconciles setting

Returns an error if API handler creation or controller registration fails.

type Runner

type Runner interface {
	// Run starts workflow execution for a trigger run.
	//
	// This method initiates a workflow using the workflow client, configures execution
	// parameters (task list, timeouts, schedules), and returns the initial status.
	//
	// For recurring triggers (cron/interval), this starts a long-running workflow that
	// spawns child workflows on schedule. For one-time triggers (backfill), this starts
	// a single workflow execution.
	//
	// Returns TriggerRunStatus with State=RUNNING on success or State=FAILED on error.
	Run(ctx context.Context, triggerRun *v2pb.TriggerRun) (v2pb.TriggerRunStatus, error)

	// Kill terminates an active trigger run workflow.
	//
	// This method stops workflow execution by calling TerminateWorkflow on the workflow
	// client. For recurring triggers, this stops future scheduled executions.
	//
	// Returns TriggerRunStatus with State=KILLED on success. If the workflow is already
	// terminated or not running, returns KILLED without error.
	Kill(ctx context.Context, triggerRun *v2pb.TriggerRun) (v2pb.TriggerRunStatus, error)

	// Pause suspends an active recurring trigger run workflow.
	//
	// This method pauses workflow execution for recurring triggers (cron/interval) to prevent
	// new executions from being scheduled. The workflow remains alive but inactive.
	//
	// Returns TriggerRunStatus with State=PAUSED on success. If the workflow is not running
	// or not a recurring type, returns appropriate error state.
	Pause(ctx context.Context, triggerRun *v2pb.TriggerRun) (v2pb.TriggerRunStatus, error)

	// Resume reactivates a paused recurring trigger run workflow.
	//
	// This method resumes workflow execution for previously paused recurring triggers,
	// allowing new executions to be scheduled again according to the original schedule.
	//
	// Returns TriggerRunStatus with State=RUNNING on success. If the workflow is not paused
	// or not a recurring type, returns appropriate error state.
	Resume(ctx context.Context, triggerRun *v2pb.TriggerRun) (v2pb.TriggerRunStatus, error)

	// GetStatus retrieves the current execution status of a trigger run.
	//
	// This method queries the workflow engine for execution status and maps workflow
	// states to TriggerRunStatus states:
	//  - Running → RUNNING
	//  - Completed → SUCCEEDED
	//  - Failed/TimedOut → FAILED
	//  - Terminated/Canceled → KILLED
	//
	// For recurring triggers, this checks if an open workflow execution exists.
	// For one-time triggers, this describes the specific workflow execution.
	GetStatus(ctx context.Context, triggerRun *v2pb.TriggerRun) (v2pb.TriggerRunStatus, error)

	// Update synchronizes TriggerRun spec changes to the workflow engine.
	//
	// This method compares the TriggerRun spec with the workflow engine state
	// and updates the workflow engine if they differ. For recurring triggers (cron/interval),
	// this updates the schedule. For one-time triggers (backfill/batch rerun), this is a no-op.
	//
	// The action parameter allows folding pause/resume into the same atomic update as a cron
	// change, avoiding race conditions between separate Update and Pause/Unpause API calls.
	// When action is PAUSE or RESUME and there is a cron drift, both are applied atomically.
	// Returns true in the second return value if the action was handled atomically.
	//
	// Returns current TriggerRunStatus. Does not change the state unless action was applied.
	Update(ctx context.Context, triggerRun *v2pb.TriggerRun, action v2pb.TriggerRunAction) (v2pb.TriggerRunStatus, bool, error)
}

Runner defines the interface for trigger execution engines.

This interface abstracts workflow lifecycle operations for different trigger types (cron, backfill, interval, batch rerun). Each Runner implementation manages workflow execution through Cadence or Temporal, providing status tracking and termination support.

All methods return a TriggerRunStatus containing the execution state and metadata including workflow ID, run ID, and workflow UI URL.

Implementations:

  • cronTrigger: Manages recurring workflows with cron schedules
  • backfillTrigger: Manages one-time backfill workflows
  • intervalTrigger: Manages interval-based workflows (planned)
  • batchRerunTrigger: Manages batch rerun workflows (planned)

func NewBackfillTrigger

func NewBackfillTrigger(log logr.Logger, workflowClient clientInterface.WorkflowClient, configProvider uberconfig.Provider) Runner

NewBackfillTrigger creates a new backfill trigger Runner.

The returned Runner manages one-time workflows for historical data processing. It requires a logger for structured logging and a workflow client for interacting with the workflow engine.

func NewCronTrigger

func NewCronTrigger(log logr.Logger, workflowClient clientInterface.WorkflowClient, configProvider uberconfig.Provider) Runner

NewCronTrigger creates a new cron trigger Runner.

The returned Runner manages recurring scheduled workflows using cron expressions. It requires a logger for structured logging and a workflow client for interacting with the workflow engine.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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