k8s

package
v1.91.0 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2022 License: Apache-2.0 Imports: 35 Imported by: 1

Documentation

Index

Constants

View Source
const (
	CNRMGroup                            = "cnrm.cloud.google.com"
	ApiDomainSuffix                      = ".cnrm.cloud.google.com"
	SystemNamespace                      = "cnrm-system"
	ControllerMaxConcurrentReconciles    = 20
	ReconcileDeadline                    = 59 * time.Minute
	TimeToLeaseExpiration                = 40 * time.Minute
	TimeToLeaseRenewal                   = 20 * time.Minute
	MeanReconcileReenqueuePeriod         = 10 * time.Minute
	JitterFactor                         = 2.0
	UpToDate                             = "UpToDate"
	UpToDateMessage                      = "The resource is up to date"
	Created                              = "Created"
	CreatedMessage                       = "Successfully created"
	CreateFailed                         = "CreateFailed"
	CreateFailedMessageTmpl              = "Create call failed: %v"
	Updating                             = "Updating"
	UpdatingMessage                      = "Update in progress"
	UpdateFailed                         = "UpdateFailed"
	UpdateFailedMessageTmpl              = "Update call failed: %v"
	Deleting                             = "Deleting"
	DeletingMessage                      = "Deletion in progress"
	Deleted                              = "Deleted"
	DeletedMessage                       = "Successfully deleted"
	DeleteFailed                         = "DeleteFailed"
	NoCondition                          = "NoCondition"
	DeleteFailedMessageTmpl              = "Delete call failed: %v"
	ControllerFinalizerName              = "cnrm.cloud.google.com/finalizer"
	DeletionDefenderFinalizerName        = "cnrm.cloud.google.com/deletion-defender"
	DependencyNotReady                   = "DependencyNotReady"
	DependencyNotFound                   = "DependencyNotFound"
	DependencyInvalid                    = "DependencyInvalid"
	ManagementConflict                   = "ManagementConflict"
	PreActuationTransformFailed          = "PreActuationTransformFailed"
	PostActuationTransformFailed         = "PostActuationTransformFailed"
	DeletionPolicyDelete                 = "delete"
	DeletionPolicyAbandon                = "abandon"
	AnnotationPrefix                     = CNRMGroup
	NamespaceEnvVar                      = "NAMESPACE"
	ImmediateReconcileRequestsBufferSize = 10000

	ReadinessServerPort = 23232
	ReadinessServerPath = "/ready"

	ControllerManagedFieldManager = "cnrm-controller-manager"
	SupportsSSAManager            = "supports-ssa"

	// Management conflict prevention policies
	ManagementConflictPreventionPolicyNone     = "none"
	ManagementConflictPreventionPolicyResource = "resource"

	// State into spec annotation values
	StateMergeIntoSpec = "merge"
	StateAbsentInSpec  = "absent"

	// Core kubernetes constants
	LastAppliedConfigurationAnnotation = "kubectl.kubernetes.io/last-applied-configuration"
	ManagedFieldsTypeFieldsV1          = "FieldsV1"

	ResourceIDFieldName = "resourceID"
	ResourceIDFieldPath = "spec." + ResourceIDFieldName

	StabilityLevelStable = "stable"
	StabilityLevelAlpha  = "alpha"

	KCCAPIVersion = "v1beta1"
)

TODO: clean up old conditions used in handcrafted controllers

Variables

