utils

package
v1.19.0 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2023 License: Apache-2.0 Imports: 34 Imported by: 3

Documentation

Overview

Package utils contains otherwise uncategorized kubernetes relative functions

Index

Constants

View Source
const (
	// 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 = "cnpg.io/fencedInstances"

	// FenceAllServers is the wildcard that, if put inside the fenced instances list, will fence every
	// CNPG instance
	FenceAllServers = "*"
)
View Source
const (
	// ClusterLabelName is the name of cluster which the backup CR belongs to
	ClusterLabelName = "cnpg.io/cluster"

	// OldClusterLabelName label is applied to objects to link them to the owning
	// cluster.
	//
	// Deprecated: please use ClusterLabelName instead
	//
	// TODO: delete as soon as possible. releases 1.16, 1.17 still
	// have embedded logic relying on "postgresql" as the cluster label
	// in controllers/cluster_controller.go mapNodeToClusters() at minimum.
	// Release 1.18 does not have that logic
	//
	// IMPORTANT: Removing this is a breaking change and should be announced in Release Notes
	// utils.ClusterLabelName should be used instead where possible.
	OldClusterLabelName = "postgresql" // Deprecated: use ClusterLabelName going forward

	// JobRoleLabelName is the name of the label containing the purpose of the executed job
	JobRoleLabelName = "cnpg.io/jobRole"

	// PvcRoleLabelName is the name of the label containing the purpose of the pvc
	PvcRoleLabelName = "cnpg.io/pvcRole"

	// PodRoleLabelName is the name of the label containing the podRole value
	PodRoleLabelName = "cnpg.io/podRole"

	// InstanceNameLabelName is the name of the label containing the instance name
	InstanceNameLabelName = "cnpg.io/instanceName"

	// OperatorVersionAnnotationName is the name of the annotation containing
	// the version of the operator that generated a certain object
	OperatorVersionAnnotationName = "cnpg.io/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 = "cnpg.io/reconciliationLoop"

	// HibernateClusterManifestAnnotationName contains the hibernated cluster manifest
	HibernateClusterManifestAnnotationName = "cnpg.io/hibernateClusterManifest"

	// HibernatePgControlDataAnnotationName contains the pg_controldata output of the hibernated cluster
	HibernatePgControlDataAnnotationName = "cnpg.io/hibernatePgControlData"

	// PodEnvHashAnnotationName is the name of the annotation containing the podEnvHash value
	PodEnvHashAnnotationName = "cnpg.io/podEnvHash"
)
View Source
const (
	// PodHealthy means that a Pod is active and ready
	PodHealthy = "healthy"

	// PodReplicating means that a Pod is still not ready but still active
	PodReplicating = "replicating"

	// PodFailed means that a Pod will not be scheduled again (deleted or evicted)
	PodFailed = "failed"
)
View Source
const (
	// PodReasonEvicted is set inside the status as the Pod failure reason
	// when the Kubelet evicts a Pod
	PodReasonEvicted = "Evicted"
)

Variables

View Source
var (
	// ErrorFencedInstancesSyntax is emitted when the fencedInstances annotation
	// have an invalid syntax
	ErrorFencedInstancesSyntax = errors.New("fencedInstances annotation has invalid syntax")

	// ErrorServerAlreadyFenced is emitted when trying to fence an instance
	// which is already fenced
	ErrorServerAlreadyFenced = errors.New("this instance has already been fenced")

	// ErrorServerAlreadyUnfenced is emitted when trying to unfencing an instance
	// which was not fenced
	ErrorServerAlreadyUnfenced = errors.New("this instance was not fenced")

	// 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")
)
View Source
var ErrorContainerNotFound = fmt.Errorf("container not found")

ErrorContainerNotFound is raised when an Exec call is invoked against a non existing container

Functions

func AddFencedInstance

func AddFencedInstance(serverName string, object *metav1.ObjectMeta) error

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, annotations map[string]string)

AnnotateAppArmor adds an annotation to the pod

func CollectDifferencesFromMaps

func CollectDifferencesFromMaps(p1 map[string]string, p2 map[string]string) map[string][]string

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 ConvertToPostgresFormat

func ConvertToPostgresFormat(timestamp string) string

