Documentation
¶
Overview ¶
Package utils provides shared utilities for the Wazuh Operator
Index ¶
- Constants
- func AddFinalizer(obj client.Object, finalizer string)
- func BoolPtr(b bool) *bool
- func CalculateBackoff(attempt int, config RetryConfig) time.Duration
- func CheckMaintenanceWindows(windows []MaintenanceWindowChecker, now time.Time) (bool, error)
- func CompareHashes(hash1, hash2 string) bool
- func CopyStringMap(m map[string]string) map[string]string
- func DeepMerge(dst, src any) error
- func EnsureAnnotations(obj metav1.Object, annotations map[string]string)
- func EnsureLabels(obj metav1.Object, labels map[string]string)
- func ExcludeFromStringMap(m map[string]string, keys []string) map[string]string
- func FilterStringMap(m map[string]string, keys []string) map[string]string
- func FindCondition(conditions []metav1.Condition, conditionType ConditionType) *metav1.Condition
- func GenerateRandomBytes(length int) ([]byte, error)
- func GenerateRandomPassword(length int) (string, error)
- func GenerateRandomString(length int) (string, error)
- func GenerateWazuhAPIPassword(length int) (string, error)
- func GetAnnotation(obj metav1.Object, key string) string
- func GetLabel(obj metav1.Object, key string) string
- func HasFinalizer(obj client.Object, finalizer string) bool
- func HashBytes(data []byte) string
- func HashChanged(obj any, storedHash string) (bool, string, error)
- func HashConfigData(data map[string]string) string
- func HashMap(m map[string]string) string
- func HashObject(obj any) (string, error)
- func HashSecretData(data map[string][]byte) string
- func HashString(s string) string
- func HashStrings(strings ...string) string
- func Int32Ptr(i int32) *int32
- func Int64Ptr(i int64) *int64
- func IsBeingDeleted(obj metav1.Object) bool
- func IsCRDNotInstalledError(err error) bool
- func IsConditionFalse(conditions []metav1.Condition, conditionType ConditionType) bool
- func IsConditionTrue(conditions []metav1.Condition, conditionType ConditionType) bool
- func IsConditionUnknown(conditions []metav1.Condition, conditionType ConditionType) bool
- func IsDeploymentImmutableError(err error) bool
- func IsRetryableKubernetesError(err error) bool
- func IsStatefulSetImmutableError(err error) bool
- func MergeAnnotations(maps ...map[string]string) map[string]string
- func MergeLabels(maps ...map[string]string) map[string]string
- func MergeSlices(slices ...[]string) []string
- func MergeStringMaps(maps ...map[string]string) map[string]string
- func NewCondition(conditionType ConditionType, status metav1.ConditionStatus, ...) metav1.Condition
- func ObjectKey(namespace, name string) types.NamespacedName
- func ObjectKeyFromObject(obj client.Object) types.NamespacedName
- func ObjectKeyString(namespace, name string) string
- func RecreateDeploymentOnError(ctx context.Context, c client.Client, recorder record.EventRecorder, ...) (bool, error)
- func RecreateStatefulSetOnError(ctx context.Context, c client.Client, recorder record.EventRecorder, ...) (bool, error)
- func RemoveAnnotation(obj metav1.Object, key string)
- func RemoveCondition(conditions *[]metav1.Condition, conditionType ConditionType)
- func RemoveFinalizer(obj client.Object, finalizer string)
- func ResourceName(clusterName, suffix string) string
- func Retry(ctx context.Context, fn func() error) error
- func RetryOnConflict(ctx context.Context, fn func() error) error
- func RetryOnConflictWithConfig(ctx context.Context, config RetryConfig, fn func() error) error
- func RetryOnConflictWithResult[T any](ctx context.Context, fn func() (T, error)) (T, error)
- func RetryOnConflictWithResultAndConfig[T any](ctx context.Context, config RetryConfig, fn func() (T, error)) (T, error)
- func RetryWithBackoff(ctx context.Context, config RetryConfig, fn func() error) error
- func RetryWithRefresh[T any](ctx context.Context, refreshFn func() (T, error), updateFn func(T) error) error
- func RetryWithResult[T any](ctx context.Context, config RetryConfig, fn func() (T, error)) (T, error)
- func SetAnnotation(obj metav1.Object, key, value string)
- func SetCondition(conditions *[]metav1.Condition, condition metav1.Condition)
- func SetDegradedCondition(conditions *[]metav1.Condition, status metav1.ConditionStatus, ...)
- func SetLabel(obj metav1.Object, key, value string)
- func SetOwnerReference(owner, controlled metav1.Object, scheme *runtime.Scheme) error
- func SetProgressingCondition(conditions *[]metav1.Condition, status metav1.ConditionStatus, ...)
- func SetReadyCondition(conditions *[]metav1.Condition, status metav1.ConditionStatus, ...)
- func SetStringMapDefault(m map[string]string, key, defaultValue string)
- func ShortHash(hash string) string
- func ShouldRetry(err error) bool
- func StringPtr(s string) *string
- type ConditionReason
- type ConditionType
- type MaintenanceWindowChecker
- type PendingRollout
- type RetryConfig
- type RetryableError
- type RolloutStatus
- type RolloutType
- type RolloutWaitResult
- type RolloutWaiter
- func (w *RolloutWaiter) CheckRolloutStatus(ctx context.Context, rollout *PendingRollout) RolloutStatus
- func (w *RolloutWaiter) IsRolloutComplete(ctx context.Context, rollout *PendingRollout) bool
- func (w *RolloutWaiter) WaitForDeploymentReadyWithResult(ctx context.Context, namespace, name string) *RolloutWaitResult
- func (w *RolloutWaiter) WaitForRollout(ctx context.Context, rollout *PendingRollout) error
- func (w *RolloutWaiter) WaitForStatefulSetReadyWithResult(ctx context.Context, namespace, name string) *RolloutWaitResult
- func (w *RolloutWaiter) WithTimeout(timeout time.Duration) *RolloutWaiter
Constants ¶
const DefaultRolloutTimeout = 10 * time.Minute
DefaultRolloutTimeout is the default timeout for waiting on rollouts
Variables ¶
This section is empty.
Functions ¶
func AddFinalizer ¶
AddFinalizer adds a finalizer to an object
func CalculateBackoff ¶
func CalculateBackoff(attempt int, config RetryConfig) time.Duration
CalculateBackoff calculates the backoff duration for a given attempt
func CheckMaintenanceWindows ¶
func CheckMaintenanceWindows(windows []MaintenanceWindowChecker, now time.Time) (bool, error)
CheckMaintenanceWindows checks multiple maintenance windows and returns true if any is active
func CompareHashes ¶
CompareHashes checks if two hashes are equal
func CopyStringMap ¶
CopyStringMap creates a copy of a string map
func DeepMerge ¶
DeepMerge performs a recursive deep merge of two objects. Both dst and src are marshaled to map[string]any, merged recursively, then the result is unmarshalled back into dst. For nested maps, keys are merged individually rather than overwritten.
func EnsureAnnotations ¶
EnsureAnnotations ensures that required annotations are present on an object
func EnsureLabels ¶
EnsureLabels ensures that required labels are present on an object
func ExcludeFromStringMap ¶
ExcludeFromStringMap returns a map excluding specified keys
func FilterStringMap ¶
FilterStringMap filters a map by keys
func FindCondition ¶
func FindCondition(conditions []metav1.Condition, conditionType ConditionType) *metav1.Condition
FindCondition finds a condition by type in a slice of conditions
func GenerateRandomBytes ¶
GenerateRandomBytes generates cryptographically secure random bytes
func GenerateRandomPassword ¶
GenerateRandomPassword generates a secure random password of the specified length. Returns an error if the length is invalid or if cryptographic random generation fails.
func GenerateRandomString ¶
GenerateRandomString generates a random alphanumeric string of the specified length. Returns an error if the length is invalid or if cryptographic random generation fails.
func GenerateWazuhAPIPassword ¶
GenerateWazuhAPIPassword generates a secure random password for Wazuh API that meets Wazuh's password policy requirements: - Minimum 8 characters - At least one lowercase letter (a-z) - At least one uppercase letter (A-Z) - At least one digit (0-9) - At least one special character Length must be at least 8, defaults to 20 if less. Returns an error if cryptographic random generation fails.
func GetAnnotation ¶
GetAnnotation safely gets an annotation value
func HasFinalizer ¶
HasFinalizer checks if an object has a specific finalizer
func HashChanged ¶
HashChanged checks if the object hash has changed from the stored hash
func HashConfigData ¶
HashConfigData computes a hash for ConfigMap data
func HashObject ¶
HashObject computes a SHA256 hash of an object's JSON representation
func HashSecretData ¶
HashSecretData computes a hash for Secret data
func HashStrings ¶
HashStrings computes a hash of multiple strings
func IsBeingDeleted ¶
IsBeingDeleted checks if an object is being deleted
func IsCRDNotInstalledError ¶
IsCRDNotInstalledError checks if the error is due to a CRD not being installed. This is useful for handling optional CRD dependencies gracefully (e.g., Gateway API, Prometheus Operator, Gateway API, etc.).
Returns true if the error indicates that the CRD/Kind is not registered in the cluster.
func IsConditionFalse ¶
func IsConditionFalse(conditions []metav1.Condition, conditionType ConditionType) bool
IsConditionFalse checks if a condition is false
func IsConditionTrue ¶
func IsConditionTrue(conditions []metav1.Condition, conditionType ConditionType) bool
IsConditionTrue checks if a condition is true
func IsConditionUnknown ¶
func IsConditionUnknown(conditions []metav1.Condition, conditionType ConditionType) bool
IsConditionUnknown checks if a condition is unknown
func IsDeploymentImmutableError ¶
IsDeploymentImmutableError returns true if the error indicates an immutable Deployment field update (specifically spec.selector which is the only truly immutable Deployment field).
func IsRetryableKubernetesError ¶
IsRetryableKubernetesError checks if a Kubernetes API error is retryable
func IsStatefulSetImmutableError ¶
IsStatefulSetImmutableError returns true if the error indicates an immutable StatefulSet field update.
func MergeAnnotations ¶
MergeAnnotations is an alias for MergeStringMaps for semantic clarity
func MergeLabels ¶
MergeLabels is an alias for MergeStringMaps for semantic clarity
func MergeSlices ¶
MergeSlices merges two string slices, removing duplicates
func MergeStringMaps ¶
MergeStringMaps merges multiple string maps, with later maps taking precedence
func NewCondition ¶
func NewCondition( conditionType ConditionType, status metav1.ConditionStatus, reason ConditionReason, message string, ) metav1.Condition
NewCondition creates a new condition
func ObjectKey ¶
func ObjectKey(namespace, name string) types.NamespacedName
ObjectKey creates a types.NamespacedName from namespace and name
func ObjectKeyFromObject ¶
func ObjectKeyFromObject(obj client.Object) types.NamespacedName
ObjectKeyFromObject creates a types.NamespacedName from a client.Object
func ObjectKeyString ¶
ObjectKeyString returns a string representation of namespace/name
func RecreateDeploymentOnError ¶
func RecreateDeploymentOnError(ctx context.Context, c client.Client, recorder record.EventRecorder, desired, existing *appsv1.Deployment, err error) (bool, error)
RecreateDeploymentOnError deletes a Deployment if the error is immutable-field related. Returns (true, nil) when the resource was deleted; the caller should requeue so the normal Get→IsNotFound→Create path re-creates it on the next reconciliation cycle.
func RecreateStatefulSetOnError ¶
func RecreateStatefulSetOnError(ctx context.Context, c client.Client, recorder record.EventRecorder, desired, existing *appsv1.StatefulSet, err error) (bool, error)
RecreateStatefulSetOnError deletes a StatefulSet if the error is immutable-field related. Returns (true, nil) when the resource was deleted; the caller should requeue so the normal Get→IsNotFound→Create path re-creates it on the next reconciliation cycle.
func RemoveAnnotation ¶
RemoveAnnotation safely removes an annotation
func RemoveCondition ¶
func RemoveCondition(conditions *[]metav1.Condition, conditionType ConditionType)
RemoveCondition removes a condition from a slice of conditions
func RemoveFinalizer ¶
RemoveFinalizer removes a finalizer from an object
func ResourceName ¶
ResourceName generates a resource name with the cluster prefix
func RetryOnConflict ¶
RetryOnConflict executes a function that may encounter optimistic locking conflicts It automatically retries on conflict errors with exponential backoff
func RetryOnConflictWithConfig ¶
func RetryOnConflictWithConfig(ctx context.Context, config RetryConfig, fn func() error) error
RetryOnConflictWithConfig executes a function with custom retry configuration
func RetryOnConflictWithResult ¶
RetryOnConflictWithResult executes a function that returns a value with conflict retry
func RetryOnConflictWithResultAndConfig ¶
func RetryOnConflictWithResultAndConfig[T any](ctx context.Context, config RetryConfig, fn func() (T, error)) (T, error)
RetryOnConflictWithResultAndConfig executes a function with custom config that returns a value
func RetryWithBackoff ¶
func RetryWithBackoff(ctx context.Context, config RetryConfig, fn func() error) error
RetryWithBackoff executes the given function with exponential backoff
func RetryWithRefresh ¶
func RetryWithRefresh[T any](ctx context.Context, refreshFn func() (T, error), updateFn func(T) error) error
RetryWithRefresh executes an update operation with automatic resource refresh on conflict The refreshFn should fetch the latest version of the resource The updateFn should apply changes and update the resource
func RetryWithResult ¶
func RetryWithResult[T any](ctx context.Context, config RetryConfig, fn func() (T, error)) (T, error)
RetryWithResult executes a function that returns a value with exponential backoff
func SetAnnotation ¶
SetAnnotation safely sets an annotation value
func SetCondition ¶
SetCondition sets a condition in a slice of conditions
func SetDegradedCondition ¶
func SetDegradedCondition(conditions *[]metav1.Condition, status metav1.ConditionStatus, reason ConditionReason, message string)
SetDegradedCondition sets the Degraded condition
func SetOwnerReference ¶
SetOwnerReference sets the owner reference on a resource
func SetProgressingCondition ¶
func SetProgressingCondition(conditions *[]metav1.Condition, status metav1.ConditionStatus, reason ConditionReason, message string)
SetProgressingCondition sets the Progressing condition
func SetReadyCondition ¶
func SetReadyCondition(conditions *[]metav1.Condition, status metav1.ConditionStatus, reason ConditionReason, message string)
SetReadyCondition sets the Ready condition
func SetStringMapDefault ¶
SetStringMapDefault sets a default value in a map if the key doesn't exist
func ShouldRetry ¶
ShouldRetry checks if an error should be retried
Types ¶
type ConditionReason ¶
type ConditionReason string
ConditionReason represents the reason for a condition
const ( // ReasonReconciling indicates reconciliation is in progress ReasonReconciling ConditionReason = "Reconciling" // ReasonSucceeded indicates the operation succeeded ReasonSucceeded ConditionReason = "Succeeded" // ReasonFailed indicates the operation failed ReasonFailed ConditionReason = "Failed" // ReasonWaiting indicates the resource is waiting for something ReasonWaiting ConditionReason = "Waiting" // ReasonDeleting indicates the resource is being deleted ReasonDeleting ConditionReason = "Deleting" // ReasonConfigurationError indicates a configuration error ReasonConfigurationError ConditionReason = "ConfigurationError" // ReasonDependencyNotReady indicates a dependency is not ready ReasonDependencyNotReady ConditionReason = "DependencyNotReady" // ReasonClusterNotHealthy indicates the cluster is not healthy ReasonClusterNotHealthy ConditionReason = "ClusterNotHealthy" // ReasonSyncError indicates a sync error with external system ReasonSyncError ConditionReason = "SyncError" )
Common condition reasons
type ConditionType ¶
type ConditionType string
ConditionType represents the type of a condition
const ( // ConditionTypeReady indicates the resource is ready ConditionTypeReady ConditionType = "Ready" // ConditionTypeProgressing indicates the resource is being reconciled ConditionTypeProgressing ConditionType = "Progressing" // ConditionTypeDegraded indicates the resource is in a degraded state ConditionTypeDegraded ConditionType = "Degraded" // ConditionTypeSynced indicates the resource is synced with external system ConditionTypeSynced ConditionType = "Synced" // ConditionTypeInitialized indicates initialization is complete ConditionTypeInitialized ConditionType = "Initialized" // ConditionTypeAvailable indicates the resource is available for use ConditionTypeAvailable ConditionType = "Available" )
Common condition types
type MaintenanceWindowChecker ¶
type MaintenanceWindowChecker struct {
// Schedule is the cron expression for window start
Schedule string
// Duration is how long the window lasts
Duration time.Duration
// Timezone for schedule evaluation
Timezone *time.Location
}
MaintenanceWindowChecker checks if operations are allowed based on maintenance windows
func NewMaintenanceWindowChecker ¶
func NewMaintenanceWindowChecker(schedule string, duration time.Duration, timezone string) (*MaintenanceWindowChecker, error)
NewMaintenanceWindowChecker creates a new maintenance window checker
func (*MaintenanceWindowChecker) IsWithinWindow ¶
func (m *MaintenanceWindowChecker) IsWithinWindow(now time.Time) (bool, error)
IsWithinWindow checks if the current time is within the maintenance window
func (*MaintenanceWindowChecker) NextWindowStart ¶
NextWindowStart returns the next maintenance window start time
func (*MaintenanceWindowChecker) TimeUntilNextWindow ¶
TimeUntilNextWindow returns the duration until the next maintenance window
type PendingRollout ¶
type PendingRollout struct {
// Name is the name of the workload
Name string
// Namespace is the namespace of the workload
Namespace string
// Type is the type of workload (StatefulSet or Deployment)
Type RolloutType
// Component is the component name (e.g., "indexer", "dashboard", "manager-master")
Component string
// Reason explains why the rollout was triggered
Reason string
// StartTime is when the rollout was initiated
StartTime time.Time
// Generation is the observed generation when the rollout was initiated
Generation int64
}
PendingRollout represents a rollout that was initiated but not yet complete
type RetryConfig ¶
type RetryConfig struct {
// MaxRetries is the maximum number of retry attempts
MaxRetries int
// InitialInterval is the initial wait time between retries
InitialInterval time.Duration
// MaxInterval is the maximum wait time between retries
MaxInterval time.Duration
// Multiplier is the factor by which the interval increases
Multiplier float64
// Jitter adds randomness to prevent thundering herd
Jitter bool
}
RetryConfig configures retry behavior
func ConflictRetryConfig ¶
func ConflictRetryConfig() RetryConfig
ConflictRetryConfig returns a retry configuration optimized for conflict errors
func DefaultRetryConfig ¶
func DefaultRetryConfig() RetryConfig
DefaultRetryConfig returns a default retry configuration
type RetryableError ¶
type RetryableError interface {
IsRetryable() bool
}
IsRetryable checks if an error is retryable
type RolloutStatus ¶
type RolloutStatus struct {
// Complete indicates if the rollout is complete (alias for Ready for backwards compat)
Complete bool
// Ready indicates if the rollout is complete and all pods are ready
Ready bool
// ReadyReplicas is the number of ready replicas
ReadyReplicas int32
// Desired is the desired number of replicas
Desired int32
// Updated is the number of updated replicas
Updated int32
// Duration is how long the rollout has been in progress
Duration time.Duration
// Message provides a human-readable status message
Message string
// Error if any occurred checking the status
Error error
}
RolloutStatus represents the current status of a rollout
type RolloutType ¶
type RolloutType string
RolloutType represents the type of Kubernetes workload being rolled out
const ( // RolloutTypeStatefulSet represents a StatefulSet rollout RolloutTypeStatefulSet RolloutType = "StatefulSet" // RolloutTypeDeployment represents a Deployment rollout RolloutTypeDeployment RolloutType = "Deployment" )
type RolloutWaitResult ¶
type RolloutWaitResult struct {
// Success indicates if the rollout completed successfully
Success bool
// TimedOut indicates if the wait timed out
TimedOut bool
// Error if any occurred during the wait
Error error
// Duration is how long we waited
Duration time.Duration
// FinalStatus is the final status of the rollout
FinalStatus RolloutStatus
}
RolloutWaitResult contains the result of waiting for a rollout
type RolloutWaiter ¶
type RolloutWaiter struct {
// contains filtered or unexported fields
}
RolloutWaiter provides methods for waiting on Kubernetes rollouts
func NewRolloutWaiter ¶
func NewRolloutWaiter(c client.Client) *RolloutWaiter
NewRolloutWaiter creates a new RolloutWaiter with the default timeout
func (*RolloutWaiter) CheckRolloutStatus ¶
func (w *RolloutWaiter) CheckRolloutStatus(ctx context.Context, rollout *PendingRollout) RolloutStatus
CheckRolloutStatus checks the status of a pending rollout
func (*RolloutWaiter) IsRolloutComplete ¶
func (w *RolloutWaiter) IsRolloutComplete(ctx context.Context, rollout *PendingRollout) bool
IsRolloutComplete checks if a pending rollout is complete
func (*RolloutWaiter) WaitForDeploymentReadyWithResult ¶
func (w *RolloutWaiter) WaitForDeploymentReadyWithResult(ctx context.Context, namespace, name string) *RolloutWaitResult
WaitForDeploymentReadyWithResult waits for a Deployment rollout and returns detailed result
func (*RolloutWaiter) WaitForRollout ¶
func (w *RolloutWaiter) WaitForRollout(ctx context.Context, rollout *PendingRollout) error
WaitForRollout waits for a rollout to complete
func (*RolloutWaiter) WaitForStatefulSetReadyWithResult ¶
func (w *RolloutWaiter) WaitForStatefulSetReadyWithResult(ctx context.Context, namespace, name string) *RolloutWaitResult
WaitForStatefulSetReadyWithResult waits for a StatefulSet rollout and returns detailed result
func (*RolloutWaiter) WithTimeout ¶
func (w *RolloutWaiter) WithTimeout(timeout time.Duration) *RolloutWaiter
WithTimeout sets a custom timeout for the waiter