Documentation
¶
Overview ¶
Package utils contains otherwise uncategorized kubernetes relative functions
Index ¶
- Constants
- Variables
- func AddFencedInstance(instanceName string, object metav1.Object) (bool, error)
- func AnnotateAppArmor(object *metav1.ObjectMeta, spec *corev1.PodSpec, annotations map[string]string)
- func CollectDifferencesFromMaps(p1 map[string]string, p2 map[string]string) map[string][]string
- func CountReadyPods(podList []corev1.Pod) int
- func DetectAvailableArchitectures() error
- func DetectOLM(client discovery.DiscoveryInterface) (err error)
- func DetectSecurityContextConstraints(client discovery.DiscoveryInterface) (err error)
- func DetectVolumeSnapshotExist(client discovery.DiscoveryInterface) (err error)
- func ExecCommand(ctx context.Context, client kubernetes.Interface, config *rest.Config, ...) (string, string, error)
- func FilterActivePods(pods []corev1.Pod) []corev1.Pod
- func FilterJobsWithOneCompletion(jobList []batchv1.Job) []batchv1.Job
- func GetClusterSerialValue(annotations map[string]string) (int, error)
- func GetDiscoveryClient() (*discovery.DiscoveryClient, error)
- func GetFencedInstances(annotations map[string]string) (*stringset.Data, error)
- func GetInstanceRole(labels map[string]string) (string, bool)
- func HaveSecurityContextConstraints() bool
- func HaveVolumeSnapshot() bool
- func InheritAnnotations(object *metav1.ObjectMeta, annotations map[string]string, ...)
- func InheritLabels(object *metav1.ObjectMeta, labels map[string]string, ...)
- func IsAnnotationAppArmorPresent(spec *corev1.PodSpec, annotations map[string]string) bool
- func IsAnnotationAppArmorPresentInObject(object *metav1.ObjectMeta, spec *corev1.PodSpec, annotations map[string]string) bool
- func IsAnnotationSubset(mapSet, clusterAnnotations, fixedInheritedAnnotations map[string]string, ...) bool
- func IsConditionReasonValid(conditionReason string) bool
- func IsEmptyWalArchiveCheckEnabled(object *metav1.ObjectMeta) bool
- func IsLabelSubset(mapSet, clusterLabels, fixedInheritedLabels map[string]string, ...) bool
- func IsMapSubset(mapSet map[string]string, mapSubset map[string]string) bool
- func IsPodActive(p corev1.Pod) bool
- func IsPodAlive(p corev1.Pod) bool
- func IsPodReady(pod corev1.Pod) bool
- func IsPodSpecReconciliationDisabled(object *metav1.ObjectMeta) bool
- func IsPodUnschedulable(p *corev1.Pod) bool
- func IsPowerOfTwo(n int) bool
- func IsReconciliationDisabled(object *metav1.ObjectMeta) bool
- func IsWalArchivingDisabled(object *metav1.ObjectMeta) bool
- func JobHasOneCompletion(job batchv1.Job) bool
- func LabelClusterName(object *metav1.ObjectMeta, name string)
- func MergeObjectsMetadata(receiver client.Object, giver client.Object)
- func PodHasContainerStatuses(pod corev1.Pod) bool
- func PodMonitorExist(client discovery.DiscoveryInterface) (bool, error)
- func RunningOnOLM() bool
- func SetAsOwnedBy(controlled *metav1.ObjectMeta, controller metav1.ObjectMeta, ...)
- func SetInstanceRole(meta *metav1.ObjectMeta, role string)
- func SetOperatorVersion(object *metav1.ObjectMeta, version string)
- func SetVolumeSnapshot(value bool)
- func ToBytes[T anyNumber](mb T) float64
- type AvailableArchitecture
- type ErrInvalidPromotionToken
- type FencingMetadataExecutor
- func (fb *FencingMetadataExecutor) AddFencing() *FencingMetadataExecutor
- func (fb *FencingMetadataExecutor) Execute(ctx context.Context, key types.NamespacedName, obj client.Object) error
- func (fb *FencingMetadataExecutor) ForAllInstances() *FencingMetadataExecutor
- func (fb *FencingMetadataExecutor) ForInstance(instanceNames ...string) *FencingMetadataExecutor
- func (fb *FencingMetadataExecutor) RemoveFencing() *FencingMetadataExecutor
- type HibernationAnnotationValue
- type InheritanceController
- type PVCRole
- type PgControlData
- func (p PgControlData) CreatePromotionToken() (string, error)
- func (p PgControlData) GetBytesPerWALSegment() (int, error)
- func (p PgControlData) GetDataPageChecksumVersion() (string, error)
- func (p PgControlData) GetDatabaseClusterState() string
- func (p PgControlData) GetDatabaseSystemIdentifier() string
- func (p PgControlData) GetLatestCheckpointREDOLocation() string
- func (p PgControlData) GetLatestCheckpointTimelineID() string
- func (p PgControlData) GetREDOWALFile() string
- func (p PgControlData) GetTimeOfLatestCheckpoint() string
- func (p PgControlData) TryGetLatestCheckpointTimelineID() (string, bool)
- func (p PgControlData) TryGetREDOWALFile() (string, bool)
- type PgControldataTokenContent
- type PgDataState
- type PodRole
- type UserType
Constants ¶
const ( // DatabaseFinalizerName is the name of the finalizer // triggering the deletion of the database DatabaseFinalizerName = MetadataNamespace + "/deleteDatabase" // PublicationFinalizerName is the name of the finalizer // triggering the deletion of the publication PublicationFinalizerName = MetadataNamespace + "/deletePublication" // SubscriptionFinalizerName is the name of the finalizer // triggering the deletion of the subscription SubscriptionFinalizerName = MetadataNamespace + "/deleteSubscription" // PluginFinalizerName is the name of the finalizer // triggering the cleanup of a plugin when its service is deleted PluginFinalizerName = MetadataNamespace + "/cleanupPlugin" )
const ( // ManagerName is the name of the manager for cnpg controlled objects ManagerName = "cloudnative-pg" // AppName is the name of the application AppName = "postgresql" // DatabaseComponentName is the name of the component for the database. DatabaseComponentName = "database" // PoolerComponentName is the name of the component for the pooler. PoolerComponentName = "pooler" )
const ( // KubernetesAppManagedByLabelName is the name of the label applied to all managed objects KubernetesAppManagedByLabelName = KubernetesAppNamespaceDomain + "/managed-by" // KubernetesAppLabelName is the name of the label used to indicate the name of the application KubernetesAppLabelName = KubernetesAppNamespaceDomain + "/name" // KubernetesAppInstanceLabelName is the name of the label used to indicate the unique instance of this application KubernetesAppInstanceLabelName = KubernetesAppNamespaceDomain + "/instance" // KubernetesAppVersionLabelName is the name of the label used to indicate the version postgres KubernetesAppVersionLabelName = KubernetesAppNamespaceDomain + "/version" // KubernetesAppComponentLabelName is the name of the label used to indicate the component within the architecture KubernetesAppComponentLabelName = KubernetesAppNamespaceDomain + "/component" )
const ( // ClusterLabelName is the name of the label cluster which the backup CR belongs to ClusterLabelName = MetadataNamespace + "/cluster" // JobRoleLabelName is the name of the label containing the purpose of the executed job // the value could be import, initdb, join JobRoleLabelName = MetadataNamespace + "/jobRole" // PvcRoleLabelName is the name of the label containing the purpose of the pvc PvcRoleLabelName = MetadataNamespace + "/pvcRole" // TablespaceNameLabelName is the name of the label containing tablespace name that a pvc holds TablespaceNameLabelName = "cnpg.io/tablespaceName" // PodRoleLabelName is the name of the label containing the podRole value PodRoleLabelName = MetadataNamespace + "/podRole" // InstanceNameLabelName is the name of the label containing the instance name InstanceNameLabelName = MetadataNamespace + "/instanceName" // BackupNameLabelName is the name of the label containing the backup id, available on backup resources BackupNameLabelName = MetadataNamespace + "/backupName" // MajorVersionLabelName is the Postgres major version contained in a snapshot backup MajorVersionLabelName = MetadataNamespace + "/majorVersion" // PgbouncerNameLabel is the name of the label of containing the pooler name PgbouncerNameLabel = MetadataNamespace + "/poolerName" // ClusterRoleLabelName is the name of label applied to instances to mark primary/replica // // Deprecated: Use ClusterInstanceRoleLabelName. ClusterRoleLabelName = "role" // ClusterInstanceRoleLabelName is the name of label applied to instances to mark primary/replica ClusterInstanceRoleLabelName = MetadataNamespace + "/instanceRole" // ImmediateBackupLabelName is the name of the label applied to backups to tell if the first scheduled backup is // taken immediately or not ImmediateBackupLabelName = MetadataNamespace + "/immediateBackup" // ParentScheduledBackupLabelName is the name of the label applied to backups to easily tell the name of parent // scheduled backup if a backup is created by a scheduled backup ParentScheduledBackupLabelName = MetadataNamespace + "/scheduled-backup" // WatchedLabelName the name of the label which tells if a resource change will be automatically reloaded by instance // or not, use for Secrets or ConfigMaps WatchedLabelName = MetadataNamespace + "/reload" // UserTypeLabelName the name of the label which tells if a Secret refers // to a superuser database role or an application one UserTypeLabelName = MetadataNamespace + "/userType" // BackupTimelineLabelName is the name or the label where the timeline of a backup is kept BackupTimelineLabelName = MetadataNamespace + "/backupTimeline" // BackupYearLabelName is the name of the label where the year of a backup is kept BackupYearLabelName = MetadataNamespace + "/backupYear" // BackupMonthLabelName is the name of the label where the month of a backup is kept BackupMonthLabelName = MetadataNamespace + "/backupMonth" // BackupDateLabelName is the name of the label where the date of a backup in 'YYYYMMDD' format is kept BackupDateLabelName = MetadataNamespace + "/backupDate" // IsOnlineBackupLabelName is the name of the label used to specify whether a backup was online IsOnlineBackupLabelName = MetadataNamespace + "/onlineBackup" // IsManagedLabelName is the name of the label used to indicate a '.spec.managed' resource IsManagedLabelName = MetadataNamespace + "/isManaged" // PluginNameLabelName is the name of the label to be applied to services // to have them detected as CNPG-i plugins PluginNameLabelName = MetadataNamespace + "/pluginName" // LivenessPingerAnnotationName is the name of the pinger configuration LivenessPingerAnnotationName = AlphaMetadataNamespace + "/livenessPinger" )
When you add a new label or annotation, please make sure that you also update the publicly visible documentation, namely the `docs/src/labels_annotations.md` file
const ( // OperatorVersionAnnotationName is the name of the annotation containing // the version of the operator that generated a certain object OperatorVersionAnnotationName = MetadataNamespace + "/operatorVersion" // AppArmorAnnotationPrefix will be the name of the AppArmor profile to apply // This is required for Azure but can be set in other environments AppArmorAnnotationPrefix = "container.apparmor.security.beta.kubernetes.io" // ReconciliationLoopAnnotationName is the name of the annotation controlling // the status of the reconciliation loop for the cluster ReconciliationLoopAnnotationName = MetadataNamespace + "/reconciliationLoop" // ReconcilePodSpecAnnotationName is the name of the annotation that prevents the pod spec to be reconciled ReconcilePodSpecAnnotationName = MetadataNamespace + "/reconcilePodSpec" // HibernateClusterManifestAnnotationName contains the hibernated cluster manifest // Deprecated. Replaced by: ClusterManifestAnnotationName. This annotation is // kept for backward compatibility HibernateClusterManifestAnnotationName = MetadataNamespace + "/hibernateClusterManifest" // HibernatePgControlDataAnnotationName contains the pg_controldata output of the hibernated cluster // Deprecated. Replaced by: PgControldataAnnotationName. This annotation is // kept for backward compatibility HibernatePgControlDataAnnotationName = MetadataNamespace + "/hibernatePgControlData" // PodEnvHashAnnotationName is the name of the annotation containing the podEnvHash value // // Deprecated: the PodSpec annotation covers the environment drift. This annotation is // kept for backward compatibility PodEnvHashAnnotationName = MetadataNamespace + "/podEnvHash" // PodSpecAnnotationName is the name of the annotation with the PodSpec derived from the cluster PodSpecAnnotationName = MetadataNamespace + "/podSpec" // ClusterManifestAnnotationName is the name of the annotation containing the cluster manifest ClusterManifestAnnotationName = MetadataNamespace + "/clusterManifest" // CoredumpFilter stores the value defined by the user to set in /proc/self/coredump_filter CoredumpFilter = MetadataNamespace + "/coredumpFilter" // PgControldataAnnotationName is the name of the annotation containing the pg_controldata output of the cluster PgControldataAnnotationName = MetadataNamespace + "/pgControldata" // SkipWalArchiving is the name of the annotation which turns off WAL archiving SkipWalArchiving = MetadataNamespace + "/skipWalArchiving" // ClusterSerialAnnotationName is the name of the annotation containing the // serial number of the node ClusterSerialAnnotationName = MetadataNamespace + "/nodeSerial" // ClusterReloadAnnotationName is the name of the annotation containing the // latest reload time trigger by external ClusterReloadAnnotationName = MetadataNamespace + "/reloadedAt" // PVCStatusAnnotationName is the name of the annotation that shows the current status of the PVC. // The status can be "initializing", "ready" or "detached" PVCStatusAnnotationName = MetadataNamespace + "/pvcStatus" // LegacyBackupAnnotationName is the name of the annotation represents whether taking a backup without passing // the name argument even on barman version 3.3.0+. The value can be "true" or "false" LegacyBackupAnnotationName = MetadataNamespace + "/forceLegacyBackup" // HibernationAnnotationName is the name of the annotation which used to declaratively hibernate a // PostgreSQL cluster HibernationAnnotationName = MetadataNamespace + "/hibernation" // PoolerSpecHashAnnotationName is the name of the annotation added to the deployment to tell // the hash of the Pooler Specification PoolerSpecHashAnnotationName = MetadataNamespace + "/poolerSpecHash" // OperatorManagedSecretsAnnotationName is the name of the annotation containing // the secrets managed by the operator inside the generated service account OperatorManagedSecretsAnnotationName = MetadataNamespace + "/managedSecrets" // FencedInstanceAnnotation is the annotation to be used for fencing instances, the value should be a // JSON list of all the instances we want to be fenced, e.g. `["cluster-example-1","cluster-example-2`"]. // If the list contain the "*" element, every node is fenced. FencedInstanceAnnotation = MetadataNamespace + "/fencedInstances" // CNPGHashAnnotationName is the name of the annotation containing the hash of the resource used by operator // expect the pooler that uses PoolerSpecHashAnnotationName CNPGHashAnnotationName = MetadataNamespace + "/hash" // BackupStartWALAnnotationName is the name of the annotation where a backup's start WAL is kept BackupStartWALAnnotationName = MetadataNamespace + "/backupStartWAL" // BackupEndWALAnnotationName is the name of the annotation where a backup's end WAL is kept BackupEndWALAnnotationName = MetadataNamespace + "/backupEndWAL" // BackupStartTimeAnnotationName is the name of the annotation where a backup's start time is kept BackupStartTimeAnnotationName = MetadataNamespace + "/backupStartTime" // BackupEndTimeAnnotationName is the name of the annotation where a backup's end time is kept BackupEndTimeAnnotationName = MetadataNamespace + "/backupEndTime" // BackupLabelFileAnnotationName is the name of the annotation where the `backup_label` file is kept BackupLabelFileAnnotationName = MetadataNamespace + "/backupLabelFile" // BackupTablespaceMapFileAnnotationName is the name of the annotation where the `tablespace_map` file is kept BackupTablespaceMapFileAnnotationName = MetadataNamespace + "/backupTablespaceMapFile" // BackupVolumeSnapshotDeadlineAnnotationName is the annotation for the snapshot backup failure deadline in minutes. // It is only applied to snapshot retryable errors BackupVolumeSnapshotDeadlineAnnotationName = MetadataNamespace + "/volumeSnapshotDeadline" // SnapshotStartTimeAnnotationName is the name of the annotation where a snapshot's start time is kept SnapshotStartTimeAnnotationName = MetadataNamespace + "/snapshotStartTime" // SnapshotEndTimeAnnotationName is the name of the annotation where a snapshot's end time is kept SnapshotEndTimeAnnotationName = MetadataNamespace + "/snapshotEndTime" // ClusterRestartAnnotationName is the name of the annotation containing the // latest required restart time ClusterRestartAnnotationName = "kubectl.kubernetes.io/restartedAt" // UpdateStrategyAnnotation is the name of the annotation used to indicate how to update the given resource UpdateStrategyAnnotation = MetadataNamespace + "/updateStrategy" // LastAppliedSpecAnnotationName is the name of the annotation containing // the last applied spec, used for three-way merge during reconciliation // to detect intentional field removals LastAppliedSpecAnnotationName = MetadataNamespace + "/lastAppliedSpec" // PluginClientSecretAnnotationName is the name of the annotation containing // the secret containing the TLS credentials that the operator should use to // connect to the plugin PluginClientSecretAnnotationName = MetadataNamespace + "/pluginClientSecret" // PluginServerSecretAnnotationName is the name of the annotation containing // the secret containing the TLS credentials that are used by the plugin // server to authenticate PluginServerSecretAnnotationName = MetadataNamespace + "/pluginServerSecret" // PluginPortAnnotationName is the name of the annotation containing the // port the plugin is listening to PluginPortAnnotationName = MetadataNamespace + "/pluginPort" // PluginServerNameAnnotationName is the name of the annotation containing the // server name to use for TLS verification when connecting to the plugin. // If not specified, defaults to the service name PluginServerNameAnnotationName = MetadataNamespace + "/pluginServerName" // PodPatchAnnotationName is the name of the annotation containing the // patch to apply to the pod PodPatchAnnotationName = MetadataNamespace + "/podPatch" // WebhookValidationAnnotationName is the name of the annotation describing if // the validation webhook should be enabled or disabled WebhookValidationAnnotationName = MetadataNamespace + "/validation" // FailoverQuorumAnnotationName is the name of the annotation that allows the // user to enable synchronous quorum failover protection. // // This feature enables quorum-based check before failover, ensuring // no data loss at the expense of availability. FailoverQuorumAnnotationName = AlphaMetadataNamespace + "/failoverQuorum" // EnableInstancePprofAnnotationName is the name of the annotation describing if the instances generated by // the cluster should enable the pprof server. Accepts "true" | "false" values. EnableInstancePprofAnnotationName = AlphaMetadataNamespace + "/enableInstancePprof" // UnrecoverableInstanceAnnotationName is the name of the annotation telling the // operator if a instance is recoverable or not. Not recoverable instances will // be deleted with the contents of their PVCs. UnrecoverableInstanceAnnotationName = AlphaMetadataNamespace + "/unrecoverable" )
const AlphaMetadataNamespace = "alpha.cnpg.io"
AlphaMetadataNamespace is the annotation and label namespace used by the alpha features of the operator
const ( // FenceAllInstances is the wildcard that, if put inside the fenced instances list, will fence every // CNPG instance FenceAllInstances = "*" )
const KubernetesAppNamespaceDomain = "app.kubernetes.io"
KubernetesAppNamespaceDomain is the domain used for the official kubernetes app labels
const MetadataNamespace = "cnpg.io"
MetadataNamespace is the annotation and label namespace used by the operator
Variables ¶
var ( // ErrorFencedInstancesSyntax is emitted when the fencedInstances annotation // have an invalid syntax ErrorFencedInstancesSyntax = errors.New("fencedInstances annotation has invalid syntax") // ErrorSingleInstanceUnfencing is emitted when unfencing a single instance // while all the cluster is fenced ErrorSingleInstanceUnfencing = errors.New("unfencing an instance while the whole cluster is fenced is not supported") )
var ( // ErrEmptyLatestCheckpointTimelineID is raised when the relative field // in the promotion token is empty ErrEmptyLatestCheckpointTimelineID = &ErrInvalidPromotionToken{ err: nil, reason: "LatestCheckpointTimelineID is empty", } // ErrEmptyREDOWALFile is raised when the relative field // in the promotion token is empty ErrEmptyREDOWALFile = &ErrInvalidPromotionToken{ err: nil, reason: "REDOWALFile is empty", } // ErrEmptyDatabaseSystemIdentifier is raised when the relative field // in the promotion token is empty ErrEmptyDatabaseSystemIdentifier = &ErrInvalidPromotionToken{ err: nil, reason: "DatabaseSystemIdentifier is empty", } // ErrEmptyLatestCheckpointREDOLocation is raised when the relative field // in the promotion token is empty ErrEmptyLatestCheckpointREDOLocation = &ErrInvalidPromotionToken{ err: nil, reason: "LatestCheckpointREDOLocation is empty", } // ErrEmptyTimeOfLatestCheckpoint is raised when the relative field // in the promotion token is empty ErrEmptyTimeOfLatestCheckpoint = &ErrInvalidPromotionToken{ err: nil, reason: "TimeOfLatestCheckpoint is empty", } // ErrEmptyOperatorVersion is raised when the relative field // in the promotion token is empty ErrEmptyOperatorVersion = &ErrInvalidPromotionToken{ err: nil, reason: "OperatorVersion is empty", } )
var ErrNextLoop = errors.New("stop this loop and return the associated Result object")
ErrNextLoop is not a real error. It forces the current reconciliation loop to stop and return the associated Result object
var ErrTerminateLoop = errors.New("stop this loop and do not requeue")
ErrTerminateLoop is not a real error. It forces the current reconciliation loop to stop
var ErrorContainerNotFound = fmt.Errorf("container not found")
ErrorContainerNotFound is raised when an Exec call is invoked against a non existing container
Functions ¶
func AddFencedInstance ¶
AddFencedInstance adds the given server name to the FencedInstanceAnnotation annotation returns an error if the instance was already fenced
func AnnotateAppArmor ¶
func AnnotateAppArmor(object *metav1.ObjectMeta, spec *corev1.PodSpec, annotations map[string]string)
AnnotateAppArmor adds an annotation to the pod
func CollectDifferencesFromMaps ¶
CollectDifferencesFromMaps returns a map of the differences (as slice of strings) of the values of two given maps. Map result values are added when a key is present just in one of the input maps, or if the values are different given the same key
func CountReadyPods ¶
CountReadyPods counts the number of Pods which are ready
func DetectAvailableArchitectures ¶ added in v1.21.4
func DetectAvailableArchitectures() error
DetectAvailableArchitectures detects the architectures available in the cluster
func DetectOLM ¶ added in v1.22.5
func DetectOLM(client discovery.DiscoveryInterface) (err error)
DetectOLM looks for the operators.coreos.com operators resource in the current Kubernetes cluster
func DetectSecurityContextConstraints ¶
func DetectSecurityContextConstraints(client discovery.DiscoveryInterface) (err error)
DetectSecurityContextConstraints connects to the discovery API and find out if we're running under a system that implements OpenShift Security Context Constraints
func DetectVolumeSnapshotExist ¶ added in v1.21.0
func DetectVolumeSnapshotExist(client discovery.DiscoveryInterface) (err error)
DetectVolumeSnapshotExist connects to the discovery API and find out if the VolumeSnapshot CRD exist in the cluster
func ExecCommand ¶
func ExecCommand( ctx context.Context, client kubernetes.Interface, config *rest.Config, pod corev1.Pod, containerName string, timeout *time.Duration, command ...string, ) (string, string, error)
ExecCommand executes a command inside the pod, automatically retrying transient errors like proxy failures or network issues.
func FilterActivePods ¶
FilterActivePods returns pods that have not terminated.
func FilterJobsWithOneCompletion ¶ added in v1.17.4
FilterJobsWithOneCompletion returns jobs that have one completion
func GetClusterSerialValue ¶ added in v1.25.2
GetClusterSerialValue returns the `nodeSerial` value from the given annotation map or return an error
func GetDiscoveryClient ¶
func GetDiscoveryClient() (*discovery.DiscoveryClient, error)
GetDiscoveryClient creates a discovery client or return error
func GetFencedInstances ¶
GetFencedInstances gets the set of fenced servers from the annotations
func GetInstanceRole ¶ added in v1.19.5
GetInstanceRole tries to fetch the ClusterRoleLabelName andClusterInstanceRoleLabelName value from a given labels map
func HaveSecurityContextConstraints ¶
func HaveSecurityContextConstraints() bool
HaveSecurityContextConstraints returns true if we're running under a system that implements OpenShift Security Context Constraints It panics if called before DetectSecurityContextConstraints
func HaveVolumeSnapshot ¶ added in v1.21.0
func HaveVolumeSnapshot() bool
HaveVolumeSnapshot returns true if we're running under a system that implements having the VolumeSnapshot CRD
func InheritAnnotations ¶
func InheritAnnotations( object *metav1.ObjectMeta, annotations map[string]string, fixedAnnotations map[string]string, controller InheritanceController, )
InheritAnnotations puts into the object metadata the passed annotations if the annotations are supposed to be inherited. The passed configuration is used to determine whenever a certain annotation is inherited or not
func InheritLabels ¶
func InheritLabels( object *metav1.ObjectMeta, labels map[string]string, fixedLabels map[string]string, controller InheritanceController, )
InheritLabels puts into the object metadata the passed labels if the labels are supposed to be inherited. The passed configuration is used to determine whenever a certain label is inherited or not
func IsAnnotationAppArmorPresent ¶
IsAnnotationAppArmorPresent checks if one of the annotations is an AppArmor annotation
func IsAnnotationAppArmorPresentInObject ¶
func IsAnnotationAppArmorPresentInObject( object *metav1.ObjectMeta, spec *corev1.PodSpec, annotations map[string]string, ) bool
IsAnnotationAppArmorPresentInObject checks if the AppArmor annotations are present or not in the given Object
func IsAnnotationSubset ¶
func IsAnnotationSubset( mapSet, clusterAnnotations, fixedInheritedAnnotations map[string]string, controller InheritanceController, ) bool
IsAnnotationSubset checks if a collection of annotations is a subset of another
NOTE: there are two parameters for the annotations to check. The `fixed` one is for annotations that certainly should be inherited (`inheritedMetadata` in the spec) The other annotations may or may not be inherited depending on the configuration
func IsConditionReasonValid ¶ added in v1.15.5
IsConditionReasonValid checks if a certain condition reason is valid or not given the Kubernetes API requirements
func IsEmptyWalArchiveCheckEnabled ¶ added in v1.16.4
func IsEmptyWalArchiveCheckEnabled(object *metav1.ObjectMeta) bool
IsEmptyWalArchiveCheckEnabled returns a boolean indicating if we should run the logic that checks if the WAL archive storage is empty
func IsLabelSubset ¶
func IsLabelSubset( mapSet, clusterLabels, fixedInheritedLabels map[string]string, controller InheritanceController, ) bool
IsLabelSubset checks if a collection of labels is a subset of another
NOTE: there are two parameters for the labels to check. The `fixed` one is for labels that certainly should be inherited (`inheritedMetadata` in the spec) The other labels may or may not be inherited depending on the configuration
func IsMapSubset ¶ added in v1.19.5
IsMapSubset returns true if mapSubset is a subset of mapSet otherwise false
func IsPodActive ¶
IsPodActive checks if a pod is active, copied from: https://github.com/kubernetes/kubernetes/blob/1bd0077/test/e2e/framework/pod/resource.go#L664
func IsPodAlive ¶
IsPodAlive check if a pod is active and not crash-looping
func IsPodReady ¶
IsPodReady reports whether the Pod has its PodReady condition set to True.
The PodReady condition is kept up-to-date by two independent control-plane actors:
- the kubelet on the pod's node, while the node is healthy: the transition from True to False happens within FailureThreshold consecutive probe periods of the underlying container becoming unhealthy (about 30s with stock defaults: PeriodSeconds=10, FailureThreshold=3, unless the user overrides them via `.spec.probes.readiness`).
- the node lifecycle controller when the node stops reporting to the API server; once the node transitions to `Unknown` (after `--node-monitor-grace-period`, 40s by default on Kubernetes 1.29-1.31 and 50s on 1.32+) the controller calls `MarkPodsNotReady`, which flips PodReady to False on every pod of that node. With stock defaults the operator observes the flip about 40 to 55 seconds after the node becomes unreachable.
Note that `tolerationSeconds` on the `node.kubernetes.io/unreachable` taint (300s by default) controls pod eviction, not this condition: PodReady has already flipped to False well before eviction happens.
This helper is the source of truth for "is this pod serviceable right now?" across the operator: failover election, backup target selection, failover-quorum reachability, offline volume-snapshot fencing, and user-visible cluster health classification.
func IsPodSpecReconciliationDisabled ¶ added in v1.22.5
func IsPodSpecReconciliationDisabled(object *metav1.ObjectMeta) bool
IsPodSpecReconciliationDisabled checks if the pod spec reconciliation is disabled
func IsPodUnschedulable ¶ added in v1.22.5
IsPodUnschedulable check if a Pod is unschedulable
func IsPowerOfTwo ¶
IsPowerOfTwo calculates if a number is power of two or not reference: https://github.com/golang/go/blob/master/src/strconv/itoa.go#L204 #wokeignore:rule=master This function will return false if the number is zero
func IsReconciliationDisabled ¶
func IsReconciliationDisabled(object *metav1.ObjectMeta) bool
IsReconciliationDisabled checks if the reconciliation loop is disabled on the given resource
func IsWalArchivingDisabled ¶ added in v1.21.4
func IsWalArchivingDisabled(object *metav1.ObjectMeta) bool
IsWalArchivingDisabled returns a boolean indicating if PostgreSQL not archive WAL files
func JobHasOneCompletion ¶ added in v1.18.4
JobHasOneCompletion Completion check if a certain job is complete
func LabelClusterName ¶
func LabelClusterName(object *metav1.ObjectMeta, name string)
LabelClusterName labels the object with the cluster name
func MergeObjectsMetadata ¶ added in v1.20.5
MergeObjectsMetadata is capable of merging the labels and annotations of two objects metadata
func PodHasContainerStatuses ¶ added in v1.21.6
PodHasContainerStatuses checks if a Pod has container status elements
func PodMonitorExist ¶
func PodMonitorExist(client discovery.DiscoveryInterface) (bool, error)
PodMonitorExist tries to find the PodMonitor resource in the current cluster
func RunningOnOLM ¶ added in v1.22.5
func RunningOnOLM() bool
RunningOnOLM returns if we're running over a Kubernetes cluster with OLM support
func SetAsOwnedBy ¶
func SetAsOwnedBy(controlled *metav1.ObjectMeta, controller metav1.ObjectMeta, typeMeta metav1.TypeMeta)
SetAsOwnedBy sets the controlled object as owned by a certain other controller object with his type information
func SetInstanceRole ¶ added in v1.19.5
func SetInstanceRole(meta *metav1.ObjectMeta, role string)
SetInstanceRole sets both ClusterRoleLabelName and ClusterInstanceRoleLabelName on the given ObjectMeta
func SetOperatorVersion ¶
func SetOperatorVersion(object *metav1.ObjectMeta, version string)
SetOperatorVersion set inside a certain object metadata the annotation containing the version of the operator that generated the object
func SetVolumeSnapshot ¶ added in v1.21.0
func SetVolumeSnapshot(value bool)
SetVolumeSnapshot set the haveVolumeSnapshot variable to a specific value for testing purposes IMPORTANT: use it only in the unit tests
Types ¶
type AvailableArchitecture ¶ added in v1.21.4
type AvailableArchitecture struct {
GoArch string
// contains filtered or unexported fields
}
AvailableArchitecture is a struct containing info about an available architecture
func GetAvailableArchitecture ¶ added in v1.21.4
func GetAvailableArchitecture(goArch string) (*AvailableArchitecture, error)
GetAvailableArchitecture returns an available architecture given its goArch
func GetAvailableArchitectures ¶ added in v1.21.4
func GetAvailableArchitectures() []*AvailableArchitecture
GetAvailableArchitectures returns the available instance's architectures
func (*AvailableArchitecture) FileStream ¶ added in v1.21.4
func (arch *AvailableArchitecture) FileStream() (io.ReadCloser, error)
FileStream opens a stream reading from the manager's binary
func (*AvailableArchitecture) GetHash ¶ added in v1.21.4
func (arch *AvailableArchitecture) GetHash() string
GetHash retrieves the hash for a given AvailableArchitecture
type ErrInvalidPromotionToken ¶ added in v1.24.0
type ErrInvalidPromotionToken struct {
// contains filtered or unexported fields
}
ErrInvalidPromotionToken is raised when the promotion token is not valid
func (*ErrInvalidPromotionToken) Error ¶ added in v1.24.0
func (e *ErrInvalidPromotionToken) Error() string
func (*ErrInvalidPromotionToken) Unwrap ¶ added in v1.24.0
func (e *ErrInvalidPromotionToken) Unwrap() error
type FencingMetadataExecutor ¶ added in v1.21.5
type FencingMetadataExecutor struct {
// contains filtered or unexported fields
}
FencingMetadataExecutor executes the logic regarding adding and removing the fencing annotation for a kubernetes object
func NewFencingMetadataExecutor ¶ added in v1.21.5
func NewFencingMetadataExecutor(cli client.Client) *FencingMetadataExecutor
NewFencingMetadataExecutor creates a fluent client for FencingMetadataExecutor
func (*FencingMetadataExecutor) AddFencing ¶ added in v1.21.5
func (fb *FencingMetadataExecutor) AddFencing() *FencingMetadataExecutor
AddFencing instructs the client to execute the logic of adding a instance
func (*FencingMetadataExecutor) Execute ¶ added in v1.21.5
func (fb *FencingMetadataExecutor) Execute(ctx context.Context, key types.NamespacedName, obj client.Object) error
Execute executes the instructions given with the fluent builder, returns any error encountered
func (*FencingMetadataExecutor) ForAllInstances ¶ added in v1.21.5
func (fb *FencingMetadataExecutor) ForAllInstances() *FencingMetadataExecutor
ForAllInstances applies the logic to all cluster instances
func (*FencingMetadataExecutor) ForInstance ¶ added in v1.21.5
func (fb *FencingMetadataExecutor) ForInstance(instanceNames ...string) *FencingMetadataExecutor
ForInstance applies the logic to the specified instance
func (*FencingMetadataExecutor) RemoveFencing ¶ added in v1.21.5
func (fb *FencingMetadataExecutor) RemoveFencing() *FencingMetadataExecutor
RemoveFencing instructs the client to execute the logic of removing an instance
type HibernationAnnotationValue ¶ added in v1.21.4
type HibernationAnnotationValue string
HibernationAnnotationValue describes the status of the hibernation
const ( // HibernationAnnotationValueOff is the value of hibernation annotation when the hibernation // has been deactivated for the cluster HibernationAnnotationValueOff HibernationAnnotationValue = "off" // HibernationAnnotationValueOn is the value of hibernation annotation when the hibernation // has been requested for the cluster HibernationAnnotationValueOn HibernationAnnotationValue = "on" )
type InheritanceController ¶ added in v1.18.4
type InheritanceController interface {
// IsAnnotationInherited checks if a certain annotation should be
// inherited
IsAnnotationInherited(name string) bool
// IsLabelInherited checks if a certain label should be
// inherited
IsLabelInherited(name string) bool
}
InheritanceController controls if a label or an annotation should be inherited
type PgControlData ¶ added in v1.24.4
type PgControlData map[pgControlDataKey]string
PgControlData represents the parsed output of pg_controldata
func ParsePgControldataOutput ¶ added in v1.21.0
func ParsePgControldataOutput(data string) PgControlData
ParsePgControldataOutput parses a pg_controldata output into a map of key-value pairs
func (PgControlData) CreatePromotionToken ¶ added in v1.24.4
func (p PgControlData) CreatePromotionToken() (string, error)
CreatePromotionToken translates a parsed pgControlData into a JSON token
func (PgControlData) GetBytesPerWALSegment ¶ added in v1.24.4
func (p PgControlData) GetBytesPerWALSegment() (int, error)
GetBytesPerWALSegment returns the size of the WAL segments
func (PgControlData) GetDataPageChecksumVersion ¶ added in v1.24.4
func (p PgControlData) GetDataPageChecksumVersion() (string, error)
GetDataPageChecksumVersion returns whether the checksums are enabled in the cluster
func (PgControlData) GetDatabaseClusterState ¶ added in v1.24.4
func (p PgControlData) GetDatabaseClusterState() string
GetDatabaseClusterState returns the status of the latest primary that ran on this data directory
func (PgControlData) GetDatabaseSystemIdentifier ¶ added in v1.24.4
func (p PgControlData) GetDatabaseSystemIdentifier() string
GetDatabaseSystemIdentifier returns the database system identifier
func (PgControlData) GetLatestCheckpointREDOLocation ¶ added in v1.24.4
func (p PgControlData) GetLatestCheckpointREDOLocation() string
GetLatestCheckpointREDOLocation returns the latest checkpoint's REDO location
func (PgControlData) GetLatestCheckpointTimelineID ¶ added in v1.24.4
func (p PgControlData) GetLatestCheckpointTimelineID() string
GetLatestCheckpointTimelineID returns the latest checkpoint's TimeLineID
func (PgControlData) GetREDOWALFile ¶ added in v1.24.4
func (p PgControlData) GetREDOWALFile() string
GetREDOWALFile returns the latest checkpoint's REDO WAL file
func (PgControlData) GetTimeOfLatestCheckpoint ¶ added in v1.24.4
func (p PgControlData) GetTimeOfLatestCheckpoint() string
GetTimeOfLatestCheckpoint returns the time of latest checkpoint
func (PgControlData) TryGetLatestCheckpointTimelineID ¶ added in v1.24.4
func (p PgControlData) TryGetLatestCheckpointTimelineID() (string, bool)
TryGetLatestCheckpointTimelineID returns the latest checkpoint's TimeLineID
func (PgControlData) TryGetREDOWALFile ¶ added in v1.24.4
func (p PgControlData) TryGetREDOWALFile() (string, bool)
TryGetREDOWALFile returns the latest checkpoint's REDO WAL file
type PgControldataTokenContent ¶ added in v1.24.0
type PgControldataTokenContent struct {
// Latest checkpoint's TimeLineID
// TODO(leonardoce): should this be an integer?
LatestCheckpointTimelineID string `json:"latestCheckpointTimelineID,omitempty"`
// Latest checkpoint's REDO WAL file
REDOWALFile string `json:"redoWalFile,omitempty"`
// Database system identifier
DatabaseSystemIdentifier string `json:"databaseSystemIdentifier,omitempty"`
// Latest checkpoint's REDO location
LatestCheckpointREDOLocation string `json:"latestCheckpointREDOLocation,omitempty"`
// Time of latest checkpoint
TimeOfLatestCheckpoint string `json:"timeOfLatestCheckpoint,omitempty"`
// The version of the operator that created the token
// TODO(leonardoce): if the version of the operator is different,
// the webhook should raise a warning
OperatorVersion string `json:"operatorVersion,omitempty"`
}
PgControldataTokenContent contains the data needed to properly create a promotion token
func ParsePgControldataToken ¶ added in v1.24.0
func ParsePgControldataToken(base64Token string) (*PgControldataTokenContent, error)
ParsePgControldataToken parses the JSON token into usable content
func (*PgControldataTokenContent) Encode ¶ added in v1.24.0
func (token *PgControldataTokenContent) Encode() (string, error)
Encode encodes the token content into a base64 string
func (*PgControldataTokenContent) IsValid ¶ added in v1.24.0
func (token *PgControldataTokenContent) IsValid() error
IsValid checks if the promotion token is valid or returns an error otherwise
type PgDataState ¶ added in v1.24.0
type PgDataState string
PgDataState represents the "Database cluster state" field of pg_controldata
func (PgDataState) IsShutdown ¶ added in v1.24.0
func (state PgDataState) IsShutdown(ctx context.Context) bool
IsShutdown checks if the PGDATA status represents a shut down instance
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package context contains utility functions to work with context.Context
|
Package context contains utility functions to work with context.Context |
|
Package extensions provides utilities for resolving PostgreSQL extension configurations from image catalogs and cluster specifications
|
Package extensions provides utilities for resolving PostgreSQL extension configurations from image catalogs and cluster specifications |
|
Package hash allows the user to get a hash number for a given Kubernetes object.
|
Package hash allows the user to get a hash number for a given Kubernetes object. |
|
Package imagecatalog provides utilities for fetching image catalogs
|
Package imagecatalog provides utilities for fetching image catalogs |