ConvertToPostgresFormat converts timestamps to PostgreSQL time format, if needed. e.g. "2006-01-02T15:04:05Z07:00" --> "2006-01-02 15:04:05.000000Z07:00" If the conversion fails, the input timestamp is returned as it is.

func CountJobsWithOneCompletion added in v1.17.4

func CountJobsWithOneCompletion(jobList []batchv1.Job) int

CountJobsWithOneCompletion count the number complete jobs

func CountReadyPods

func CountReadyPods(podList []corev1.Pod) int

CountReadyPods counts the number of Pods which are ready

func DetectKubeSystemUID

func DetectKubeSystemUID(ctx context.Context, kubeClient client.Client) error

DetectKubeSystemUID retrieves the UID of the kube-system namespace of the containing cluster

func DetectSeccompSupport added in v1.16.4

func DetectSeccompSupport(client *discovery.DiscoveryClient) (err error)

DetectSeccompSupport checks the version of Kubernetes in the cluster to determine whether Seccomp is supported

func DetectSecurityContextConstraints

func DetectSecurityContextConstraints(client *discovery.DiscoveryClient) (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 DifferenceBetweenTimestamps added in v1.15.3

func DifferenceBetweenTimestamps(first, second string) (time.Duration, error)

DifferenceBetweenTimestamps returns the time.Duration difference between two timestamps strings in time.RFC3339.

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, and returns its result

func FilterActivePods

func FilterActivePods(pods []corev1.Pod) []corev1.Pod

FilterActivePods returns pods that have not terminated.

func FilterJobsWithOneCompletion added in v1.17.4

func FilterJobsWithOneCompletion(jobList []batchv1.Job) []batchv1.Job

FilterJobsWithOneCompletion returns jobs that have one completion

func GetCurrentTimestamp

func GetCurrentTimestamp() string

GetCurrentTimestamp returns the current timestamp as a string in RFC3339Micro format

func GetDiscoveryClient

func GetDiscoveryClient() (*discovery.DiscoveryClient, error)

GetDiscoveryClient creates a discovery client or return error

func GetFencedInstances

func GetFencedInstances(annotations map[string]string) (*stringset.Data, error)

GetFencedInstances gets the set of fenced servers from the annotations

func GetImageTag

func GetImageTag(imageName string) string

GetImageTag gets the image tag from a full image string. Example:

GetImageTag("postgres") == "latest"
GetImageTag("ghcr.io/cloudnative-pg/postgresql:12.3") == "12.3"

func GetKubeSystemUID

func GetKubeSystemUID() string

GetKubeSystemUID returns the uid of the kube-system namespace

func HaveSeccompSupport added in v1.16.4

func HaveSeccompSupport() bool

HaveSeccompSupport returns true if Seccomp is supported. If it is, we should set the SeccompProfile in the pods

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 InheritAnnotations

func InheritAnnotations(
	object *metav1.ObjectMeta,
	annotations map[string]string,
	fixedAnnotations map[string]string,
	config *configuration.Data,
)

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,
	config *configuration.Data,
)

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

func IsAnnotationAppArmorPresent(annotations map[string]string) bool

IsAnnotationAppArmorPresent checks if one of the annotations is an AppArmor annotation

func IsAnnotationAppArmorPresentInObject

func IsAnnotationAppArmorPresentInObject(object *metav1.ObjectMeta, 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,
	configuration *config.Data,
) 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

func IsConditionReasonValid(conditionReason string) bool

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,
	configuration *config.Data,
) 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 IsPodActive

func IsPodActive(p corev1.Pod) bool

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

func IsPodAlive(p corev1.Pod) bool

IsPodAlive check if a pod is active and not crash-looping

func IsPodEvicted

func IsPodEvicted(p corev1.Pod) bool

IsPodEvicted checks if a pod has been evicted by the Kubelet

func IsPodReady

func IsPodReady(pod corev1.Pod) bool

IsPodReady check if a Pod is ready or not

func IsPowerOfTwo

func IsPowerOfTwo(n int) bool

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 IsResourceSubset

func IsResourceSubset(resources, resourcesSubset corev1.ResourceRequirements) bool

IsResourceSubset checks if some resource requirements are a subset of another

func LabelClusterName

func LabelClusterName(object *metav1.ObjectMeta, name string)

