Documentation ¶
Overview ¶
Package state implements the representation of system state.
Index ¶
- Constants
- Variables
- func MockTime(now time.Time) (restore func())
- type Backend
- type Change
- func (c *Change) Abort()
- func (c *Change) AbortLanes(lanes []int)
- func (c *Change) AddAll(ts *TaskSet)
- func (c *Change) AddTask(t *Task)
- func (c *Change) Err() error
- func (c *Change) Get(key string, value interface{}) error
- func (c *Change) ID() string
- func (c *Change) IsClean() bool
- func (c *Change) IsReady() bool
- func (c *Change) Kind() string
- func (c *Change) LaneTasks(lanes ...int) []*Task
- func (c *Change) MarshalJSON() ([]byte, error)
- func (c *Change) Ready() <-chan struct{}
- func (c *Change) ReadyTime() time.Time
- func (c *Change) Set(key string, value interface{})
- func (c *Change) SetStatus(s Status)
- func (c *Change) SpawnTime() time.Time
- func (c *Change) State() *State
- func (c *Change) Status() Status
- func (c *Change) Summary() string
- func (c *Change) Tasks() []*Task
- func (c *Change) UnmarshalJSON(data []byte) error
- type HandlerFunc
- type RestartType
- type Retry
- type State
- func (s *State) AllWarnings() []*Warning
- func (s *State) Cache(key, value interface{})
- func (s *State) Cached(key interface{}) interface{}
- func (s *State) Change(id string) *Change
- func (s *State) Changes() []*Change
- func (s *State) ClearReboot()
- func (s *State) EnsureBefore(d time.Duration)
- func (s *State) Get(key string, value interface{}) error
- func (s *State) Lock()
- func (s *State) MarshalJSON() ([]byte, error)
- func (s *State) Modified() bool
- func (s *State) NewChange(kind, summary string) *Change
- func (s *State) NewLane() int
- func (s *State) NewTask(kind, summary string) *Task
- func (s *State) OkayWarnings(t time.Time) int
- func (s *State) PendingWarnings() ([]*Warning, time.Time)
- func (s *State) Prune(pruneWait, abortWait time.Duration, maxReadyChanges int)
- func (s *State) RequestRestart(t RestartType)
- func (s *State) Restarting() (bool, RestartType)
- func (s *State) Set(key string, value interface{})
- func (s *State) Task(id string) *Task
- func (s *State) TaskCount() int
- func (s *State) Tasks() []*Task
- func (s *State) Unlock()
- func (s *State) UnmarshalJSON(data []byte) error
- func (s *State) UnshowAllWarnings()
- func (s *State) VerifyReboot(curBootID string) error
- func (s *State) Warnf(template string, args ...interface{})
- func (s *State) WarningsSummary() (int, time.Time)
- type Status
- type Task
- func (t *Task) At(when time.Time)
- func (t *Task) AtTime() time.Time
- func (t *Task) Change() *Change
- func (t *Task) Clear(key string)
- func (t *Task) DoingTime() time.Duration
- func (t *Task) Errorf(format string, args ...interface{})
- func (t *Task) Get(key string, value interface{}) error
- func (t *Task) HaltTasks() []*Task
- func (t *Task) Has(key string) bool
- func (t *Task) ID() string
- func (t *Task) IsClean() bool
- func (t *Task) JoinLane(lane int)
- func (t *Task) Kind() string
- func (t *Task) Lanes() []int
- func (t *Task) Log() []string
- func (t *Task) Logf(format string, args ...interface{})
- func (t *Task) MarshalJSON() ([]byte, error)
- func (t *Task) NumHaltTasks() int
- func (t *Task) Progress() (label string, done, total int)
- func (t *Task) ReadyTime() time.Time
- func (t *Task) Set(key string, value interface{})
- func (t *Task) SetClean()
- func (t *Task) SetProgress(label string, done, total int)
- func (t *Task) SetStatus(new Status)
- func (t *Task) SpawnTime() time.Time
- func (t *Task) State() *State
- func (t *Task) Status() Status
- func (t *Task) Summary() string
- func (t *Task) UndoingTime() time.Duration
- func (t *Task) UnmarshalJSON(data []byte) error
- func (t *Task) WaitAll(ts *TaskSet)
- func (t *Task) WaitFor(another *Task)
- func (t *Task) WaitTasks() []*Task
- type TaskRunner
- func (r *TaskRunner) AddBlocked(pred func(t *Task, running []*Task) bool)
- func (r *TaskRunner) AddCleanup(kind string, cleanup HandlerFunc)
- func (r *TaskRunner) AddHandler(kind string, do, undo HandlerFunc)
- func (r *TaskRunner) AddOptionalHandler(match func(t *Task) bool, do, undo HandlerFunc)
- func (r *TaskRunner) Ensure() error
- func (r *TaskRunner) KnownTaskKinds() []string
- func (r *TaskRunner) SetBlocked(pred func(t *Task, running []*Task) bool)
- func (r *TaskRunner) Stop()
- func (r *TaskRunner) StopKinds(kind ...string)
- func (r *TaskRunner) Wait()
- type TaskSet
- func (ts *TaskSet) AddAll(anotherTs *TaskSet)
- func (ts *TaskSet) AddAllWithEdges(anotherTs *TaskSet) error
- func (ts *TaskSet) AddTask(task *Task)
- func (ts TaskSet) Edge(e TaskSetEdge) (*Task, error)
- func (ts *TaskSet) JoinLane(lane int)
- func (ts *TaskSet) MarkEdge(task *Task, edge TaskSetEdge)
- func (ts TaskSet) Tasks() []*Task
- func (ts *TaskSet) WaitAll(anotherTs *TaskSet)
- func (ts TaskSet) WaitFor(another *Task)
- type TaskSetEdge
- type Warning
Constants ¶
const ( // Messages logged in tasks are guaranteed to use the time formatted // per RFC3339 plus the following strings as a prefix, so these may // be handled programmatically and parsed or stripped for presentation. LogInfo = "INFO" LogError = "ERROR" )
Variables ¶
var ( DefaultRepeatAfter = time.Hour * 24 DefaultExpireAfter = time.Hour * 24 * 28 )
var ErrExpectedReboot = errors.New("expected reboot did not happen")
var ErrNoState = errors.New("no state entry for key")
ErrNoState represents the case of no state entry for a given key.
Functions ¶
Types ¶
type Backend ¶
type Backend interface { Checkpoint(data []byte) error EnsureBefore(d time.Duration) // TODO: take flags to ask for reboot vs restart? RequestRestart(t RestartType) }
A Backend is used by State to checkpoint on every unlock operation and to mediate requests to ensure the state sooner or request restarts.
type Change ¶
type Change struct {
// contains filtered or unexported fields
}
Change represents a tracked modification to the system state.
The Change provides both the justification for individual tasks to be performed and the grouping of them.
As an example, if an administrator requests an interface connection, multiple hooks might be individually run to accomplish the task. The Change summary would reflect the request for an interface connection, while the individual Task values would track the running of the hooks themselves.
func (*Change) Abort ¶
func (c *Change) Abort()
Abort flags the change for cancellation, whether in progress or not. Cancellation will proceed at the next ensure pass.
func (*Change) AbortLanes ¶
AbortLanes aborts all tasks in the provided lanes and any tasks waiting on them, except for tasks that are also in a healthy lane (not aborted, and not waiting on aborted).
func (*Change) AddAll ¶
AddAll registers all tasks in the set as required for the state change to be accomplished.
func (*Change) AddTask ¶
AddTask registers a task as required for the state change to be accomplished.
func (*Change) Err ¶
Err returns an error value based on errors that were logged for tasks registered in this change, or nil if the change is not in ErrorStatus.
func (*Change) Get ¶
Get unmarshals the stored value associated with the provided key into the value parameter.
func (*Change) IsClean ¶
IsClean returns whether all tasks in the change have been cleaned. See SetClean.
func (*Change) IsReady ¶
IsReady returns whether the change is considered ready.
The result is similar to calling Ready on the status returned by the Status method, but this function is more efficient as it doesn't need to recompute the aggregated state of tasks on every call.
As an exception, IsReady returns false for a Change without any tasks that never had its status explicitly set and was never unmarshalled out of the persistent state, despite its initial status being Hold. This is how the system represents changes right after they are created.
func (*Change) LaneTasks ¶
LaneTasks returns all tasks from given lanes the state change depends on.
func (*Change) MarshalJSON ¶
MarshalJSON makes Change a json.Marshaller
func (*Change) Ready ¶
func (c *Change) Ready() <-chan struct{}
Ready returns a channel that is closed the first time the change becomes ready.
func (*Change) Set ¶
Set associates value with key for future consulting by managers. The provided value must properly marshal and unmarshal with encoding/json.
func (*Change) SetStatus ¶
SetStatus sets the change status, overriding the default behavior (see Status method).
func (*Change) Status ¶
Status returns the current status of the change. If the status was not explicitly set the result is derived from the status of the individual tasks related to the change, according to the following decision sequence:
- With at least one task in DoStatus, return DoStatus
- With at least one task in ErrorStatus, return ErrorStatus
- Otherwise, return DoneStatus
func (*Change) UnmarshalJSON ¶
UnmarshalJSON makes Change a json.Unmarshaller
type HandlerFunc ¶
HandlerFunc is the type of function for the handlers
type RestartType ¶
type RestartType int
const ( RestartUnset RestartType = iota RestartDaemon RestartSystem // RestartSocket will restart the daemon so that it goes into // socket activation mode. RestartSocket )
func MockRestarting ¶
func MockRestarting(s *State, restarting RestartType) RestartType
type Retry ¶
Retry is returned from a handler to signal that is ok to rerun the task at a later point. It's to be used also when a task goroutine is asked to stop through its tomb. After can be used to indicate how much to postpone the retry, 0 (the default) means at the next ensure pass and is what should be used if stopped through its tomb. Reason is an optional explanation of the conflict.
type State ¶
type State struct {
// contains filtered or unexported fields
}
State represents an evolving system state that persists across restarts.
The State is concurrency-safe, and all reads and writes to it must be performed with the state locked. It's a runtime error (panic) to perform operations without it.
The state is persisted on every unlock operation via the StateBackend it was initialized with.
func (*State) AllWarnings ¶
AllWarnings returns all the warnings in the system, whether they're due to be shown or not. They'll be sorted by lastAdded.
func (*State) Cache ¶
func (s *State) Cache(key, value interface{})
Cache associates value with key for future consulting by managers. The cached value is not persisted.
func (*State) Cached ¶
func (s *State) Cached(key interface{}) interface{}
Cached returns the cached value associated with the provided key. It returns nil if there is no entry for key.
func (*State) ClearReboot ¶
func (s *State) ClearReboot()
ClearReboot clears state information about tracking requested reboots.
func (*State) EnsureBefore ¶
EnsureBefore asks for an ensure pass to happen sooner within duration from now.
func (*State) Get ¶
Get unmarshals the stored value associated with the provided key into the value parameter. It returns ErrNoState if there is no entry for key.
func (*State) MarshalJSON ¶
MarshalJSON makes State a json.Marshaller
func (*State) NewTask ¶
NewTask creates a new task. It usually will be registered with a Change using AddTask or through a TaskSet.
func (*State) OkayWarnings ¶
OkayWarnings marks warnings that were showable at the given time as shown.
func (*State) PendingWarnings ¶
PendingWarnings returns the list of warnings to show the user, sorted by lastAdded, and a timestamp than can be used to refer to these warnings.
Warnings to show to the user are those that have not been shown before, or that have been shown earlier than repeatAfter ago.
func (*State) Prune ¶
Prune does several cleanup tasks to the in-memory state:
it removes changes that became ready for more than pruneWait and aborts tasks spawned for more than abortWait.
it removes tasks unlinked to changes after pruneWait. When there are more changes than the limit set via "maxReadyChanges" those changes in ready state will also removed even if they are below the pruneWait duration.
it removes expired warnings.
func (*State) RequestRestart ¶
func (s *State) RequestRestart(t RestartType)
RequestRestart asks for a restart of the managing process. The state needs to be locked to request a RestartSystem.
func (*State) Restarting ¶
func (s *State) Restarting() (bool, RestartType)
Restarting returns whether a restart was requested with RequestRestart and of which type.
func (*State) Set ¶
Set associates value with key for future consulting by managers. The provided value must properly marshal and unmarshal with encoding/json.
func (*State) Task ¶
Task returns the task for the given ID if the task has been linked to a change.
func (*State) TaskCount ¶
TaskCount returns the number of tasks that currently exist in the state, whether linked to a change or not.
func (*State) Unlock ¶
func (s *State) Unlock()
Unlock releases the state lock and checkpoints the state. It does not return until the state is correctly checkpointed. After too many unsuccessful checkpoint attempts, it panics.
func (*State) UnmarshalJSON ¶
UnmarshalJSON makes State a json.Unmarshaller
func (*State) UnshowAllWarnings ¶
func (s *State) UnshowAllWarnings()
UnshowAllWarnings clears the lastShown timestamp from all the warnings. For use in debugging.
func (*State) VerifyReboot ¶
VerifyReboot checks if the state rembers that a system restart was requested and whether it succeeded based on the provided current boot id. It returns ErrExpectedReboot if the expected reboot did not happen yet. It must be called early in the usage of state and before an RequestRestart with RestartSystem is attempted. It must be called with the state lock held.
type Status ¶
type Status int
Status is used for status values for changes and tasks.
const ( // DefaultStatus is the standard computed status for a change or task. // For tasks it's always mapped to DoStatus, and for change its mapped // to an aggregation of its tasks' statuses. See Change.Status for details. DefaultStatus Status = 0 // HoldStatus means the task should not run, perhaps as a consequence of an error on another task. HoldStatus Status = 1 // DoStatus means the change or task is ready to start. DoStatus Status = 2 // DoingStatus means the change or task is running or an attempt was made to run it. DoingStatus Status = 3 // DoneStatus means the change or task was accomplished successfully. DoneStatus Status = 4 // AbortStatus means the task should stop doing its activities and then undo. AbortStatus Status = 5 // UndoStatus means the change or task should be undone, probably due to an error elsewhere. UndoStatus Status = 6 // UndoingStatus means the change or task is being undone or an attempt was made to undo it. UndoingStatus Status = 7 // UndoneStatus means a task was first done and then undone after an error elsewhere. // Changes go directly into the error status instead of being marked as undone. UndoneStatus Status = 8 // ErrorStatus means the change or task has errored out while running or being undone. ErrorStatus Status = 9 )
Admitted status values for changes and tasks.
type Task ¶
type Task struct {
// contains filtered or unexported fields
}
Task represents an individual operation to be performed for accomplishing one or more state changes.
See Change for more details.
func (*Task) At ¶
At schedules the task, if it's not ready, to happen no earlier than when, if when is the zero time any previous special scheduling is suppressed.
func (*Task) AtTime ¶
AtTime returns the time at which the task is scheduled to run. A zero time means no special schedule, i.e. run as soon as prerequisites are met.
func (*Task) Get ¶
Get unmarshals the stored value associated with the provided key into the value parameter.
func (*Task) JoinLane ¶
JoinLane registers the task in the provided lane. Tasks in different lanes abort independently on errors. See Change.AbortLane for details.
func (*Task) Log ¶
Log returns the most recent messages logged into the task.
Only the most recent entries logged are returned, potentially with different behavior for different task statuses. How many entries are returned is an implementation detail and may change over time.
Messages are prefixed with one of the known message kinds. See details about LogInfo and LogError.
The returned slice should not be read from without the state lock held, and should not be written to.
func (*Task) MarshalJSON ¶
MarshalJSON makes Task a json.Marshaller
func (*Task) NumHaltTasks ¶
NumHaltTasks returns the number of tasks registered to wait for t.
func (*Task) Progress ¶
Progress returns the current progress for the task. If progress is not explicitly set, it returns (0, 1) if the status is DoStatus and (1, 1) otherwise.
func (*Task) Set ¶
Set associates value with key for future consulting by managers. The provided value must properly marshal and unmarshal with encoding/json.
func (*Task) SetClean ¶
func (t *Task) SetClean()
SetClean flags the task as clean after any left over data was removed.
Cleaning a task must only be done after the change is ready.
func (*Task) SetProgress ¶
SetProgress sets the task progress to cur out of total steps.
func (*Task) SetStatus ¶
SetStatus sets the task status, overriding the default behavior (see Status method).
func (*Task) UndoingTime ¶
func (*Task) UnmarshalJSON ¶
UnmarshalJSON makes Task a json.Unmarshaller
func (*Task) WaitAll ¶
WaitAll registers all the tasks in the set as a requirement for t to make progress.
type TaskRunner ¶
type TaskRunner struct {
// contains filtered or unexported fields
}
TaskRunner controls the running of goroutines to execute known task kinds.
func NewTaskRunner ¶
func NewTaskRunner(s *State) *TaskRunner
NewTaskRunner creates a new TaskRunner
func (*TaskRunner) AddBlocked ¶
func (r *TaskRunner) AddBlocked(pred func(t *Task, running []*Task) bool)
AddBlocked adds a predicate function to decide whether to block a task from running based on the current running tasks. It can be used to control task serialisation. All added predicates are considered in turn until one returns true, or none.
func (*TaskRunner) AddCleanup ¶
func (r *TaskRunner) AddCleanup(kind string, cleanup HandlerFunc)
AddCleanup registers a function to be called after the change completes, for cleaning up data left behind by tasks of the specified kind. The provided function will be called no matter what the final status of the task is. This mechanism enables keeping data around for a potential undo until there's no more chance of the task being undone.
The cleanup function is run concurrently with other cleanup functions, despite any wait ordering between the tasks. If it returns an error, it will be retried later.
The handler for tasks of the provided kind must have been previously registered before AddCleanup is called for it.
func (*TaskRunner) AddHandler ¶
func (r *TaskRunner) AddHandler(kind string, do, undo HandlerFunc)
AddHandler registers the functions to concurrently call for doing and undoing tasks of the given kind. The undo handler may be nil.
func (*TaskRunner) AddOptionalHandler ¶
func (r *TaskRunner) AddOptionalHandler(match func(t *Task) bool, do, undo HandlerFunc)
AddOptionalHandler register functions for doing and undoing tasks that match the given predicate if no explicit handler was registered for the task kind.
func (*TaskRunner) Ensure ¶
func (r *TaskRunner) Ensure() error
Ensure starts new goroutines for all known tasks with no pending dependencies. Note that Ensure will lock the state.
func (*TaskRunner) KnownTaskKinds ¶
func (r *TaskRunner) KnownTaskKinds() []string
KnownTaskKinds returns all tasks kinds handled by this runner.
func (*TaskRunner) SetBlocked ¶
func (r *TaskRunner) SetBlocked(pred func(t *Task, running []*Task) bool)
SetBlocked sets a predicate function to decide whether to block a task from running based on the current running tasks. It can be used to control task serialisation.
func (*TaskRunner) Stop ¶
func (r *TaskRunner) Stop()
Stop kills all concurrent activities and returns after that's done.
func (*TaskRunner) StopKinds ¶
func (r *TaskRunner) StopKinds(kind ...string)
StopKinds kills all concurrent tasks of the given kinds and returns after that's done.
func (*TaskRunner) Wait ¶
func (r *TaskRunner) Wait()
Wait waits for all concurrent activities and returns after that's done.
type TaskSet ¶
type TaskSet struct {
// contains filtered or unexported fields
}
A TaskSet holds a set of tasks.
func NewTaskSet ¶
NewTaskSet returns a new TaskSet comprising the given tasks.
func (*TaskSet) AddAllWithEdges ¶
AddAllWithEdges adds all the tasks in the argument set to the target set ts and also adds all TaskSetEdges. Duplicated TaskSetEdges are an error.
func (TaskSet) Edge ¶
func (ts TaskSet) Edge(e TaskSetEdge) (*Task, error)
Edge returns the task marked with the given edge name.
func (*TaskSet) MarkEdge ¶
func (ts *TaskSet) MarkEdge(task *Task, edge TaskSetEdge)
MarkEdge marks the given task as a specific edge. Any pre-existing edge mark will be overridden.
type TaskSetEdge ¶
type TaskSetEdge string
TaskSetEdge designates tasks inside a TaskSet for outside reference.
This is useful to give tasks inside TaskSets a special meaning. It is used to mark e.g. the last task used for downloading a snap.
type Warning ¶
type Warning struct {
// contains filtered or unexported fields
}