state

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package state manages OCFP bloc state persistence, backup, reconciliation, and resource tracking.

Index

Constants

View Source
const (
	// Network resources.
	ResourceTypeNetwork       = "network"
	ResourceTypeSubnet        = "subnet"
	ResourceTypeSecurityGroup = "security_group"
	ResourceTypePublicIP      = "public_ip"
	ResourceTypeFloatingIP    = "floating_ip"
	ResourceTypeRouter        = "router"
	ResourceTypeLoadBalancer  = "load_balancer"

	// Compute resources.
	ResourceTypeInstance = "compute_instance"
	ResourceTypeKeyPair  = "ssh_key_pair"
	ResourceTypeVolume   = "block_volume"
	ResourceTypeImage    = "compute_image"
	ResourceTypeFlavor   = "compute_flavor"

	// Storage resources.
	ResourceTypeBucket           = "object_storage_bucket"
	ResourceTypeSnapshot         = "volume_snapshot"
	ResourceTypeCredentialsGroup = "credentials_group"
)

ResourceType constants for different cloud resources.

Variables

View Source
var (
	ErrNoStateLoaded        = errors.New("no state loaded")
	ErrResourceIDRequired   = errors.New("resource ID is required")
	ErrStateIsLocked        = errors.New("state is locked")
	ErrNoBackupsAvailable   = errors.New("no backups available for rollback")
	ErrCurrentStateNil      = errors.New("current state cannot be nil")
	ErrDiffSetNil           = errors.New("diff set cannot be nil")
	ErrUnknownMergeStrategy = errors.New("invalid merge strategy")
	ErrProviderNil          = errors.New("provider cannot be nil")
	ErrStateManagerNil      = errors.New("state manager cannot be nil")
	ErrBlocNameEmpty        = errors.New("bloc name cannot be empty")
)

State management errors.

Functions

func ErrOutputNotFound

func ErrOutputNotFound(key string) error

ErrOutputNotFound returns an error indicating the specified output key was not found in state.

func ErrResourceNotFound

func ErrResourceNotFound(key string) error

ErrResourceNotFound returns an error indicating the specified resource key was not found in state.

func ErrStateIsLockedBy

func ErrStateIsLockedBy(owner, createdAt interface{}) error

ErrStateIsLockedBy returns an error indicating the state is locked by the given owner since the given time.

func GetResourcesByCategory

func GetResourcesByCategory(category ResourceCategory) []string

GetResourcesByCategory returns all resource types in a category.

func GetStateDir

func GetStateDir(blocName string) (string, error)

GetStateDir returns the standard state directory path for a given bloc. Resolves under config.StateHome() (OCFP_HOME when set, else $XDG_STATE_HOME/ocfp or the ~/.local/state/ocfp default), with a dual-read fallback to the pre-migration ~/.ocfp/{blocName}/state directory when only that exists.

func UpdateResourceFromDiscovered

func UpdateResourceFromDiscovered(stateRes *Resource, discoveredRes *Resource)

UpdateResourceFromDiscovered updates a state resource with discovered resource data.

Types

type BackupInfo

type BackupInfo struct {
	Path      string
	Timestamp time.Time
	Size      int64
}

BackupInfo contains information about a state backup.

type DiffSet

type DiffSet struct {
	// Added resources (in provider, not in state)
	Added []*ResourceDiff

	// Modified resources (in both, but changed)
	Modified []*ResourceDiff

	// Deleted resources (in state, not in provider)
	Deleted []*ResourceDiff

	// Unchanged resources (in both, no changes)
	Unchanged []*ResourceDiff

	// TotalStateResources is the count of resources in state
	TotalStateResources int

	// TotalDiscoveredResources is the count of resources discovered
	TotalDiscoveredResources int
}

DiffSet contains all differences between state and discovered resources.

func CompareResources

func CompareResources(stateResources map[string]*Resource, discoveredResources []*Resource) *DiffSet

CompareResources compares state resources with discovered resources and returns a DiffSet.

func (*DiffSet) HasChanges

func (ds *DiffSet) HasChanges() bool

HasChanges returns true if there are any additions, modifications, or deletions.

func (*DiffSet) Summary

func (ds *DiffSet) Summary() string

Summary returns a human-readable summary of the diff set.

func (*DiffSet) TotalChanges

func (ds *DiffSet) TotalChanges() int

TotalChanges returns the total number of changes (added + modified + deleted).

type DiffType

type DiffType string

DiffType represents the type of change detected.

const (
	// DiffTypeAdded indicates a resource exists in provider but not in state.
	DiffTypeAdded DiffType = "added"

	// DiffTypeModified indicates a resource exists in both but has changed.
	DiffTypeModified DiffType = "modified"

	// DiffTypeDeleted indicates a resource exists in state but not in provider.
	DiffTypeDeleted DiffType = "deleted"

	// DiffTypeUnchanged indicates a resource exists in both and hasn't changed.
	DiffTypeUnchanged DiffType = "unchanged"
)

