utils

package
v0.0.0-...-cf30d46 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package utils provides shared utilities for the Wazuh Operator

Index

Constants

View Source
const DefaultRolloutTimeout = 10 * time.Minute

DefaultRolloutTimeout is the default timeout for waiting on rollouts

Variables

This section is empty.

Functions

func AddFinalizer

func AddFinalizer(obj client.Object, finalizer string)

AddFinalizer adds a finalizer to an object

func BoolPtr

func BoolPtr(b bool) *bool

BoolPtr returns a pointer to a bool

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

func CompareHashes(hash1, hash2 string) bool

CompareHashes checks if two hashes are equal

func CopyStringMap

func CopyStringMap(m map[string]string) map[string]string

CopyStringMap creates a copy of a string map

func DeepMerge

func DeepMerge(dst, src any) error

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

func EnsureAnnotations(obj metav1.Object, annotations map[string]string)

EnsureAnnotations ensures that required annotations are present on an object

func EnsureLabels

func EnsureLabels(obj metav1.Object, labels map[string]string)

EnsureLabels ensures that required labels are present on an object

func ExcludeFromStringMap

func ExcludeFromStringMap(m map[string]string, keys []string) map[string]string

ExcludeFromStringMap returns a map excluding specified keys

func FilterStringMap

func FilterStringMap(m map[string]string, keys []string) map[string]string

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

func GenerateRandomBytes(length int) ([]byte, error)

GenerateRandomBytes generates cryptographically secure random bytes

func GenerateRandomPassword

func GenerateRandomPassword(length int) (string, error)

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

func GenerateRandomString(length int) (string, error)

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

func GenerateWazuhAPIPassword(length int) (string, error)

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

func GetAnnotation(obj metav1.Object, key string) string

GetAnnotation safely gets an annotation value

func GetLabel

func GetLabel(obj metav1.Object, key string) string

GetLabel safely gets a label value

func HasFinalizer

func HasFinalizer(obj client.Object, finalizer string) bool

HasFinalizer checks if an object has a specific finalizer

func HashBytes

func HashBytes(data []byte) string

HashBytes computes a SHA256 hash of a byte slice

func HashChanged

func HashChanged(obj any, storedHash string) (bool, string, error)

HashChanged checks if the object hash has changed from the stored hash

func HashConfigData

func HashConfigData(data map[string]string) string

HashConfigData computes a hash for ConfigMap data

func HashMap

func HashMap(m map[string]string) string

HashMap computes a deterministic hash of a map

func HashObject

func HashObject(obj any) (string, error)

HashObject computes a SHA256 hash of an object's JSON representation

func HashSecretData

func HashSecretData(data map[string][]byte) string

HashSecretData computes a hash for Secret data

func HashString

func HashString(s string) string

HashString computes a SHA256 hash of a string

func HashStrings

func HashStrings(strings ...string) string

HashStrings computes a hash of multiple strings

func Int32Ptr

func Int32Ptr(i int32) *int32

Int32Ptr returns a pointer to an int32

func Int64Ptr

func Int64Ptr(i int64) *int64

Int64Ptr returns a pointer to an int64

func IsBeingDeleted

func IsBeingDeleted(obj metav1.Object) bool

IsBeingDeleted checks if an object is being deleted

func IsCRDNotInstalledError

func IsCRDNotInstalledError(err error) bool

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

func IsDeploymentImmutableError(err error) bool

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

func IsRetryableKubernetesError(err error) bool

IsRetryableKubernetesError checks if a Kubernetes API error is retryable

func IsStatefulSetImmutableError

func IsStatefulSetImmutableError(err error) bool

IsStatefulSetImmutableError returns true if the error indicates an immutable StatefulSet field update.

func MergeAnnotations

func MergeAnnotations(maps ...map[string]string) map[string]string

MergeAnnotations is an alias for MergeStringMaps for semantic clarity

func MergeLabels

func MergeLabels(maps ...map[string]string) map[string]string

MergeLabels is an alias for MergeStringMaps for semantic clarity

func MergeSlices

func MergeSlices(slices ...[]string) []string

MergeSlices merges two string slices, removing duplicates

func MergeStringMaps

func MergeStringMaps(maps ...map[string]string) map[string]string

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

func ObjectKeyString(namespace, name string) string

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

func RemoveAnnotation(obj metav1.Object, key string)

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

func RemoveFinalizer(obj client.Object, finalizer string)

RemoveFinalizer removes a finalizer from an object

func ResourceName

func ResourceName(clusterName, suffix string) string

ResourceName generates a resource name with the cluster prefix

func Retry

func Retry(ctx context.Context, fn func() error) error

Retry executes the given function with default retry configuration

func RetryOnConflict

func RetryOnConflict(ctx context.Context, fn func() error) error

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

func RetryOnConflictWithResult[T any](ctx context.Context, fn func() (T, error)) (T, error)

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

func SetAnnotation(obj metav1.Object, key, value string)

SetAnnotation safely sets an annotation value

func SetCondition

func SetCondition(conditions *[]metav1.Condition, condition metav1.Condition)

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 SetLabel

func SetLabel(obj metav1.Object, key, value string)

SetLabel safely sets a label value

func SetOwnerReference

func SetOwnerReference(owner, controlled metav1.Object, scheme *runtime.Scheme) error

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

func SetStringMapDefault(m map[string]string, key, defaultValue string)

SetStringMapDefault sets a default value in a map if the key doesn't exist

func ShortHash

func ShortHash(hash string) string

ShortHash returns a truncated hash (first 8 characters)

func ShouldRetry

func ShouldRetry(err error) bool

ShouldRetry checks if an error should be retried

func StringPtr

func StringPtr(s string) *string

StringPtr returns a pointer to a string

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

func (m *MaintenanceWindowChecker) NextWindowStart(after time.Time) (time.Time, error)

NextWindowStart returns the next maintenance window start time

func (*MaintenanceWindowChecker) TimeUntilNextWindow

func (m *MaintenanceWindowChecker) TimeUntilNextWindow(now time.Time) (time.Duration, error)

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

Jump to

Keyboard shortcuts

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