fsm

package
v0.0.0-...-3bfe646 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2023 License: Apache-2.0 Imports: 37 Imported by: 8

Documentation

Index

Constants

View Source
const (
	// CanRunLocally states that the task can run locally
	CanRunLocally = ExecutionCheck(iota)
	// CanRunRemotely states that the task can run remotely
	CanRunRemotely
	// ShouldRunRemotely states that the task should run remotely
	ShouldRunRemotely
	// ExecutionCheckUndefined signifies the unknown task execution mode
	ExecutionCheckUndefined
)
View Source
const RootPhase = "/"

RootPhase is the name of the top-level phase

Variables

This section is empty.

Functions

func AgentSecretsDir

func AgentSecretsDir() (string, error)

AgentSecretsDir returns the location of agent credentials

func CanRollback

func CanRollback(plan storage.OperationPlan, phaseID string) error

CanRollback checks if specified phase can be rolled back

func CheckMasterServer

func CheckMasterServer(servers []storage.Server) error

CheckMasterServer makes sure this method is executed on a master server

func CheckPlanCoordinator

func CheckPlanCoordinator(p *storage.OperationPlan) error

CheckPlanCoordinator ensures that the node this function is invoked on is the coordinator node specified in the plan.

This is mainly important for making sure the plan is executed on the lead node for a particular plan - for example, for etcd upgrades, where state can only be kept in sync on the lead master node itself.

func CompleteOrFailOperation

func CompleteOrFailOperation(ctx context.Context, plan storage.OperationPlan, operator ops.Operator, planErr string) (err error)

CompleteOrFailOperation completes or fails the operation given by the plan in the specified operator. planErr optionally specifies the error to record in the failed message and record operation failure

func DiffChangelog

func DiffChangelog(local, remote storage.PlanChangelog) []storage.PlanChange

DiffChangelog returns a list of changelog entries from "local" that are missing from "remote"

func FindPhase

func FindPhase(plan storage.OperationPlan, phaseID string) (result *storage.OperationPhase, err error)

FindPhase finds a phase with the specified id in the provided plan

func FollowOperationPlan

func FollowOperationPlan(ctx context.Context, getPlan GetPlanFunc) <-chan PlanEvent

FollowOperationPlan returns a channel that will be receiving phase updates for the specified plan. The returned channel must be served to avoid blocking the producer as no events are dropped.

The watch will stop upon entering one of the terminal operation states, for example if the obtained plan is completed or fully rolled back or when the specified context has expired. In any case, the channel will be closed to signal completion

func FormatOperationPlanJSON

func FormatOperationPlanJSON(w io.Writer, plan storage.OperationPlan) error

func FormatOperationPlanShort

func FormatOperationPlanShort(w io.Writer, plan storage.OperationPlan)

FormatOperationPlanShort formats provided operation plan as text with fewer number of columns.

func FormatOperationPlanText

func FormatOperationPlanText(w io.Writer, plan storage.OperationPlan)

func FormatOperationPlanYAML

func FormatOperationPlanYAML(w io.Writer, plan storage.OperationPlan) error

func GetClientCredentials

func GetClientCredentials() (credentials.TransportCredentials, error)

GetClientCredentials reads the RPC credentials for an update operation from a predefined directory.

The reason credentials are not read from the cluster package service is that during certain operations (cluster upgrades, cluster or environment configuration updates), the etcd backend might be temporarily inaccessible between commands hence in this mode, the credentials are cached on disk.

func GetNumPhases

func GetNumPhases(plan storage.OperationPlan) (numPhases int)

GetNumPhases computes the number of phases in the given plan

func GetOperationPlan

func GetOperationPlan(backend storage.Backend, opKey ops.SiteOperationKey) (*storage.OperationPlan, error)

GetOperationPlan returns plan for the specified operation

func GetPlanProgress

func GetPlanProgress(plan storage.OperationPlan) (progress []storage.PlanChange)

GetPlanProgress returns phases of the plan that have been executed so far in the form of a changelog.

func GetUpsertBootstrapResourceFunc

func GetUpsertBootstrapResourceFunc(client *kubernetes.Clientset) resources.ResourceFunc

GetUpsertBootstrapResourceFunc returns a function that takes a Kubernetes object representing a bootstrap resource (ClusterRole, ClusterRoleBinding or PodSecurityPolicy) and creates or updates it using the provided client

func HasFailed

func HasFailed(plan storage.OperationPlan) bool

HasFailed returns true if the provided plan has at least one failed phase

func IsCompleted

func IsCompleted(plan storage.OperationPlan) bool

IsCompleted returns true if all phases of the provided plan are completed

func IsFailed

func IsFailed(plan storage.OperationPlan) bool

IsFailed returns true if all phases of the provided plan are either rolled back or unstarted

func IsMasterServer

func IsMasterServer(server storage.Server) bool

IsMasterServer returns true if the provided service has a master cluster role

func IsRolledBack

func IsRolledBack(plan storage.OperationPlan) bool

IsRolledBack returns true if the provided plan is rolled back.

func MarkCompleted