View Source
var (
	DeletionPolicyAnnotation = FormatAnnotation("deletion-policy")

	// Annotations for Container objects
	ProjectIDAnnotation  = FormatAnnotation("project-id")
	FolderIDAnnotation   = FormatAnnotation("folder-id")
	OrgIDAnnotation      = FormatAnnotation("organization-id")
	ContainerAnnotations = []string{
		ProjectIDAnnotation,
		FolderIDAnnotation,
		OrgIDAnnotation,
	}

	ManagementConflictPreventionPolicyAnnotation               = "management-conflict-prevention-policy"
	ManagementConflictPreventionPolicyFullyQualifiedAnnotation = FormatAnnotation(ManagementConflictPreventionPolicyAnnotation)
	ManagementConflictPreventionPolicyValues                   = []string{
		ManagementConflictPreventionPolicyNone,
		ManagementConflictPreventionPolicyResource,
	}

	KCCComponentLabel = FormatAnnotation("component")
	KCCSystemLabel    = FormatAnnotation("system")
	KCCVersionLabel   = FormatAnnotation("version")
	DCL2CRDLabel      = FormatAnnotation("dcl2crd")
	KCCStabilityLabel = FormatAnnotation("stability-level")

	MutableButUnreadableFieldsAnnotation = FormatAnnotation("mutable-but-unreadable-fields")
	ObservedSecretVersionsAnnotation     = FormatAnnotation("observed-secret-versions")

	SupportsSSAAnnotation = FormatAnnotation("supports-ssa")

	BlueprintAttributionAnnotation = FormatAnnotation("blueprint")

	StateIntoSpecAnnotation       = FormatAnnotation("state-into-spec")
	StateIntoSpecAnnotationValues = []string{
		StateMergeIntoSpec,
		StateAbsentInSpec,
	}
	WebhookTimeoutSeconds = int32(3)

	ReservedStatusFieldNamesForFutureUse = []string{"generation"}

	NamespaceIDConfigMapNN = types.NamespacedName{
		Namespace: SystemNamespace,
		Name:      "namespace-id",
	}
)

Functions

func ConditionSlicesEqual

func ConditionSlicesEqual(conditions1, conditions2 []v1alpha1.Condition) bool

func ConditionsEqualIgnoreTransitionTime

func ConditionsEqualIgnoreTransitionTime(c1, c2 v1alpha1.Condition) bool

func ConstructManagedFieldsV1Set

func ConstructManagedFieldsV1Set(managedFields []v1.ManagedFieldsEntry) (*fieldpath.Set, error)

ConstructManagedFieldsV1Set takes the given managed field entries and constructs a set of all the k8s-managed fields from the spec.

func ConstructTrimmedSpecWithManagedFields

func ConstructTrimmedSpecWithManagedFields(resource *Resource, jsonSchema *apiextensions.JSONSchemaProps,
	hierarchicalRefs []corekccv1alpha1.HierarchicalReference) (map[string]interface{}, error)

Construct the trimmed spec that only contains k8s managed fields.

The DCL SDK's Apply() function can take a partial state that only contains fields that users have an opinion on. Here we will look into the managed-fields set and trim the full spec to only preserve fields that are k8s-managed (i.e. users want KCC to enforce those fields to their desired state). DCL will take the generated partial state, enforce specified fields and ignore unspecified fields by preserving live values from the underlying API.

func ContainerTypes

func ContainerTypes(containers []corekccv1alpha1.Container) []corekccv1alpha1.ContainerType

func ContainerTypesFor

func ContainerTypesFor(hierarchicalRefs []corekccv1alpha1.HierarchicalReference) []corekccv1alpha1.ContainerType

func CurrentNamespace

func CurrentNamespace() string

func EnsureFinalizer

func EnsureFinalizer(o metav1.Object, finalizer string) (found bool)

func EnsureFinalizers

func EnsureFinalizers(o metav1.Object, finalizers ...string) (found bool)

func EnsureHierarchicalReference

func EnsureHierarchicalReference(ctx context.Context, resource *Resource, hierarchicalRefs []corekccv1alpha1.HierarchicalReference, containers []corekccv1alpha1.Container, c client.Client) error

EnsureHierarchicalReference ensures that the given resource has a hierarchical reference and will set one if none is found.

func EnsureManagementConflictPreventionAnnotationForTFBasedResource

func EnsureManagementConflictPreventionAnnotationForTFBasedResource(c client.Client, ctx context.Context, obj metav1.Object, rc *corekccv1alpha1.ResourceConfig, tfResourceMap map[string]*tfschema.Resource) error

func EnsureSpecIntoSateAnnotation

func EnsureSpecIntoSateAnnotation(obj *Resource) error

func FormatAnnotation

func FormatAnnotation(annotationName string) string

func GVKListContains

func GVKListContains(gvkList []schema.GroupVersionKind, gvk schema.GroupVersionKind) bool

func GVKSetToList

