operationrules

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ActionSleep                 = "Sleep"
	ActionPowerControl          = "PowerControl"
	ActionVerifyPowerStatus     = "VerifyPowerStatus"
	ActionVerifyReachability    = "VerifyReachability"
	ActionGetPowerStatus        = "GetPowerStatus"
	ActionFirmwareControl       = "FirmwareControl"
	ActionVerifyFirmwareVersion = "VerifyFirmwareVersion"

	// Bring-up specific actions
	ActionAllowBringUp      = "AllowBringUp"
	ActionWaitBringUp       = "WaitBringUp"
	ActionInjectExpectation = "InjectExpectation"
)

Action names used in YAML configuration (executor-agnostic)

View Source
const (
	ParamDuration       = "duration"        // For Sleep (time.Duration or string)
	ParamExpectedStatus = "expected_status" // For VerifyPowerStatus (string: "on"/"off")
	ParamComponentTypes = "component_types" // For VerifyReachability ([]string)
	ParamOperation      = "operation"       // For PowerControl/FirmwareControl (optional)
	ParamPollInterval   = "poll_interval"   // For FirmwareControl: firmware update poll interval
	ParamPollTimeout    = "poll_timeout"    // For FirmwareControl: firmware update poll timeout
	ParamRequireAll     = "require_all"     // For VerifyReachability: require every component to respond
)

Parameter keys for ActionConfig.Parameters

View Source
const (
	SequencePowerOn       = common.OpCodePowerControlPowerOn
	SequenceForcePowerOn  = common.OpCodePowerControlForcePowerOn
	SequencePowerOff      = common.OpCodePowerControlPowerOff
	SequenceForcePowerOff = common.OpCodePowerControlForcePowerOff
	SequenceRestart       = common.OpCodePowerControlRestart
	SequenceForceRestart  = common.OpCodePowerControlForceRestart
	SequenceWarmReset     = common.OpCodePowerControlWarmReset
	SequenceColdReset     = common.OpCodePowerControlColdReset
)

Power control sequence names - use shared operation codes

Firmware control sequence names - use shared operation codes

View Source
const (
	SequenceBringUp = common.OpCodeBringUp
	SequenceIngest  = common.OpCodeIngest
)

Bring-up sequence names - use shared operation codes

View Source
const CurrentRuleDefinitionVersion = "v1"

Current rule definition version

Variables

RequiredOperations maps operation types to their required operations These operations must have rules defined for the system to function properly

ValidOperations maps operation types to their valid operation codes Used for validating operation names in YAML configuration

Functions

func GetSequenceNameForOperation

func GetSequenceNameForOperation(operationType common.TaskType, operation any) string

GetSequenceNameForOperation maps operation-specific types to sequence names

func IsValidOperation

func IsValidOperation(opType common.TaskType, operation string) bool

IsValidOperation checks if an operation code is valid for the given operation type Returns true if the operation is recognized, false otherwise

func MarshalRuleDefinition

func MarshalRuleDefinition(rd RuleDefinition) (json.RawMessage, error)

MarshalRuleDefinition converts RuleDefinition to JSON for database storage MarshalRuleDefinition converts RuleDefinition to JSON, ensuring version is set

func ParseDuration

func ParseDuration(s string, name string) (time.Duration, error)

ParseDuration safely parses a duration string

func ValidateRequiredOperations

func ValidateRequiredOperations(
	opType common.TaskType,
	rules map[string]*OperationRule,
) error

ValidateRequiredOperations checks if all required operations have rules defined Takes a collection of rules for an operation type and verifies completeness

func ValidateStageSequence

func ValidateStageSequence(steps []SequenceStep) error

ValidateStageSequence validates that stages form a valid sequence Stages should start from 1 and increment, though gaps are allowed

Types

type ActionConfig

type ActionConfig struct {
	Name         string         `json:"name"`                    // Action name
	Timeout      time.Duration  `json:"timeout,omitempty"`       // Optional override
	PollInterval time.Duration  `json:"poll_interval,omitempty"` // For polling actions
	Parameters   map[string]any `json:"parameters,omitempty"`    // Action-specific params
}

ActionConfig defines configuration for a single action execution Note: "Action" is executor-agnostic (works with Temporal, future executors)

func (ActionConfig) MarshalJSON

func (ac ActionConfig) MarshalJSON() ([]byte, error)

MarshalJSON customizes JSON output for ActionConfig

func (*ActionConfig) UnmarshalJSON

func (ac *ActionConfig) UnmarshalJSON(data []byte) error

UnmarshalJSON customizes JSON parsing for ActionConfig

func (*ActionConfig) Validate

func (ac *ActionConfig) Validate() error

Validate validates an action configuration

type OperationRule

type OperationRule struct {
	ID             uuid.UUID       `json:"id"`
	Name           string          `json:"name"`
	Description    string          `json:"description,omitempty"`
	OperationType  common.TaskType `json:"operation_type"` // e.g., "power_control", "firmware_control"
	OperationCode  string          `json:"operation_code"` // e.g., "power_on", "power_off", "upgrade"
	RuleDefinition RuleDefinition  `json:"rule_definition"`
	IsDefault      bool            `json:"is_default"`
	CreatedAt      time.Time       `json:"created_at"`
	UpdatedAt      time.Time       `json:"updated_at"`
}