func MarkCompleted(plan storage.OperationPlan) storage.OperationPlan

MarkCompleted marks all phases of the plan as completed

func NewAgentRunner

NewAgentRunner creates a new RemoteRunner that uses a cluster of agents to run remote commands

func OperationKey

func OperationKey(plan storage.OperationPlan) ops.SiteOperationKey

OperationKey returns the operation key for the specified operation plan

func OperationStateSetter

func OperationStateSetter(key ops.SiteOperationKey, operator ops.Operator, backend storage.Backend) ops.OperationStateFunc

OperationStateSetter returns the handler to set operation state both in the given operator as well as the specified backend

func RequireIfPresent

func RequireIfPresent(plan storage.OperationPlan, phaseIDs ...string) []string

RequireIfPresent takes a list of phase IDs and returns those that are present in the provided plan

func ResolvePlan

func ResolvePlan(plan storage.OperationPlan, changelog storage.PlanChangelog) storage.OperationPlan

ResolvePlan applies changelog to the provided plan and returns the resulting plan

func RunCommand

func RunCommand(args []string) ([]byte, error)

RunCommand executes the provided command locally and returns its output

func SplitServers

func SplitServers(servers []storage.Server) (masters, nodes []storage.Server)

SplitServers splits the specified server list into servers with master cluster role and regular nodes.

func VisitPlan

func VisitPlan(plan storage.OperationPlan, cb func(phase storage.OperationPhase) bool)

VisitPlan executes the specified callback on each phase in the plan

func VisitPlanRef

func VisitPlanRef(plan *storage.OperationPlan, cb func(phase *storage.OperationPhase) bool)

VisitPlanRef executes the specified callback on each phase in the plan. The callback receives a mutable reference so any changes are persisted

Types

type Config

type Config struct {
	// Engine is the specific FSM engine
	Engine
	// Runner is used to run remote commands
	Runner rpc.RemoteRunner
	// Insecure allows to turn off cert validation in dev mode
	Insecure bool
	// Logger allows to override default logger
	Logger logrus.FieldLogger
}

Config represents config

func (*Config) CheckAndSetDefaults

func (c *Config) CheckAndSetDefaults() error

CheckAndSetDefaults makes sure the config is valid and sets some defaults

type Engine

type Engine interface {
	// GetExecutor returns a new executor based on the provided parameters
	GetExecutor(ExecutorParams, Remote) (PhaseExecutor, error)
	// ChangePhaseState updates the phase state based on the provided parameters
	ChangePhaseState(context.Context, StateChange) error
	// GetPlan returns the up-to-date operation plan
	GetPlan() (*storage.OperationPlan, error)
	// RunCommand executes the phase specified by params on the specified
	// server using the provided runner
	RunCommand(context.Context, rpc.RemoteRunner, storage.Server, Params) error
	// Complete transitions the operation to a completed state.
	// Completed state is either successful or failed depending on the state of
	// the operation plan.
	// The optional error can be used to specify the reason for failure and
	// defines the final operation failure
	Complete(context.Context, error) error
}

Engine defines interface for specific FSM implementations

type ExecutionCheck

type ExecutionCheck int

type ExecutorParams

type ExecutorParams struct {
	// Plan is the operation plan
	Plan storage.OperationPlan
	// Phase is the plan phase
	Phase storage.OperationPhase
	// Progress is the progress reporter
	Progress utils.Progress
}

ExecutorParams combines parameters needed for creating a new executor

func (ExecutorParams) Key

Key returns an operation key from these params

type FSM

type FSM struct {
	// Config is the FSM config
	Config
	// FieldLogger is used for logging
	logrus.FieldLogger
	// contains filtered or unexported fields
}

FSM is the generic FSM implementation that provides methods for phases execution and rollback, state transitioning and command execution

func New

func New(config Config) (*FSM, error)

New returns a new FSM instance

func (*FSM) ChangePhaseState

func (f *FSM) ChangePhaseState(ctx context.Context, change StateChange) error

ChangePhaseState updates the specified phase state.

func (*FSM) CheckServer

func (f *FSM) CheckServer(ctx context.Context, server storage.Server) error

CheckServer determines if the specified server is a local machine or has an agent running. Returns an error if the server cannot be used to execute a command (neither is a local machine nor has an agent running).

func (*FSM) Close

func (f *FSM) Close() error

Close releases all FSM resources

func (*FSM) ExecutePhase

func (f *FSM) ExecutePhase(ctx context.Context, p Params) error

ExecutePhase executes the specified phase of the plan

func (*FSM) ExecutePlan

func (f *FSM) ExecutePlan(ctx context.Context, progress utils.Progress) error

ExecutePlan iterates over all phases of the plan and executes them in order

func (*FSM) RollbackPhase

func (f *FSM) RollbackPhase(ctx context.Context, p Params) error

RollbackPhase rolls back the specified phase of the plan

func (*FSM) RollbackPlan

func (f *FSM) RollbackPlan(ctx context.Context, progress utils.Progress, dryRun bool) error

RollbackPlan rolls back all phases of the plan that have been attempted so far in the reverse order.