type Manager

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

Manager handles state persistence and retrieval.

func NewManager

func NewManager(stateDir string) (*Manager, error)

NewManager creates a new state manager. If stateDir is empty, it defaults to the state directory under config.StateHome(), with a dual-read fallback to the pre-migration ~/.ocfp/state/ directory when only that exists. For bloc-specific operations, use GetStateDir(blocName) to get the proper path.

func (*Manager) AddDependency

func (m *Manager) AddDependency(resource, dependsOn string) error

AddDependency adds a dependency between resources.

func (*Manager) AddResource

func (m *Manager) AddResource(resource *Resource) error

AddResource adds or updates a resource in the state.

func (*Manager) Clear

func (m *Manager) Clear()

Clear clears the current state from memory.

func (*Manager) Current

func (m *Manager) Current() *State

Current returns the current state.

func (*Manager) GetDependencies

func (m *Manager) GetDependencies(resource string) ([]string, error)

GetDependencies returns dependencies for a resource.

func (*Manager) GetOutput

func (m *Manager) GetOutput(key string) (interface{}, error)

GetOutput retrieves an output value.

func (*Manager) GetResource

func (m *Manager) GetResource(resourceType, resourceName string) (*Resource, error)

GetResource retrieves a resource from the state.

func (*Manager) GetResourcesByType

func (m *Manager) GetResourcesByType(resourceType string) ([]*Resource, error)

GetResourcesByType returns all resources of a specific type (alias for ListResources).

func (*Manager) ListResources

func (m *Manager) ListResources(resourceType string) ([]*Resource, error)

ListResources returns all resources of a specific type.

func (*Manager) Load

func (m *Manager) Load(blocName string) (*State, error)

Load loads state for a specific bloc.

func (*Manager) Lock

func (m *Manager) Lock(blocName string) error

Lock acquires an exclusive lock on the state.

func (*Manager) RemoveResource

func (m *Manager) RemoveResource(resourceType, resourceName string) error

RemoveResource removes a resource from the state.

func (*Manager) Save

func (m *Manager) Save() error

Save persists the current state.

func (*Manager) SaveWithBackup

func (m *Manager) SaveWithBackup() error

SaveWithBackup saves the current state with automatic backup and rollback on failure.

func (*Manager) SetOutput

func (m *Manager) SetOutput(key string, value interface{}) error

SetOutput sets an output value.

func (*Manager) Unlock

func (m *Manager) Unlock(blocName string) error

Unlock releases the lock on the state.

func (*Manager) UpdateResource

func (m *Manager) UpdateResource(resource *Resource) error

UpdateResource updates an existing resource in the state.

type MergeOptions

type MergeOptions struct {
	// Strategy determines which changes to apply
	Strategy MergeStrategy

	// PreserveDeleted keeps resources in state even if deleted from provider
	PreserveDeleted bool

	// UpdateTimestamps controls whether to update resource timestamps
	UpdateTimestamps bool
}

MergeOptions configures how resources are merged into state.

type MergeResult

type MergeResult struct {
	// ResourcesAdded is the count of new resources added to state
	ResourcesAdded int

	// ResourcesUpdated is the count of resources updated in state
	ResourcesUpdated int

	// ResourcesDeleted is the count of resources removed from state
	ResourcesDeleted int

	// ResourcesSkipped is the count of resources that weren't merged due to strategy
	ResourcesSkipped int

	// Errors contains any errors encountered during merge
	Errors []error
}

MergeResult contains the outcome of a merge operation.

func MergeResources

func MergeResources(currentState *State, diffSet *DiffSet, opts MergeOptions) (*MergeResult, error)

MergeResources applies a DiffSet to a State based on the merge strategy. This is the core state reconciliation logic that updates the state file.

type MergeStrategy

type MergeStrategy int

MergeStrategy defines how discovered resources are merged with state.

const (
	// MergeStrategyAddOnly only adds newly discovered resources.
	MergeStrategyAddOnly MergeStrategy = iota

	// MergeStrategyUpdate adds new resources and updates existing ones.
	MergeStrategyUpdate

	// MergeStrategyFull adds, updates, and removes resources no longer in provider.
	MergeStrategyFull
)

func ParseMergeStrategy

func ParseMergeStrategy(strategyStr string) (MergeStrategy, error)

ParseMergeStrategy converts a string to a MergeStrategy.

func (MergeStrategy) String

func (s MergeStrategy) String() string

String returns the string representation of a merge strategy.

type PropertyChange

type PropertyChange struct {
	// Property name that changed
	Property string

	// OldValue from state
	OldValue interface{}

	// NewValue from provider
	NewValue interface{}
}