OperationRule represents a complete operation rule with metadata. Rules are templates that define how operations should be performed. Each rule applies to a specific operation type + operation code combination.

func (*OperationRule) SuggestOptimizations

func (rule *OperationRule) SuggestOptimizations() []string

SuggestOptimizations analyzes a rule and suggests potential optimizations This is a helper method for users to improve their rules

func (*OperationRule) Validate

func (rule *OperationRule) Validate() error

Validate validates a complete operation rule

type RackRuleAssociation

type RackRuleAssociation struct {
	RackID        uuid.UUID
	OperationType common.TaskType
	OperationCode string
	RuleID        uuid.UUID
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

RackRuleAssociation represents an association between a rack and an operation rule. Each association maps a specific rack to a rule for a particular operation.

type Resolver

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

Resolver resolves operation rules following priority hierarchy: 1. Database rack association (rack-specific rule via association table) 2. Database default rule (is_default=true for operation type + operation) 3. Hardcoded fallback

func NewResolver

func NewResolver(store RuleStore) *Resolver

NewResolver creates a new rule resolver.

func (*Resolver) ResolveRule

func (r *Resolver) ResolveRule(
	ctx context.Context,
	operationType common.TaskType,
	operation string,
	rackID uuid.UUID,
) (*OperationRule, error)

ResolveRule resolves the operation rule for a given operation type, operation, and rack. It always returns a rule (never nil) or an error. The resolution follows this priority: 1. Database rule (rack-specific or default) 2. Hardcoded default rule

type RetryPolicy

type RetryPolicy struct {
	MaxAttempts        int           `json:"max_attempts"`
	InitialInterval    time.Duration `json:"initial_interval"`       // Parsed once at rule creation time
	BackoffCoefficient float64       `json:"backoff_coefficient"`    // Exponential backoff multiplier
	MaxInterval        time.Duration `json:"max_interval,omitempty"` // Parsed once at rule creation time
}

RetryPolicy defines retry behavior for a step

func (RetryPolicy) MarshalJSON

func (rp RetryPolicy) MarshalJSON() ([]byte, error)

MarshalJSON customizes JSON output for RetryPolicy to format durations as strings

func (*RetryPolicy) UnmarshalJSON

func (rp *RetryPolicy) UnmarshalJSON(data []byte) error

UnmarshalJSON customizes JSON parsing for RetryPolicy to parse duration strings

func (*RetryPolicy) Validate

func (rp *RetryPolicy) Validate() error

Validate validates a retry policy

type RuleDefinition

type RuleDefinition struct {
	Version string         `json:"version"` // Schema version for forward compatibility
	Steps   []SequenceStep `json:"steps"`
}

RuleDefinition contains the actual execution steps for an operation. Each rule defines how to execute a specific operation (e.g., power_on, upgrade).

func UnmarshalRuleDefinition

func UnmarshalRuleDefinition(data json.RawMessage) (*RuleDefinition, error)

UnmarshalRuleDefinition converts JSON to RuleDefinition with version awareness

func (*RuleDefinition) CalculateWorkflowTimeout

func (rd *RuleDefinition) CalculateWorkflowTimeout() time.Duration

CalculateWorkflowTimeout computes total workflow timeout from steps. Parent workflow timeout is auto-calculated: stages run sequentially, steps within a stage run in parallel (take max timeout). Adds 10% safety buffer for orchestration overhead.

func (*RuleDefinition) GetMaxStage

func (rd *RuleDefinition) GetMaxStage() int

GetMaxStage returns the highest stage number in the rule

func (*RuleDefinition) GroupStepsByStage

func (rd *RuleDefinition) GroupStepsByStage() map[int][]SequenceStep

GroupStepsByStage organizes steps by their stage number Returns a map where keys are stage numbers and values are slices of steps

func (*RuleDefinition) Validate

func (rd *RuleDefinition) Validate() error

Validate validates a rule definition

type RuleLoader

type RuleLoader interface {
	Load() (map[common.TaskType]map[string]*OperationRule, error)
}

func NewYAMLRuleLoader

func NewYAMLRuleLoader(path string) (RuleLoader, error)

type RuleStore

type RuleStore interface {
	GetRuleByOperationAndRack(ctx context.Context, opType common.TaskType, operation string, rackID *uuid.UUID) (*OperationRule, error)
}

RuleStore defines the interface for operation rule persistence. This is a subset of the full Store interface focusing on rule operations.

type SequenceStep

type SequenceStep struct {
	// Which component type this step applies to
	ComponentType devicetypes.ComponentType `json:"component_type"`

	// Execution stage number (steps with same stage run in parallel)
	// Stage 1 executes first, then stage 2, etc.
	Stage int `json:"stage"`

	// Maximum parallel component operations (0 = unlimited, 1 = sequential)
	// Controls how many components of this type are processed concurrently
	MaxParallel int `json:"max_parallel"`

	// Child workflow configuration (applies to entire workflow: pre + main + post)
	Timeout     time.Duration `json:"timeout,omitempty"` // Child workflow timeout
	RetryPolicy *RetryPolicy  `json:"retry,omitempty"`   // Child workflow retry

	// Action sequences
	PreOperation  []ActionConfig `json:"pre_operation,omitempty"`  // Before main operation
	MainOperation ActionConfig   `json:"main_operation"`           // Primary operation
	PostOperation []ActionConfig `json:"post_operation,omitempty"` // After main operation

	// Legacy field for backward compatibility (deprecated: use MainOperation)
	DelayAfter time.Duration `json:"delay_after,omitempty"`
}

SequenceStep defines a single step in the execution sequence

func (*SequenceStep) DoMainOperation

func (step *SequenceStep) DoMainOperation() (bool, ActionConfig)

DoMainOperation returns whether there is a main operation to execute and the action configuration. Returns false if using legacy mode.

func (*SequenceStep) DoPostOperations

func (step *SequenceStep) DoPostOperations() (bool, []ActionConfig)

DoPostOperations returns whether there are post-operation actions to execute and the list of actions. This encapsulates the check and data access.

func (*SequenceStep) DoPreOperations

func (step *SequenceStep) DoPreOperations() (bool, []ActionConfig)

DoPreOperations returns whether there are pre-operation actions to execute and the list of actions. This encapsulates the check and data access.

func (SequenceStep) MarshalJSON

func (s SequenceStep) MarshalJSON() ([]byte, error)

MarshalJSON customizes JSON output for SequenceStep to format durations as strings

func (*SequenceStep) UnmarshalJSON

func (s *SequenceStep) UnmarshalJSON(data []byte) error

UnmarshalJSON customizes JSON parsing for SequenceStep to parse duration strings

func (*SequenceStep) Validate

func (step *SequenceStep) Validate() error

Validate validates a single sequence step The index parameter is used for error messages

type Stage

type Stage struct {
	Number int            // The actual stage number from the rule definition
	Steps  []SequenceStep // All steps in this stage (execute in parallel)
}

Stage represents a single execution stage with all its steps

type StageIterator

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

StageIterator provides ordered iteration over rule execution stages Use Next() to retrieve stages in order until it returns nil

func NewStageIterator

func NewStageIterator(ruleDef *RuleDefinition) *StageIterator

NewStageIterator creates an iterator for the given rule definition Stages are pre-sorted by stage number, ready for sequential execution

func (*StageIterator) HasNext

func (si *StageIterator) HasNext() bool

HasNext returns true if there are more stages to iterate Useful for checking without advancing the iterator

func (*StageIterator) Next

func (si *StageIterator) Next() *Stage

Next returns the next stage in execution order Returns nil when all stages have been returned

func (*StageIterator) Reset

func (si *StageIterator) Reset()

Reset resets the iterator to the beginning Allows re-iteration without creating a new iterator

type YAMLActionConfig

type YAMLActionConfig struct {
	Name         string         `yaml:"name"`
	Timeout      string         `yaml:"timeout,omitempty"`
	PollInterval string         `yaml:"poll_interval,omitempty"`
	Parameters   map[string]any `yaml:"parameters,omitempty"`
}

YAMLActionConfig represents an action configuration in YAML

type YAMLConfig

type YAMLConfig struct {
	Version string     `yaml:"version"`
	Rules   []YAMLRule `yaml:"rules"`
}

YAMLConfig represents the top-level structure of the operation rules YAML file

type YAMLRetryPolicy

type YAMLRetryPolicy struct {
	MaxAttempts        int     `yaml:"max_attempts"`
	InitialInterval    string  `yaml:"initial_interval"`
	BackoffCoefficient float64 `yaml:"backoff_coefficient"`
	MaxInterval        string  `yaml:"max_interval,omitempty"`
}

YAMLRetryPolicy represents retry configuration in YAML

type YAMLRule

type YAMLRule struct {
	Name          string     `yaml:"name"`
	Description   string     `yaml:"description,omitempty"`
	OperationType string     `yaml:"operation_type"`
	Operation     string     `yaml:"operation"`
	Steps         []YAMLStep `yaml:"steps"`
}

YAMLRule represents a single operation rule in the YAML config

type YAMLRuleLoader

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

func (*YAMLRuleLoader) Load

func (l *YAMLRuleLoader) Load() (map[common.TaskType]map[string]*OperationRule, error)

type YAMLStep

type YAMLStep struct {
	ComponentType string             `yaml:"component_type"`
	Stage         int                `yaml:"stage"`
	MaxParallel   int                `yaml:"max_parallel"`
	Timeout       string             `yaml:"timeout,omitempty"`
	Retry         *YAMLRetryPolicy   `yaml:"retry,omitempty"`
	PreOperation  []YAMLActionConfig `yaml:"pre_operation,omitempty"`
	MainOperation YAMLActionConfig   `yaml:"main_operation"`
	PostOperation []YAMLActionConfig `yaml:"post_operation,omitempty"`
	DelayAfter    string             `yaml:"delay_after,omitempty"` // Legacy
}

YAMLStep represents a single step in the YAML config

Jump to

Keyboard shortcuts

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