utils

package
v1.15.5 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2022 License: Apache-2.0 Imports: 27 Imported by: 2

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"

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

	// 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"

	// ReconciliationDisabledValue it the value that stops the reconciliation loop
	ReconciliationDisabledValue = "disabled"
)
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 CountCompleteJobs

func CountCompleteJobs(jobList []batchv1.Job) int

CountCompleteJobs 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, cli *kubernetes.Clientset) error

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

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 arbitrary command inside the pod, and returns his result

func FilterActivePods

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

FilterActivePods returns pods that have not terminated.

func FilterCompleteJobs

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

FilterCompleteJobs returns jobs that are complete

func GetCurrentTimestamp

func GetCurrentTimestamp() string

GetCurrentTimestamp returns the current timestamp as a string in RFC3339 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 GetOperatorDeployment

func GetOperatorDeployment(
	ctx context.Context,
	client kubernetes.Interface,
	namespace, operatorLabelSelector string,
) (*v1.Deployment, error)

GetOperatorDeployment find the operator deployment using labels and then return the deployment object, in case we can't find a deployment or we find more than one, we just return an error.

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 IsJobComplete

func IsJobComplete(job batchv1.Job) bool

IsJobComplete check if a certain job is complete

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 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:SS (modified time.RFC3339)

func PodMonitorExist

func PodMonitorExist(client *discovery.DiscoveryClient) (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 *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 SetAsOwnedByOperatorDeployment

func SetAsOwnedByOperatorDeployment(ctx context.Context,
	client kubernetes.Interface,
	controlled *metav1.ObjectMeta,
	operatorLabelSelector string,
) error

SetAsOwnedByOperatorDeployment sets the controlled object as owned by the operator deployment.

IMPORTANT: The controlled resource must reside in the same namespace as the operator as described by: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/

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

Types

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