func GVKSetToList(gvkSet map[schema.GroupVersionKind]bool) []schema.GroupVersionKind

func GenerateMutableButUnreadableFieldsAnnotation

func GenerateMutableButUnreadableFieldsAnnotation(resource *Resource, mutableButUnreadablePaths [][]string) (string, error)

func GenerateMutableButUnreadableFieldsState

func GenerateMutableButUnreadableFieldsState(resource *Resource, mutableButUnreadablePaths [][]string) (map[string]interface{}, error)

func GetAnnotation

func GetAnnotation(annotation string, obj metav1.Object) (string, bool)

func GetAnnotationForContainerType

func GetAnnotationForContainerType(containerType corekccv1alpha1.ContainerType) string

func GetContainerAnnotation

func GetContainerAnnotation(annotations map[string]string, containerTypes []corekccv1alpha1.ContainerType) (string, corekccv1alpha1.ContainerType, error)

GetContainerAnnotation will get the appropriate container annotation from the given annotations.

func GetHierarchicalReference

GetHierarchicalReference gets the resource reference within the resource that corresponds to any of the given hierarchical reference configurations, as well as the the hierachical reference configuration associated with the resource reference. Returns a nil resource reference if none is found. Returns an error if multiple resource references are found (an invalid resource state as resources can have at most one hierarchical reference).

func GetHierarchicalReferenceFromSpec

func GetHierarchicalReferenceFromSpec(spec map[string]interface{}, hierarchicalRefs []corekccv1alpha1.HierarchicalReference) (
	*corekccv1alpha1.ResourceReference, corekccv1alpha1.HierarchicalReference, error)

func GetK8sManagedFields

func GetK8sManagedFields(u *unstructured.Unstructured) (*fieldpath.Set, error)

func GetMutableButUnreadableFieldsFromAnnotations

func GetMutableButUnreadableFieldsFromAnnotations(resource *Resource, mutableButUnreadablePaths [][]string) (map[string]interface{}, error)

func GetNamespacedName

func GetNamespacedName(obj metav1.Object) types.NamespacedName

func GetProjectIDForNamespace

func GetProjectIDForNamespace(c client.Client, ctx context.Context, namespaceName string) (string, error)

func GetReadyCondition

func GetReadyCondition(r *Resource) (condition k8sv1alpha1.Condition, found bool)

func GetReferencedResourceAsUnstruct

func GetReferencedResourceAsUnstruct(resourceRef *corekccv1alpha1.ResourceReference, gvk schema.GroupVersionKind, resourceNamespace string, kubeClient client.Client) (*unstructured.Unstructured, error)

func GetSecretVal

func GetSecretVal(secretKeyRef *corekccv1alpha1.SecretKeyReference, secretNamespace string, kubeClient client.Client) (secretVal string, secretVersion string, err error)

func GetSecretVersionsFromAnnotations

func GetSecretVersionsFromAnnotations(resource *Resource) (map[string]string, error)

func HasAbandonAnnotation

func HasAbandonAnnotation(obj metav1.Object) bool

func HasFinalizer

func HasFinalizer(o metav1.Object, finalizer string) bool

func HierarchicalReferencesToFields

func HierarchicalReferencesToFields(hierarchicalRefs []corekccv1alpha1.HierarchicalReference) []string

func IsAnnotationsUpdateRequired

func IsAnnotationsUpdateRequired(resource *Resource, original *Resource) bool

func IsDeleted

func IsDeleted(objectMeta *metav1.ObjectMeta) bool

func IsK8sManaged

func IsK8sManaged(key string, specObj map[string]interface{}, managedFields *fieldpath.Set) bool

func IsManagedByKCC

func IsManagedByKCC(gvk schema.GroupVersionKind) bool

func IsProjectScoped

func IsProjectScoped(containers []corekccv1alpha1.Container) bool

func IsReferenceNotFoundError

func IsReferenceNotFoundError(err error) bool

func IsResourceReady

func IsResourceReady(r *Resource) bool

func IsSpecOrStatusUpdateRequired

func IsSpecOrStatusUpdateRequired(resource *Resource, original *Resource) bool

func KindWithoutServicePrefix

func KindWithoutServicePrefix(gvk schema.GroupVersionKind) string