PropertyChange represents a single property that changed.

type ReconcileOptions

type ReconcileOptions struct {
	// DryRun previews changes without modifying state
	DryRun bool

	// Strategy determines how resources are merged
	Strategy MergeStrategy

	// Force skips confirmation prompts
	Force bool
}

ReconcileOptions holds configuration for reconciliation operations.

type ReconcileResult

type ReconcileResult struct {
	// ResourcesAdded is the count of new resources added to state
	ResourcesAdded int

	// ResourcesUpdated is the count of existing resources updated
	ResourcesUpdated int

	// ResourcesRemoved is the count of resources removed from state
	ResourcesRemoved int

	// ResourcesUnchanged is the count of resources that didn't change
	ResourcesUnchanged int

	// TotalDiscovered is the total count of resources discovered from provider
	TotalDiscovered int

	// Errors encountered during reconciliation
	Errors []error

	// Duration of the reconciliation operation
	Duration time.Duration

	// DiffSet contains the detailed differences between state and discovered resources
	DiffSet *DiffSet
}

ReconcileResult contains the results of a reconciliation operation.

type Reconciler

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

Reconciler manages state reconciliation with cloud providers.

func NewReconciler

func NewReconciler(provider cpi.Provider, manager *Manager, blocName string) (*Reconciler, error)

NewReconciler creates a new state reconciler.

func (*Reconciler) Reconcile

func (r *Reconciler) Reconcile(ctx context.Context, opts ReconcileOptions) (*ReconcileResult, error)

Reconcile performs state reconciliation with the cloud provider.

This is the main orchestration method that: 1. Loads current state from the state manager 2. Discovers all resources from the cloud provider 3. Compares discovered resources with current state 4. Merges changes according to the specified strategy 5. Updates the state file (unless in dry-run mode)

Returns a ReconcileResult summarizing the operation and any errors encountered.

func (*Reconciler) ValidateProvider

func (r *Reconciler) ValidateProvider(ctx context.Context) error

ValidateProvider ensures the provider is properly initialized.

type Resource

type Resource struct {
	ID         string                 `json:"id"         yaml:"id"`
	Type       string                 `json:"type"       yaml:"type"`
	Name       string                 `json:"name"       yaml:"name"`
	Provider   string                 `json:"provider"   yaml:"provider"`
	State      string                 `json:"state"      yaml:"state"`
	Properties map[string]interface{} `json:"properties" yaml:"properties"`
	Tags       map[string]string      `json:"tags"       yaml:"tags"`
	CreatedAt  time.Time              `json:"createdAt"  yaml:"createdAt"`
	UpdatedAt  time.Time              `json:"updatedAt"  yaml:"updatedAt"`
}

Resource represents a managed resource.

type ResourceCategory

type ResourceCategory string

ResourceCategory groups resources by their category.

const (
	CategoryNetwork ResourceCategory = "network"
	CategoryCompute ResourceCategory = "compute"
	CategoryStorage ResourceCategory = "storage"
)

Resource category constants for grouping cloud resources.

type ResourceDiff

type ResourceDiff struct {
	// Type of change detected
	Type DiffType

	// ResourceType is the type of resource (network, instance, etc.)
	ResourceType string

	// ResourceID uniquely identifies the resource
	ResourceID string

	// ResourceName is the human-readable name
	ResourceName string

	// StateResource is the resource from state (nil for added resources)
	StateResource *Resource

	// DiscoveredResource is the resource from provider (nil for deleted resources)
	DiscoveredResource *Resource

	// PropertyChanges lists which properties changed (for modified resources)
	PropertyChanges []PropertyChange
}

ResourceDiff represents the difference between state and discovered resources.

type ResourceTypeInfo

type ResourceTypeInfo struct {
	Type     string
	Category ResourceCategory
	Name     string
}

ResourceTypeInfo contains metadata about a resource type.

func GetResourceTypeInfo

func GetResourceTypeInfo(resourceType string) (ResourceTypeInfo, bool)

GetResourceTypeInfo retrieves metadata for a resource type.

type State

type State struct {
	Version      string                 `json:"version"      yaml:"version"`
	BlocName     string                 `json:"blocName"     yaml:"blocName"`
	Provider     string                 `json:"provider"     yaml:"provider"`
	Region       string                 `json:"region"       yaml:"region"`
	CreatedAt    time.Time              `json:"createdAt"    yaml:"createdAt"`
	UpdatedAt    time.Time              `json:"updatedAt"    yaml:"updatedAt"`
	Resources    map[string]*Resource   `json:"resources"    yaml:"resources"`
	Outputs      map[string]interface{} `json:"outputs"      yaml:"outputs"`
	Dependencies map[string][]string    `json:"dependencies" yaml:"dependencies"`
}

State represents the current state of an OCFP environment.

Jump to

Keyboard shortcuts

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