LabelClusterName labels the object with the cluster name

func LabelJobRole

func LabelJobRole(object *metav1.ObjectMeta, role string)

LabelJobRole labels a job with its role

func ListStatusPods

func ListStatusPods(podList []corev1.Pod) map[PodStatus][]string

ListStatusPods return a list of active Pods

func MapToBarmanTagsFormat

func MapToBarmanTagsFormat(option string, mapTags map[string]string) ([]string, error)

MapToBarmanTagsFormat will transform a map[string]string into the Barman tags format needed

func MergeMap added in v1.18.1

func MergeMap(receiver, giver map[string]string)

MergeMap transfers the content of a giver map to a receiver

func NewSimpleDBConnection added in v1.16.2

func NewSimpleDBConnection(connectionString string) (*sql.DB, error)

NewSimpleDBConnection creates a postgres connection with the simple protocol

func ParsePolicy

func ParsePolicy(policy string) (string, error)

ParsePolicy ensure that the policy string follows the rules required by Barman

func ParseTargetTime

func ParseTargetTime(currentLocation *time.Location, targetTime string) (time.Time, error)

ParseTargetTime returns the parsed targetTime which is used for point-in-time-recovery Currently, we support formats of targetTime as follows: YYYY-MM-DD HH24:MI:SS YYYY-MM-DD HH24:MI:SS.FF6TZH YYYY-MM-DD HH24:MI:SS.FF6TZH:TZM YYYY-MM-DDTHH24:MI:SSZ (time.RFC3339) YYYY-MM-DDTHH24:MI:SS±TZH:TZM (time.RFC3339) YYYY-MM-DDTHH24:MI:SSS±TZH:TZM (time.RFC3339Micro) YYYY-MM-DDTHH24:MI:SS (modified time.RFC3339)

func PodMonitorExist

func PodMonitorExist(client discovery.DiscoveryInterface) (bool, error)

PodMonitorExist tries to find the PodMonitor resource in the current cluster

func RemoveFencedInstance

func RemoveFencedInstance(serverName string, object *metav1.ObjectMeta) error

RemoveFencedInstance removes the given server name from the FencedInstanceAnnotation annotation returns an error if the instance was already unfenced

func SetAsOwnedBy

func SetAsOwnedBy(controlled *v1.ObjectMeta, controller v1.ObjectMeta, typeMeta v1.TypeMeta)

SetAsOwnedBy sets the controlled object as owned by a certain other controller object with his type information

func SetFencedInstances

func SetFencedInstances(object *metav1.ObjectMeta, data *stringset.Data) error

SetFencedInstances sets the list of fenced servers inside the annotations

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 StringInSlice

func StringInSlice(slice []string, search string) bool

StringInSlice looks for a search string inside the string slice

func ToBytes added in v1.18.2

func ToBytes[T constraints.Signed | constraints.Float](mb T) float64

ToBytes converts an input value in MB to bytes Input: value - an integer representing size in MB Output: the size in bytes, calculated by multiplying the input value by 1024 * 1024

Types

type PVCRole added in v1.17.0

type PVCRole string

PVCRole describes the role of a PVC

const (
	// PVCRolePgData is a PVC used for storing PG_DATA
	PVCRolePgData PVCRole = "PG_DATA"
	// PVCRolePgWal is a PVC used for storing PG_WAL
	PVCRolePgWal PVCRole = "PG_WAL"
)

type PodRole added in v1.15.4

type PodRole string

PodRole describes the Role of a given pod

const (
	// PodRoleInstance the label value indicating an instance
	PodRoleInstance PodRole = "instance"
)

type PodStatus

type PodStatus string

PodStatus represent the possible status of pods

type Reference

type Reference struct {
	Name   string
	Tag    string
	Digest string
}

Reference .

func NewReference

func NewReference(name string) *Reference

NewReference parses the image name and returns an error if the name is invalid.

func (*Reference) GetNormalizedName

func (r *Reference) GetNormalizedName() (name string)

GetNormalizedName returns the normalized name of a reference

Directories

Path Synopsis
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 logs contains code to fetch logs from Kubernetes pods
Package logs contains code to fetch logs from Kubernetes pods

Jump to

Keyboard shortcuts

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