Documentation
¶
Overview ¶
Package state manages OCFP bloc state persistence, backup, reconciliation, and resource tracking.
Index ¶
- Constants
- Variables
- func ErrOutputNotFound(key string) error
- func ErrResourceNotFound(key string) error
- func ErrStateIsLockedBy(owner, createdAt interface{}) error
- func GetResourcesByCategory(category ResourceCategory) []string
- func GetStateDir(blocName string) (string, error)
- func UpdateResourceFromDiscovered(stateRes *Resource, discoveredRes *Resource)
- type BackupInfo
- type DiffSet
- type DiffType
- type Manager
- func (m *Manager) AddDependency(resource, dependsOn string) error
- func (m *Manager) AddResource(resource *Resource) error
- func (m *Manager) Clear()
- func (m *Manager) Current() *State
- func (m *Manager) GetDependencies(resource string) ([]string, error)
- func (m *Manager) GetOutput(key string) (interface{}, error)
- func (m *Manager) GetResource(resourceType, resourceName string) (*Resource, error)
- func (m *Manager) GetResourcesByType(resourceType string) ([]*Resource, error)
- func (m *Manager) ListResources(resourceType string) ([]*Resource, error)
- func (m *Manager) Load(blocName string) (*State, error)
- func (m *Manager) Lock(blocName string) error
- func (m *Manager) RemoveResource(resourceType, resourceName string) error
- func (m *Manager) Save() error
- func (m *Manager) SaveWithBackup() error
- func (m *Manager) SetOutput(key string, value interface{}) error
- func (m *Manager) Unlock(blocName string) error
- func (m *Manager) UpdateResource(resource *Resource) error
- type MergeOptions
- type MergeResult
- type MergeStrategy
- type PropertyChange
- type ReconcileOptions
- type ReconcileResult
- type Reconciler
- type Resource
- type ResourceCategory
- type ResourceDiff
- type ResourceTypeInfo
- type State
Constants ¶
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 ¶
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 ¶
ErrOutputNotFound returns an error indicating the specified output key was not found in state.
func ErrResourceNotFound ¶
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 ¶
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 ¶
UpdateResourceFromDiscovered updates a state resource with discovered resource data.
Types ¶
type BackupInfo ¶
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 ¶
HasChanges returns true if there are any additions, modifications, or deletions.
func (*DiffSet) TotalChanges ¶
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 ¶
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 PreviewManager ¶ added in v0.5.7
PreviewManager is the read-only form of NewManager, for a caller that must not write, such as a dry run. It returns the error that NewManager would return for stateDir, and otherwise a manager for it, but it never creates the directory. A directory that NewManager would create counts as present, and Load reads it as empty. It checks what MkdirAll checks before it creates anything, which is that no part of the path is a file. It leaves to the real run what only creating the directory checks, such as permission to write its parent.
func (*Manager) AddDependency ¶
AddDependency adds a dependency between resources.
func (*Manager) AddResource ¶
AddResource adds or updates a resource in the state.
func (*Manager) GetDependencies ¶
GetDependencies returns dependencies for a resource.
func (*Manager) GetResource ¶
GetResource retrieves a resource from the state.
func (*Manager) GetResourcesByType ¶
GetResourcesByType returns all resources of a specific type (alias for ListResources).
func (*Manager) ListResources ¶
ListResources returns all resources of a specific type.
func (*Manager) RemoveResource ¶
RemoveResource removes a resource from the state.
func (*Manager) SaveWithBackup ¶
SaveWithBackup saves the current state with automatic backup and rollback on failure.
func (*Manager) UpdateResource ¶
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 ¶
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.