func (*FSM) SetPostExec

func (f *FSM) SetPostExec(fn PhaseHookFn)

SetPostExec sets the hook that's called after phase execution

func (*FSM) SetPreExec

func (f *FSM) SetPreExec(fn PhaseHookFn)

SetPreExec sets the hook that's called before phase execution

type FSMSpecFunc

type FSMSpecFunc func(ExecutorParams, Remote) (PhaseExecutor, error)

FSMSpecFunc defines a function that returns an appropriate executor for the specified operation phase

type GetPlanFunc

type GetPlanFunc func() (*storage.OperationPlan, error)

GetPlanFunc is a function that returns an operation plan.

type Logger

type Logger struct {
	// FieldLogger is the underlying standard logger
	logrus.FieldLogger
	// Key is the operation the logger is for
	Key ops.SiteOperationKey
	// Operator is the operator service where log entries are submitted
	Operator ops.Operator
	// Server is the optional server that will be attached to log entries
	Server *storage.Server
}

Logger logs both to the configured underlying logger and to the operation log using the Operator it was initialized with

func (*Logger) Debug

func (l *Logger) Debug(args ...interface{})

Debug logs a debug message

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...interface{})

Debugf logs a debug message

func (*Logger) Error

func (l *Logger) Error(args ...interface{})

Error logs an error message

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...interface{})

Errorf logs an error message

func (*Logger) Info

func (l *Logger) Info(args ...interface{})

Info logs an info message

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...interface{})

Infof logs an info message

func (*Logger) Warn

func (l *Logger) Warn(args ...interface{})

Warn logs a warning message

func (*Logger) Warnf

func (l *Logger) Warnf(format string, args ...interface{})

Warnf logs a warning message

func (*Logger) Warning

func (l *Logger) Warning(args ...interface{})

Warning logs a warning message

func (*Logger) Warningf

func (l *Logger) Warningf(format string, args ...interface{})

Warningf logs a warning message

type Params

type Params struct {
	// PhaseID is the id of the phase to execute/rollback
	PhaseID string
	// OperationID is the operation ID this phase is executed for
	OperationID string
	// Force is whether to force execution/rollback
	Force bool
	// Resume determines whether a failed/in-progress phase is rerun.
	//
	// It is different from Force which forces a phase in any state
	// to be rerun - this is unexpected when the operation is resumed
	// and only the unfinished/failed steps are re-executed
	Resume bool
	// Rollback indicates that the specified phase should be rolled back.
	Rollback bool
	// Progress is optional progress reporter
	Progress utils.Progress
	// DryRun allows to only print phases without executing/rolling back.
	DryRun bool
}

Params combines parameters for phase execution/rollback

func (*Params) CheckAndSetDefaults

func (p *Params) CheckAndSetDefaults() error

CheckAndSetDefaults makes sure all required parameters are set

func (Params) IsResume

func (p Params) IsResume() bool

IsResume returns true if parameters describe a resume command

type PhaseExecutor

type PhaseExecutor interface {
	// PreCheck is called before phase execution
	PreCheck(context.Context) error
	// PostCheck is called after successful phase execution
	PostCheck(context.Context) error
	// Execute executes phase
	Execute(context.Context) error
	// Rollback performs phase rollback
	Rollback(context.Context) error
	// FieldLogger allows FSM engine to use phase-specific logger
	logrus.FieldLogger
}

PhaseExecutor defines an operation plan phase executor

An executor performs a (compound) operation that it can then roll back in case any of the intermediate steps fail.

An executor can optionally validate its requirements and outcomes by implementing non-trivial PreCheck/PostCheck APIs.

type PhaseHookFn

type PhaseHookFn func(context.Context, Params) error

PhaseHookFn defines the phase hook function

type PlanChangedEvent

type PlanChangedEvent struct {
	// Change is a plan phase change.
	Change storage.PlanChange
}

PlanChangedEvent is sent when plan phases change states.

type PlanCompletedEvent

type PlanCompletedEvent struct{}

PlanCompletedEvent is sent when the plan is fully completed.

type PlanEvent

type PlanEvent interface {
	// contains filtered or unexported methods
}

PlanEvent represents an operation plan event.

type PlanRolledBackEvent

type PlanRolledBackEvent struct{}

PlanRolledBackEvent is sent when the plan is fully rolled back.

type Remote

type Remote interface {
	// CheckServer determines if the specified server is a local machine
	// or has an agent running. Returns an error if the server cannot be
	// used to execute a command (neither is a local machine nor has an agent running).
	CheckServer(context.Context, storage.Server) error
}

Remote allows to invoke remote commands

type StateChange

type StateChange struct {
	// Phase is the id of the phase that changes state
	Phase string
	// State is the new phase state
	State string
	// Error is the error that happened during phase execution
	Error trace.Error
}

StateChange represents phase state transition

func (StateChange) Check

func (c StateChange) Check() error

Check verifies that state change is valid.

func (StateChange) String

func (c StateChange) String() string

String returns a textual representation of this state change

Jump to

Keyboard shortcuts

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