KindWithoutServicePrefix returns the kind without the service prefix (e.g. "ComputeBackendBucket => "BackendBucket"). Kinds which do not contain a service prefix are returned directly (e.g. "Project" => "Project").

func MarshalAsConditionsSlice

func MarshalAsConditionsSlice(obj []interface{}) ([]v1alpha1.Condition, error)

func MarshalObjectAsUnstructured

func MarshalObjectAsUnstructured(o metav1.Object) (*unstructured.Unstructured, error)

func NewCustomReadyCondition

func NewCustomReadyCondition(status v1.ConditionStatus, rs, msg string) v1alpha1.Condition

func NewErroringClient

func NewErroringClient() client.Client

Some packages, like 'gcpclient' make use of krmtotf which is tightly coupled with the controller-runtime client. However, krmtotf does not actually need the client if all the resources passed in have all references resolved, etc. To enable usage of the library but also to avoid panics, this erroring client can be passed to krmtotf methods.

func NewReadyCondition

func NewReadyCondition() v1alpha1.Condition

func NewReadyConditionWithError

func NewReadyConditionWithError(err error) v1alpha1.Condition

func OverlayManagedFieldsOntoState

func OverlayManagedFieldsOntoState(spec, stateAsKRM map[string]interface{}, managedFields *fieldpath.Set,
	jsonSchema *apiextensions.JSONSchemaProps, hierarchicalRefs []corekccv1alpha1.HierarchicalReference) (map[string]interface{}, error)

OverlayManagedFieldsOntoState overlays the fields managed by Kubernetes managers onto the KRM-ified live state.

The return value is the union of stateAsKRM with managed fields from spec.

func ReadyConditionMatches

func ReadyConditionMatches(resource *Resource, status corev1.ConditionStatus, rs, msg string) bool

func RemoveAnnotation

func RemoveAnnotation(annotation string, obj metav1.Object)

func RemoveFinalizer

func RemoveFinalizer(o metav1.Object, finalizer string)

func RenameStatusFieldWithReservedName

func RenameStatusFieldWithReservedName(field string) string

func RenameStatusFieldsWithReservedNames

func RenameStatusFieldsWithReservedNames(status *apiextensions.JSONSchemaProps) (*apiextensions.JSONSchemaProps, error)

func ReservedStatusFieldNames

func ReservedStatusFieldNames() map[string]bool

func SetAnnotation

func SetAnnotation(annotation, val string, obj metav1.Object)

func SetDefaultContainerAnnotation

func SetDefaultContainerAnnotation(obj metav1.Object, ns *corev1.Namespace, containers []corekccv1alpha1.Container) error

func SetDefaultHierarchicalReference

func SetDefaultHierarchicalReference(resource *Resource, ns *corev1.Namespace, hierarchicalRefs []corekccv1alpha1.HierarchicalReference, containers []corekccv1alpha1.Container) error

SetDefaultHierarchicalReference sets a hierarchical reference on the given resource if it doesn't have one. The resulting hierarchical reference is based on whichever of the following is found first: (1) Resource-level container annotations (if supported) (2) Namespace-level container annotations (3) Namespace name (if resource supports project references)

func SetHierarchicalReference

func SetHierarchicalReference(resource *Resource, hierarchicalRef *corekccv1alpha1.HierarchicalReference, externalVal string) error

func SortGVKsByKind

func SortGVKsByKind(gvks []schema.GroupVersionKind) []schema.GroupVersionKind

func ToGVR added in v1.90.0

ToGVR returns the equivalent GVR for a given GVK. Note that while GVKs and GVRs do not necessarily have a 1:1 mapping, GVKs and GVRs of CRDs do. (see https://book.kubebuilder.io/cronjob-tutorial/gvks.html#kinds-and-resources)

func TriggerManagedFieldsMetadata

func TriggerManagedFieldsMetadata(ctx context.Context, c client.Client, u *unstructured.Unstructured) (
	*unstructured.Unstructured, error)

TriggerManagedFieldsMetadata ensures that managed fields metadata is present on the given resource for Server-Side Apply (SSA) compatible clusters.

func UpdateOrRemoveObservedSecretVersionsAnnotation

func UpdateOrRemoveObservedSecretVersionsAnnotation(resource *Resource, secretVersions map[string]string, hasSensitiveFields bool) error

func ValidateOrDefaultManagementConflictPreventionAnnotationForDCLBasedResource

func ValidateOrDefaultManagementConflictPreventionAnnotationForDCLBasedResource(obj metav1.Object, ns *corev1.Namespace, schema *openapi.Schema) error

func ValidateOrDefaultManagementConflictPreventionAnnotationForTFBasedResource

func ValidateOrDefaultManagementConflictPreventionAnnotationForTFBasedResource(obj metav1.Object, ns *corev1.Namespace, rc *corekccv1alpha1.ResourceConfig, tfResourceMap map[string]*tfschema.Resource) error

func ValidateOrDefaultStateIntoSpecAnnotation

func ValidateOrDefaultStateIntoSpecAnnotation(obj *unstructured.Unstructured) error

func ValueToDNSSubdomainName

func ValueToDNSSubdomainName(value string) string

Types

type ErrorWithReason

type ErrorWithReason struct {
	Message string
	Reason  string
}

func (ErrorWithReason) Error

func (e ErrorWithReason) Error() string

type ImmutableFieldsMutationError

type ImmutableFieldsMutationError struct {
	// contains filtered or unexported fields
}

func NewImmutableFieldsMutationError

func NewImmutableFieldsMutationError(immutableFields []string) *ImmutableFieldsMutationError

func (*ImmutableFieldsMutationError) Error

type KeyInSecretNotFoundError

type KeyInSecretNotFoundError struct {
	// contains filtered or unexported fields
}

func AsKeyInSecretNotFoundError

func AsKeyInSecretNotFoundError(err error) (unwrappedErr *KeyInSecretNotFoundError, ok bool)

func NewKeyInSecretNotFoundError

func NewKeyInSecretNotFoundError(key string, secret types.NamespacedName) *KeyInSecretNotFoundError

func (*KeyInSecretNotFoundError) Error

func (e *KeyInSecretNotFoundError) Error() string

type ManagementConflictPreventionPolicy

type ManagementConflictPreventionPolicy string

func GetManagementConflictPreventionAnnotationValue

func GetManagementConflictPreventionAnnotationValue(obj metav1.Object) (ManagementConflictPreventionPolicy, error)

type ReferenceNotFoundError

type ReferenceNotFoundError struct {
	RefResourceGVK schema.GroupVersionKind
	RefResource    types.NamespacedName
}

func AsReferenceNotFoundError

func AsReferenceNotFoundError(err error) (unwrappedErr *ReferenceNotFoundError, ok bool)

func NewReferenceNotFoundError

func NewReferenceNotFoundError(refResourceGVK schema.GroupVersionKind, refResource types.NamespacedName) *ReferenceNotFoundError

func NewReferenceNotFoundErrorForResource

func NewReferenceNotFoundErrorForResource(r *Resource) *ReferenceNotFoundError

func (*ReferenceNotFoundError) Error

func (e *ReferenceNotFoundError) Error() string

type ReferenceNotReadyError

type ReferenceNotReadyError struct {
	RefResourceGVK schema.GroupVersionKind
	RefResource    types.NamespacedName
}

func AsReferenceNotReadyError

func AsReferenceNotReadyError(err error) (unwrappedErr *ReferenceNotReadyError, ok bool)

func NewReferenceNotReadyErrorForResource

func NewReferenceNotReadyErrorForResource(r *Resource) *ReferenceNotReadyError

func (*ReferenceNotReadyError) Error

func (e *ReferenceNotReadyError) Error() string

type Resource

type Resource struct {
	// Fundamental fields
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty"`
	Spec              map[string]interface{} `json:"spec,omitempty"`
	Status            map[string]interface{} `json:"status,omitempty"`

	// ManagedFields is the set of spec fields whose desired state is managed
	// by Kubernetes. Fields that are not part of this set are considered
	// unmanaged, and their values in etcd will be updated to match the
	// underlying API.
	//
	// If this object is nil, all fields in the spec in etcd are considered
	// managed and their values will be constantly enforced.
	ManagedFields *fieldpath.Set `json:"-"`
}

Resource represents a resource in KRM

func GetReferencedResource

func GetReferencedResource(resourceRef *corekccv1alpha1.ResourceReference, gvk schema.GroupVersionKind, resourceNamespace string, kubeClient client.Client) (*Resource, error)

func GetReferencedResourceIfReady

func GetReferencedResourceIfReady(resourceRef *corekccv1alpha1.ResourceReference, gvk schema.GroupVersionKind, resourceNamespace string, kubeClient client.Client) (*Resource, error)

func NewResource

func NewResource(u *unstructured.Unstructured) (*Resource, error)

NewResource creates a Resource based on the given unstructured. NewResource can be used to create deep copies of a Resource by calling NewResource multiple times on the same unstructured since the Resource objects created are separate copies.

func (*Resource) GetNamespacedName

func (r *Resource) GetNamespacedName() types.NamespacedName

func (*Resource) HasResourceIDField

func (r *Resource) HasResourceIDField() bool

func (*Resource) IsResourceIDConfigured

func (r *Resource) IsResourceIDConfigured() (bool, error)

func (*Resource) MarshalAsUnstructured

func (r *Resource) MarshalAsUnstructured() (*unstructured.Unstructured, error)

type ResourceIDNotFoundError

type ResourceIDNotFoundError struct {
	// contains filtered or unexported fields
}

func AsResourceIDNotFoundError

func AsResourceIDNotFoundError(err error) (unwrappedErr *ResourceIDNotFoundError, ok bool)

func NewResourceIDNotFoundError

func NewResourceIDNotFoundError(resourceGVK schema.GroupVersionKind, resource types.NamespacedName) *ResourceIDNotFoundError

func (*ResourceIDNotFoundError) Error

func (e *ResourceIDNotFoundError) Error() string

type SecretNotFoundError

type SecretNotFoundError struct {
	// contains filtered or unexported fields
}

func AsSecretNotFoundError

func AsSecretNotFoundError(err error) (unwrappedErr *SecretNotFoundError, ok bool)

func NewSecretNotFoundError

func NewSecretNotFoundError(secret types.NamespacedName) *SecretNotFoundError

func (*SecretNotFoundError) Error

func (e *SecretNotFoundError) Error() string

type ServerGeneratedIDNotFoundError

type ServerGeneratedIDNotFoundError struct {
	// contains filtered or unexported fields
}

func AsServerGeneratedIDNotFoundError

func AsServerGeneratedIDNotFoundError(err error) (unwrappedErr *ServerGeneratedIDNotFoundError, ok bool)

func NewServerGeneratedIDNotFoundError

func NewServerGeneratedIDNotFoundError(resourceGVK schema.GroupVersionKind, resource types.NamespacedName) *ServerGeneratedIDNotFoundError

func (*ServerGeneratedIDNotFoundError) Error

type TransitiveDependencyNotFoundError

type TransitiveDependencyNotFoundError struct {
	ResourceGVK schema.GroupVersionKind
	Resource    types.NamespacedName
}

func AsTransitiveDependencyNotFoundError

func AsTransitiveDependencyNotFoundError(err error) (unwrappedErr *TransitiveDependencyNotFoundError, ok bool)

func NewTransitiveDependencyNotFoundError

func NewTransitiveDependencyNotFoundError(resourceGVK schema.GroupVersionKind, resource types.NamespacedName) *TransitiveDependencyNotFoundError

func (*TransitiveDependencyNotFoundError) Error

type TransitiveDependencyNotReadyError

type TransitiveDependencyNotReadyError struct {
	ResourceGVK schema.GroupVersionKind
	Resource    types.NamespacedName
}

func AsTransitiveDependencyNotReadyError

func AsTransitiveDependencyNotReadyError(err error) (unwrappedErr *TransitiveDependencyNotReadyError, ok bool)

func NewTransitiveDependencyNotReadyError

func NewTransitiveDependencyNotReadyError(resourceGVK schema.GroupVersionKind, resource types.NamespacedName) *TransitiveDependencyNotReadyError

func (*TransitiveDependencyNotReadyError) Error

Jump to

Keyboard shortcuts

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