util

package
v1.8.7 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2024 License: Apache-2.0 Imports: 52 Imported by: 10

Documentation

Index

Constants

View Source
const (
	// NamespaceClusterLease is the namespace which cluster lease are stored.
	NamespaceClusterLease = "karmada-cluster"
	// KubeCredentials is the secret that contains mandatory credentials whether reported when registering cluster
	KubeCredentials = "KubeCredentials"
	// KubeImpersonator is the secret that contains the token of impersonator whether reported when registering cluster
	KubeImpersonator = "KubeImpersonator"
	// None is means don't report any secrets.
	None = "None"
)
View Source
const (
	// ServiceNamespaceLabel is added to work object, which is report by member cluster, to specify service namespace associated with EndpointSlice.
	ServiceNamespaceLabel = "endpointslice.karmada.io/namespace"

	// ServiceNameLabel is added to work object, which is report by member cluster, to specify service name associated with EndpointSlice.
	ServiceNameLabel = "endpointslice.karmada.io/name"

	// MultiClusterServiceNamespaceLabel is added to work object, represents the work is managed by the corresponding MultiClusterService
	// This label indicates the namepsace
	MultiClusterServiceNamespaceLabel = "multiclusterservice.karmada.io/namespace"

	// MultiClusterServiceNameLabel is added to work object, represents the work is managed by the corresponding MultiClusterService
	// This label indicates the name
	MultiClusterServiceNameLabel = "multiclusterservice.karmada.io/name"

	// EndPointSliceProvisionClusterAnnotation is added to EndpointSlice to specify the cluster which cluster provides the EndpointSlice.
	EndpointSliceProvisionClusterAnnotation = "endpointslice.karmada.io/provision-cluster"

	// EndPointSliceProvisionGenerationAnnotation is added to EndpointSlice to specify the generation of EndpointSlice of the provision cluster.
	EndPointSliceProvisionGenerationAnnotation = "endpointslice.karmada.io/endpointslice-generation"

	// PropagationInstruction is used to mark a resource(like Work) propagation instruction.
	// Valid values includes:
	// - suppressed: indicates that the resource should not be propagated.
	//
	// Note: This instruction is intended to set on Work objects to indicate the Work should be ignored by
	// execution controller. The instruction maybe deprecated once we extend the Work API and no other scenario want this.
	PropagationInstruction = "propagation.karmada.io/instruction"

	// FederatedResourceQuotaNamespaceLabel is added to Work to specify associated FederatedResourceQuota's namespace.
	FederatedResourceQuotaNamespaceLabel = "federatedresourcequota.karmada.io/namespace"

	// FederatedResourceQuotaNameLabel is added to Work to specify associated FederatedResourceQuota's name.
	FederatedResourceQuotaNameLabel = "federatedresourcequota.karmada.io/name"

	// ManagedByKarmadaLabel is a reserved karmada label to indicate whether resources are managed by karmada controllers.
	ManagedByKarmadaLabel = "karmada.io/managed"

	// ManagedByKarmadaLabelValue indicates that resources are managed by karmada controllers.
	ManagedByKarmadaLabelValue = "true"

	// EndpointSliceDispatchControllerLabelValue indicates the endpointSlice are controlled by Karmada
	EndpointSliceDispatchControllerLabelValue = "endpointslice-dispatch-controller.karmada.io"

	// RetainReplicasLabel is a reserved label to indicate whether the replicas should be retained. e.g:
	// resourcetemplate.karmada.io/retain-replicas: true   // with value `true` indicates retain
	// resourcetemplate.karmada.io/retain-replicas: false  // with value `false` and others, indicates not retain
	RetainReplicasLabel = "resourcetemplate.karmada.io/retain-replicas"

	// RetainReplicasValue is an optional value of RetainReplicasLabel, indicating retain
	RetainReplicasValue = "true"
)
View Source
const (
	// PolicyPlacementAnnotation is the annotation of a policy's placement.
	// It is intended to set on ResourceBinding or ClusterResourceBinding objects to record applied placement declaration.
	// The placement could be either PropagationPolicy's or ClusterPropagationPolicy's.
	PolicyPlacementAnnotation = "policy.karmada.io/applied-placement"

	// AppliedOverrides is the annotation which used to record override items an object applied.
	// It is intended to set on Work objects to record applied overrides.
	// The overrides items should be sorted alphabetically in ascending order by OverridePolicy's name.
	AppliedOverrides = "policy.karmada.io/applied-overrides"

	// AppliedClusterOverrides is the annotation which used to record override items an object applied.
	// It is intended to set on Work objects to record applied overrides.
	// The overrides items should be sorted alphabetically in ascending order by ClusterOverridePolicy's name.
	AppliedClusterOverrides = "policy.karmada.io/applied-cluster-overrides"
)

Define annotations used by karmada system.

View Source
const (
	// ClusterControllerFinalizer is added to Cluster to ensure Work as well as the
	// execution space (namespace) is deleted before itself is deleted.
	ClusterControllerFinalizer = "karmada.io/cluster-controller"

	// ExecutionControllerFinalizer is added to Work to ensure manifests propagated to member cluster
	// is deleted before Work itself is deleted.
	ExecutionControllerFinalizer = "karmada.io/execution-controller"

	// BindingControllerFinalizer is added to ResourceBinding to ensure related Works are deleted
	// before ResourceBinding itself is deleted.
	BindingControllerFinalizer = "karmada.io/binding-controller"

	// MCSEndpointSliceCollectControllerFinalizer is added to mcs to ensure related Works in provision clusters are deleted
	MCSEndpointSliceCollectControllerFinalizer = "karmada.io/mcs-endpointslice-collect-controller"

	// MCSEndpointSliceDispatchControllerFinalizer is added to mcs to ensure related Works in consumption clusters are deleted
	MCSEndpointSliceDispatchControllerFinalizer = "karmada.io/mcs-endpointslice-dispatch-controller"

	// ClusterResourceBindingControllerFinalizer is added to ClusterResourceBinding to ensure related Works are deleted
	// before ClusterResourceBinding itself is deleted.
	ClusterResourceBindingControllerFinalizer = "karmada.io/cluster-resource-binding-controller"

	// MCSControllerFinalizer is added to Cluster to ensure service work is deleted before itself is deleted.
	MCSControllerFinalizer = "karmada.io/multiclusterservice-controller"
)

Define finalizers used by karmada system.

View Source
const (
	// ProviderField indicates the 'provider' field of a cluster
	ProviderField = "provider"
	// RegionField indicates the 'region' field of a cluster
	RegionField = "region"
	// ZoneField indicates the 'zone' field of a cluster
	ZoneField = "zone"
)
View Source
const (
	// DeploymentKind indicates the target resource is a deployment
	DeploymentKind = "Deployment"
	// ServiceKind indicates the target resource is a service
	ServiceKind = "Service"
	// IngressKind indicates the target resource is a ingress
	IngressKind = "Ingress"
	// CronJobKind indicates the target resource is a cronjob
	CronJobKind = "CronJob"
	// JobKind indicates the target resource is a job
	JobKind = "Job"
	// PodKind indicates the target resource is a pod
	PodKind = "Pod"
	// ServiceAccountKind indicates the target resource is a serviceaccount
	ServiceAccountKind = "ServiceAccount"
	// ReplicaSetKind indicates the target resource is a replicaset
	ReplicaSetKind = "ReplicaSet"
	// StatefulSetKind indicates the target resource is a statefulset
	StatefulSetKind = "StatefulSet"
	// DaemonSetKind indicates the target resource is a daemonset
	DaemonSetKind = "DaemonSet"
	// EndpointSliceKind indicates the target resource is a endpointslice
	EndpointSliceKind = "EndpointSlice"
	// PersistentVolumeClaimKind indicated the target resource is a persistentvolumeclaim
	PersistentVolumeClaimKind = "PersistentVolumeClaim"
	// PersistentVolumeKind indicates the target resource is a persistentvolume
	PersistentVolumeKind = "PersistentVolume"
	// HorizontalPodAutoscalerKind indicates the target resource is a horizontalpodautoscaler
	HorizontalPodAutoscalerKind = "HorizontalPodAutoscaler"
	// PodDisruptionBudgetKind indicates the target resource is a poddisruptionbudget
	PodDisruptionBudgetKind = "PodDisruptionBudget"

	// ServiceExportKind indicates the target resource is a serviceexport crd
	ServiceExportKind = "ServiceExport"
	// ServiceImportKind indicates the target resource is a serviceimport crd
	ServiceImportKind = "ServiceImport"

	// CRDKind indicated the target resource is a CustomResourceDefinition
	CRDKind = "CustomResourceDefinition"

	// ClusterRoleKind indicates the target resource is a clusterrole
	ClusterRoleKind = "ClusterRole"
	// ClusterRoleBindingKind indicates the target resource is a clusterrolebinding
	ClusterRoleBindingKind = "ClusterRoleBinding"
)

Define resource kind.

View Source
const (
	// SpecField indicates the 'spec' field of a resource
	SpecField = "spec"
	// ReplicasField indicates the 'replicas' field of a resource
	ReplicasField = "replicas"
	// ReadyReplicasField indicates the 'readyReplicas' field of a resource status
	ReadyReplicasField = "readyReplicas"
	// ParallelismField indicates the 'parallelism' field of a job
	ParallelismField = "parallelism"
	// CompletionsField indicates the 'completions' field of a job
	CompletionsField = "completions"
	// TemplateField indicates the 'template' field of a resource
	TemplateField = "template"
)

Define resource filed

View Source
const (
	// CacheSyncTimeout refers to the time limit set on waiting for cache to sync
	CacheSyncTimeout = 2 * time.Minute
)
View Source
const (
	// NamespaceKarmadaSystem is the karmada system namespace.
	NamespaceKarmadaSystem = "karmada-system"
)
View Source
const (
	// PropagationInstructionSuppressed indicates that the resource should not be propagated.
	PropagationInstructionSuppressed = "suppressed"
)

Variables

View Source
var (

	// ClusterPolicyRules represents cluster policy rules
	ClusterPolicyRules = []rbacv1.PolicyRule{
		namespacedPolicyRules[0],
		{
			NonResourceURLs: []string{rbacv1.NonResourceAll},
			Verbs:           []string{"get"},
		},
	}
)

Functions

func BuildClusterConfig added in v1.4.0

func BuildClusterConfig(clusterName string,
	clusterGetter func(string) (*clusterv1alpha1.Cluster, error),
	secretGetter func(string, string) (*corev1.Secret, error)) (*rest.Config, error)

BuildClusterConfig return rest config for member cluster.

func BuildClusterRoleReference added in v1.3.0

func BuildClusterRoleReference(roleName string) rbacv1.RoleRef

BuildClusterRoleReference will generate a ClusterRole reference.

func BuildRoleBindingSubjects added in v1.3.0

func BuildRoleBindingSubjects(serviceAccountName, serviceAccountNamespace string) []rbacv1.Subject

BuildRoleBindingSubjects will generate a subject as per service account. The subject used by RoleBinding or ClusterRoleBinding.

func ClusterAccessCredentialChanged added in v1.6.0

func ClusterAccessCredentialChanged(newSpec, oldSpec clusterv1alpha1.ClusterSpec) bool

ClusterAccessCredentialChanged checks whether the cluster access credential changed

func ClusterMatches added in v0.3.0

func ClusterMatches(cluster *clusterv1alpha1.Cluster, affinity policyv1alpha1.ClusterAffinity) bool

ClusterMatches tells if specific cluster matches the affinity.

func ClusterNamesMatches added in v0.3.0

func ClusterNamesMatches(cluster *clusterv1alpha1.Cluster, clusterNames []string) bool

ClusterNamesMatches tells if specific cluster matches the clusterNames affinity.

func ContextForChannel added in v0.8.0

func ContextForChannel(parentCh <-chan struct{}) (context.Context, context.CancelFunc)

ContextForChannel derives a child context from a parent channel.

The derived context's Done channel is closed when the returned cancel function is called or when the parent channel is closed, whichever happens first.

Note the caller must *always* call the CancelFunc, otherwise resources may be leaked.

func ConvertToClusterNames added in v0.8.0

func ConvertToClusterNames(clusters []workv1alpha2.TargetCluster) sets.Set[string]

ConvertToClusterNames will convert a cluster slice to clusterName's sets.String

func CreateClusterObject added in v1.0.0

func CreateClusterObject(controlPlaneClient karmadaclientset.Interface, clusterObj *clusterv1alpha1.Cluster) (*clusterv1alpha1.Cluster, error)

CreateClusterObject create cluster object in karmada control plane

func CreateClusterRole

func CreateClusterRole(client kubeclient.Interface, clusterRoleObj *rbacv1.ClusterRole) (*rbacv1.ClusterRole, error)

CreateClusterRole just try to create the ClusterRole.

func CreateClusterRoleBinding

func CreateClusterRoleBinding(client kubeclient.Interface, clusterRoleBindingObj *rbacv1.ClusterRoleBinding) (*rbacv1.ClusterRoleBinding, error)

CreateClusterRoleBinding just try to create the ClusterRoleBinding.

func CreateNamespace

func CreateNamespace(client kubeclient.Interface, namespaceObj *corev1.Namespace) (*corev1.Namespace, error)

CreateNamespace just try to create the namespace.

func CreateOrUpdateClusterObject added in v1.0.0

func CreateOrUpdateClusterObject(controlPlaneClient karmadaclientset.Interface, clusterObj *clusterv1alpha1.Cluster, mutate func(*clusterv1alpha1.Cluster)) (*clusterv1alpha1.Cluster, error)

CreateOrUpdateClusterObject create cluster object in karmada control plane, if cluster object has been existed and different from input clusterObj, update it.

func CreateSecret

func CreateSecret(client kubeclient.Interface, secret *corev1.Secret) (*corev1.Secret, error)

CreateSecret just try to create the secret.

func CreateServiceAccount

func CreateServiceAccount(client kubeclient.Interface, saObj *corev1.ServiceAccount) (*corev1.ServiceAccount, error)

CreateServiceAccount just try to create the ServiceAccount.

func DedupeAndMergeAnnotations added in v1.7.0

func DedupeAndMergeAnnotations(existAnnotation, newAnnotation map[string]string) map[string]string

DedupeAndMergeAnnotations merges the new annotations into exist annotations.

func DedupeAndMergeLabels added in v1.1.0

func DedupeAndMergeLabels(existLabel, newLabel map[string]string) map[string]string

DedupeAndMergeLabels merges the new labels into exist labels.

func DeleteClusterRole

func DeleteClusterRole(client kubeclient.Interface, name string) error

DeleteClusterRole just try to delete the ClusterRole.

func DeleteClusterRoleBinding

func DeleteClusterRoleBinding(client kubeclient.Interface, name string) error

DeleteClusterRoleBinding just try to delete the ClusterRoleBinding.

func DeleteNamespace

func DeleteNamespace(client kubeclient.Interface, namespace string) error

DeleteNamespace just try to delete the namespace.

func DeleteServiceAccount

func DeleteServiceAccount(client kubeclient.Interface, namespace, name string) error

DeleteServiceAccount just try to delete the ServiceAccount.

func Dial added in v0.9.0

func Dial(path string, timeout time.Duration) (*grpc.ClientConn, error)

Dial establishes the gRPC communication.

func DiffKey added in v1.7.0

func DiffKey[K comparable, V1, V2 any](previous map[K]V1, current map[K]V2) (added, removed []K)

DiffKey compares keys of two map with same key type, as the name of return values told, it will find out added keys and removed keys.

func EnsureClusterRoleBindingExist added in v1.3.0

func EnsureClusterRoleBindingExist(client kubeclient.Interface, clusterRoleBinding *rbacv1.ClusterRoleBinding, dryRun bool) (*rbacv1.ClusterRoleBinding, error)

EnsureClusterRoleBindingExist makes sure that the specific ClusterRoleBinding exist in cluster. If ClusterRoleBinding not exit, just create it.

func EnsureClusterRoleExist added in v1.3.0

func EnsureClusterRoleExist(client kubeclient.Interface, clusterRole *rbacv1.ClusterRole, dryRun bool) (*rbacv1.ClusterRole, error)

EnsureClusterRoleExist makes sure that the specific cluster role exist in cluster. If cluster role not exit, just create it.

func EnsureNamespaceExist added in v1.0.0

func EnsureNamespaceExist(client kubeclient.Interface, namespace string, dryRun bool) (*corev1.Namespace, error)

EnsureNamespaceExist makes sure that the specific namespace exist in cluster. If namespace not exit, just create it.

func EnsureNamespaceExistWithLabels added in v1.7.0

func EnsureNamespaceExistWithLabels(client kubeclient.Interface, namespace string, dryRun bool, labels map[string]string) (*corev1.Namespace, error)

EnsureNamespaceExistWithLabels makes sure that the specific namespace exist in cluster. If namespace not exit, just create it with specific labels.

func EnsureServiceAccountExist added in v1.0.0

func EnsureServiceAccountExist(client kubeclient.Interface, serviceAccountObj *corev1.ServiceAccount, dryRun bool) (*corev1.ServiceAccount, error)

EnsureServiceAccountExist makes sure that the specific service account exist in cluster. If service account not exit, just create it.

func GenerateImpersonationRules added in v1.0.0

func GenerateImpersonationRules(subjects []rbacv1.Subject) []rbacv1.PolicyRule

GenerateImpersonationRules generate PolicyRules from given subjects for impersonation.

func GetAnnotationValue added in v1.0.0

func GetAnnotationValue(annotations map[string]string, annotationKey string) string

GetAnnotationValue retrieves the value via 'annotationKey' (if it exists), otherwise an empty string is returned.

func GetBindingClusterNames added in v0.3.0

func GetBindingClusterNames(spec *workv1alpha2.ResourceBindingSpec) []string

GetBindingClusterNames will get clusterName list from bind clusters field

func GetCluster added in v0.3.0

func GetCluster(hostClient client.Client, clusterName string) (*clusterv1alpha1.Cluster, error)

GetCluster returns the given Cluster resource

func GetClusterSet added in v1.8.0

func GetClusterSet(hostClient client.Client) (sets.Set[string], error)

GetClusterWithKubeClient returns the given Clusters name set

func GetClusterWithKarmadaClient added in v1.0.0

func GetClusterWithKarmadaClient(client karmadaclientset.Interface, name string) (*clusterv1alpha1.Cluster, bool, error)

GetClusterWithKarmadaClient tells if a cluster already joined to control plane.

func GetLabelValue

func GetLabelValue(labels map[string]string, labelKey string) string

GetLabelValue retrieves the value via 'labelKey' if exist, otherwise returns an empty string.

func GetSecret added in v1.0.5

func GetSecret(client kubeclient.Interface, namespace, name string) (*corev1.Secret, error)

GetSecret just try to get the secret.

func GetSumOfReplicas added in v0.8.0

func GetSumOfReplicas(clusters []workv1alpha2.TargetCluster) int32

GetSumOfReplicas will get the sum of replicas in target clusters

func IsBindingReplicasChanged added in v0.8.0

func IsBindingReplicasChanged(bindingSpec *workv1alpha2.ResourceBindingSpec, strategy *policyv1alpha1.ReplicaSchedulingStrategy) bool

IsBindingReplicasChanged will check if the sum of replicas is different from the replicas of object

func IsClusterIdentifyUnique added in v1.3.0

func IsClusterIdentifyUnique(controlPlaneClient karmadaclientset.Interface, id string) (bool, string, error)

IsClusterIdentifyUnique checks whether the ClusterID exists in the karmada control plane.

func IsClusterReady added in v0.3.0

func IsClusterReady(clusterStatus *clusterv1alpha1.ClusterStatus) bool

IsClusterReady tells whether the cluster status in 'Ready' condition.

func IsClusterRoleBindingExist

func IsClusterRoleBindingExist(client kubeclient.Interface, name string) (bool, error)

IsClusterRoleBindingExist tells if specific ClusterRole already exists.

func IsClusterRoleExist

func IsClusterRoleExist(client kubeclient.Interface, name string) (bool, error)

IsClusterRoleExist tells if specific ClusterRole already exists.

func IsConditionsEqual added in v1.0.0

func IsConditionsEqual(newCondition, oldCondition metav1.Condition) bool

IsConditionsEqual compares the given condition's Status, Reason and Message.

func IsNamespaceExist

func IsNamespaceExist(client kubeclient.Interface, namespace string) (bool, error)

IsNamespaceExist tells if the namespace already exists.

func IsServiceAccountExist

func IsServiceAccountExist(client kubeclient.Interface, namespace string, name string) (bool, error)

IsServiceAccountExist tells if specific service account already exists.

func Keys added in v1.7.0

func Keys[K comparable, V any](m map[K]V) []K

Keys return slice of keys of the given map

func MaxInt64 added in v1.4.0

func MaxInt64(a, b int64) int64

MaxInt64 returns the largest of two int64 numbers.

func MergeAnnotation added in v0.3.0

func MergeAnnotation(obj *unstructured.Unstructured, annotationKey string, annotationValue string)

MergeAnnotation adds annotation for the given object, keep the value unchanged if key exist.

func MergeLabel

func MergeLabel(obj *unstructured.Unstructured, labelKey string, labelValue string)

MergeLabel adds label for the given object.

func MergeTargetClusters added in v0.10.0

func MergeTargetClusters(old, new []workv1alpha2.TargetCluster) []workv1alpha2.TargetCluster

MergeTargetClusters will merge the replicas in two TargetCluster

func MinInt64 added in v0.9.0

func MinInt64(a, b int64) int64

MinInt64 returns the smaller of two int64 numbers.

func NewCondition added in v1.0.0

func NewCondition(conditionType, reason, message string, status metav1.ConditionStatus) metav1.Condition

NewCondition returns a new condition object.

func NewProxyHeaderRoundTripperWrapperConstructor added in v1.7.0

func NewProxyHeaderRoundTripperWrapperConstructor(wt transport.WrapperFunc, headers map[string]string) transport.WrapperFunc

NewProxyHeaderRoundTripperWrapperConstructor returns a RoundTripper wrapper that's usable within restConfig.WrapTransport.

func ObtainClusterID added in v1.3.0

func ObtainClusterID(clusterKubeClient kubernetes.Interface) (string, error)

ObtainClusterID returns the cluster ID property with clusterKubeClient

func ObtainCredentialsFromMemberCluster added in v1.3.0

func ObtainCredentialsFromMemberCluster(clusterKubeClient kubeclient.Interface, opts ClusterRegisterOption) (*corev1.Secret, *corev1.Secret, error)

ObtainCredentialsFromMemberCluster obtain credentials for member cluster

func PatchSecret

func PatchSecret(client kubeclient.Interface, namespace, name string, pt types.PatchType, patchSecretBody *corev1.Secret) error

PatchSecret just try to patch the secret.

func PolicyRuleAPIGroupMatches added in v1.0.0

func PolicyRuleAPIGroupMatches(rule *rbacv1.PolicyRule, requestedGroup string) bool

PolicyRuleAPIGroupMatches determines if the given policy rule is applied for requested group.

func PolicyRuleResourceMatches added in v1.0.0

func PolicyRuleResourceMatches(rule *rbacv1.PolicyRule, requestedResource string) bool

PolicyRuleResourceMatches determines if the given policy rule is applied for requested resource.

func PolicyRuleResourceNameMatches added in v1.0.0

func PolicyRuleResourceNameMatches(rule *rbacv1.PolicyRule, requestedName string) bool

PolicyRuleResourceNameMatches determines if the given policy rule is applied for named resource.

func RecordManagedAnnotations added in v1.5.0

func RecordManagedAnnotations(object *unstructured.Unstructured)

RecordManagedAnnotations sets or updates the annotation(resourcetemplate.karmada.io/managed-annotations) to record the annotation keys.

func RecordManagedLabels added in v1.5.0

func RecordManagedLabels(object *unstructured.Unstructured)

RecordManagedLabels sets or updates the annotation(resourcetemplate.karmada.io/managed-labels) to record the label keys.

func RegisterClusterInControllerPlane added in v1.3.0

func RegisterClusterInControllerPlane(opts ClusterRegisterOption, controlPlaneKubeClient kubeclient.Interface, generateClusterInControllerPlane generateClusterInControllerPlaneFunc) error

RegisterClusterInControllerPlane represents register cluster in controller plane

func RemoveLabels added in v1.4.5

func RemoveLabels(obj *unstructured.Unstructured, labelKeys ...string)

RemoveLabels removes the labels from the given object.

func ReplaceAnnotation added in v1.7.0

func ReplaceAnnotation(obj *unstructured.Unstructured, annotationKey string, annotationValue string)

ReplaceAnnotation adds annotation for the given object, replace the value if key exist.

func ResourceMatchSelectors added in v0.5.0

func ResourceMatchSelectors(resource *unstructured.Unstructured, selectors ...policyv1alpha1.ResourceSelector) bool

ResourceMatchSelectors tells if the specific resource matches the selectors.

func ResourceMatches added in v0.3.0

func ResourceMatches(resource *unstructured.Unstructured, rs policyv1alpha1.ResourceSelector) bool

ResourceMatches tells if the specific resource matches the selector.

func RetainAnnotations added in v1.5.0

func RetainAnnotations(desired *unstructured.Unstructured, observed *unstructured.Unstructured)

RetainAnnotations merges the annotations that added by controllers running in member cluster to avoid overwriting. Following keys will be ignored if :

  • the keys were previous propagated to member clusters(that are tracked by "resourcetemplate.karmada.io/managed-annotations" annotation in observed) but have been removed from Karmada control plane(don't exist in desired anymore).
  • the keys that exist in both desired and observed even those been accidentally modified in member clusters.

func RetainLabels added in v1.5.0

func RetainLabels(desired *unstructured.Unstructured, observed *unstructured.Unstructured)

RetainLabels merges the labels that added by controllers running in member cluster to avoid overwriting. Following keys will be ignored if :

  • the keys were previous propagated to member clusters(that are tracked by "resourcetemplate.karmada.io/managed-lables" annotation in observed) but have been removed from Karmada control plane(don't exist in desired anymore).
  • the keys that exist in both desired and observed even those been accidentally modified in member clusters.

func SetLeaseOwnerFunc added in v0.7.0

func SetLeaseOwnerFunc(c client.Client, clusterName string) func(lease *coordinationv1.Lease) error

SetLeaseOwnerFunc helps construct a newLeasePostProcessFunc which sets a cluster OwnerReference to the given lease object.

func StringerJoin added in v1.7.0

func StringerJoin[T fmt.Stringer](st []T, sep string) string

StringerJoin acts the same with `strings.Join`, except that it consumes a slice of `fmt.Stringer`. This mainly used for debug purpose, to log some slice of complex object as human-readable string.

func WaitForServiceAccountSecretCreation added in v1.0.0

func WaitForServiceAccountSecretCreation(client kubeclient.Interface, asObj *corev1.ServiceAccount) (*corev1.Secret, error)

WaitForServiceAccountSecretCreation wait the ServiceAccount's secret has been created.

Types

type AsyncWorker

type AsyncWorker interface {
	// Add adds the 'item' to queue immediately(without any delay).
	Add(item interface{})

	// AddAfter adds an item to the workqueue after the indicated duration has passed
	AddAfter(item interface{}, duration time.Duration)

	// Enqueue generates the key of 'obj' according to a 'KeyFunc' then adds the key as an item to queue by 'Add'.
	Enqueue(obj runtime.Object)

	// Run starts a certain number of concurrent workers to reconcile the items and will never stop until 'stopChan'
	// is closed.
	Run(workerNumber int, stopChan <-chan struct{})
}

AsyncWorker maintains a rate limiting queue and the items in the queue will be reconciled by a "ReconcileFunc". The item will be re-queued if "ReconcileFunc" returns an error, maximum re-queue times defined by "maxRetries" above, after that the item will be discarded from the queue.

func NewAsyncWorker

func NewAsyncWorker(opt Options) AsyncWorker

NewAsyncWorker returns a asyncWorker which can process resource periodic.

type ClientOption added in v0.8.0

type ClientOption struct {
	// QPS indicates the maximum QPS to the master from this client.
	// If it's zero, the created RESTClient will use DefaultQPS: 5
	QPS float32

	// Burst indicates the maximum burst for throttle.
	// If it's zero, the created RESTClient will use DefaultBurst: 10.
	Burst int
}

ClientOption holds the attributes that should be injected to a Kubernetes client.

type ClusterClient

type ClusterClient struct {
	KubeClient  *kubeclientset.Clientset
	ClusterName string
}

ClusterClient stands for a cluster Clientset for the given member cluster

func NewClusterClientSet

func NewClusterClientSet(clusterName string, client client.Client, clientOption *ClientOption) (*ClusterClient, error)

NewClusterClientSet returns a ClusterClient for the given member cluster.

func NewClusterClientSetForAgent added in v0.5.0

func NewClusterClientSetForAgent(clusterName string, _ client.Client, clientOption *ClientOption) (*ClusterClient, error)

NewClusterClientSetForAgent returns a ClusterClient for the given member cluster which will be used in karmada agent.

type ClusterRegisterOption added in v1.3.0

type ClusterRegisterOption struct {
	ClusterNamespace   string
	ClusterName        string
	ReportSecrets      []string
	ClusterAPIEndpoint string
	ProxyServerAddress string
	ClusterProvider    string
	ClusterRegion      string
	// Deprecated: Use ClusterZones instead.
	ClusterZone  string
	ClusterZones []string
	DryRun       bool

	ControlPlaneConfig *rest.Config
	ClusterConfig      *rest.Config
	Secret             corev1.Secret
	ImpersonatorSecret corev1.Secret
	ClusterID          string
}

ClusterRegisterOption represents the option for RegistryCluster.

func (ClusterRegisterOption) IsKubeCredentialsEnabled added in v1.3.0

func (r ClusterRegisterOption) IsKubeCredentialsEnabled() bool

IsKubeCredentialsEnabled represents whether report secret

func (ClusterRegisterOption) IsKubeImpersonatorEnabled added in v1.3.0

func (r ClusterRegisterOption) IsKubeImpersonatorEnabled() bool

IsKubeImpersonatorEnabled represents whether report impersonator secret

type ClusterScaleClient added in v1.6.0

type ClusterScaleClient struct {
	KubeClient  *kubeclientset.Clientset
	ScaleClient scale.ScalesGetter
	ClusterName string
}

ClusterScaleClient stands for a cluster ClientSet with scale client for the given member cluster

func NewClusterScaleClientSet added in v1.6.0

func NewClusterScaleClientSet(clusterName string, client client.Client) (*ClusterScaleClient, error)

NewClusterScaleClientSet returns a ClusterScaleClient for the given member cluster.

type ContextKey added in v0.10.0

type ContextKey string

ContextKey is the key of context.

const (
	// ContextKeyObject is the context value key of a resource.
	ContextKeyObject ContextKey = "object"
)

type DynamicClusterClient

type DynamicClusterClient struct {
	DynamicClientSet dynamic.Interface
	ClusterName      string
}

DynamicClusterClient stands for a dynamic client for the given member cluster

func NewClusterDynamicClientSet

func NewClusterDynamicClientSet(clusterName string, client client.Client) (*DynamicClusterClient, error)

NewClusterDynamicClientSet returns a dynamic client for the given member cluster.

func NewClusterDynamicClientSetForAgent added in v0.5.0

func NewClusterDynamicClientSetForAgent(clusterName string, _ client.Client) (*DynamicClusterClient, error)

NewClusterDynamicClientSetForAgent returns a dynamic client for the given member cluster which will be used in karmada agent.

type ImplicitPriority added in v1.4.0

type ImplicitPriority int

ImplicitPriority describes the extent to which a ResourceSelector or a set of ResourceSelectors match resources.

const (
	// PriorityMisMatch means the ResourceSelector does not match the resource.
	PriorityMisMatch ImplicitPriority = iota
	// PriorityMatchAll means the ResourceSelector whose Name and LabelSelector is empty
	// matches the resource.
	PriorityMatchAll
	// PriorityMatchLabelSelector means the LabelSelector of ResourceSelector matches the resource.
	PriorityMatchLabelSelector
	// PriorityMatchName means the Name of ResourceSelector matches the resource.
	PriorityMatchName
)

func ResourceMatchSelectorsPriority added in v1.4.0

func ResourceMatchSelectorsPriority(resource *unstructured.Unstructured, selectors ...policyv1alpha1.ResourceSelector) ImplicitPriority

ResourceMatchSelectorsPriority returns the highest priority between specific resource and the selectors.

func ResourceSelectorPriority added in v1.4.0

func ResourceSelectorPriority(resource *unstructured.Unstructured, rs policyv1alpha1.ResourceSelector) ImplicitPriority

ResourceSelectorPriority tells the priority between the specific resource and the selector.

type KeyFunc added in v0.4.0

type KeyFunc func(obj interface{}) (QueueKey, error)

KeyFunc knows how to make a key from an object. Implementations should be deterministic.

type Options added in v1.2.0

type Options struct {
	// Name is the queue's name that will be used to emit metrics.
	// Defaults to "", which means disable metrics.
	Name               string
	KeyFunc            KeyFunc
	ReconcileFunc      ReconcileFunc
	RateLimiterOptions ratelimiterflag.Options
}

Options are the arguments for creating a new AsyncWorker.

type QueueKey added in v0.4.0

type QueueKey interface{}

QueueKey is the item key that stores in queue. The key could be arbitrary types.

In some cases, people would like store different resources in a same queue, the traditional full-qualified key, such as '<namespace>/<name>', can't distinguish which resource the key belongs to, the key might carry more information of a resource, such as GVK(Group Version Kind), in that cases people need to use self-defined key, e.g. a struct.

func MetaNamespaceKeyFunc added in v1.1.0

func MetaNamespaceKeyFunc(obj interface{}) (QueueKey, error)

MetaNamespaceKeyFunc generates a namespaced key for object.

type ReconcileFunc added in v0.4.0

type ReconcileFunc func(key QueueKey) error

ReconcileFunc knows how to consume items(key) from the queue.

type Resource added in v0.7.0

type Resource struct {
	MilliCPU         int64
	Memory           int64
	EphemeralStorage int64
	AllowedPodNumber int64

	// ScalarResources
	ScalarResources map[corev1.ResourceName]int64
}

Resource is a collection of compute resource.

func EmptyResource added in v0.7.0

func EmptyResource() *Resource

EmptyResource creates an empty resource object and returns.

func NewResource added in v0.9.0

func NewResource(rl corev1.ResourceList) *Resource

NewResource creates a new resource object from resource list.

func (*Resource) Add added in v0.7.0

func (r *Resource) Add(rl corev1.ResourceList)

Add is used to add two resources.

func (*Resource) AddPodRequest added in v0.7.0

func (r *Resource) AddPodRequest(podSpec *corev1.PodSpec) *Resource

AddPodRequest add the effective request resource of a pod to the origin resource. The Pod's effective request is the higher of: - the sum of all app containers(spec.Containers) request for a resource. - the effective init containers(spec.InitContainers) request for a resource. The effective init containers request is the highest request on all init containers.

func (*Resource) AddPodTemplateRequest added in v1.1.0

func (r *Resource) AddPodTemplateRequest(podSpec *corev1.PodSpec) *Resource

AddPodTemplateRequest add the effective request resource of a pod template to the origin resource. If pod container limits are specified, but requests are not, default requests to limits. The code logic is almost the same as kubernetes. https://github.com/kubernetes/kubernetes/blob/f7cdbe2c96cc12101226686df9e9819b4b007c5c/pkg/apis/core/v1/defaults.go#L147-L181

func (*Resource) AddResourcePods added in v0.9.0

func (r *Resource) AddResourcePods(pods int64)

AddResourcePods adds pod resources into the Resource. Notice that a pod request resource list does not contain a request for pod resources, this function helps to add the pod resources.

func (*Resource) AddScalar added in v0.7.0

func (r *Resource) AddScalar(name corev1.ResourceName, quantity int64)

AddScalar adds a resource by a scalar value of this resource.

func (*Resource) Clone added in v1.4.0

func (r *Resource) Clone() *Resource

Clone returns a copy of this resource.

func (*Resource) MaxDivided added in v0.9.0

func (r *Resource) MaxDivided(rl corev1.ResourceList) int64

MaxDivided returns how many replicas that the resource can be divided.

func (*Resource) ResourceList added in v0.7.0

func (r *Resource) ResourceList() corev1.ResourceList

ResourceList returns a resource list of this resource.

func (*Resource) SetMaxResource added in v0.7.0

func (r *Resource) SetMaxResource(rl corev1.ResourceList)

SetMaxResource compares with ResourceList and takes max value for each Resource.

func (*Resource) SetScalar added in v0.7.0

func (r *Resource) SetScalar(name corev1.ResourceName, quantity int64)

SetScalar sets a resource by a scalar value of this resource.

func (*Resource) SubResource added in v1.4.0

func (r *Resource) SubResource(rr *Resource) *Resource

SubResource is used to subtract two resources, if r < rr, set r to zero.

type SkippedResourceConfig added in v0.7.0

type SkippedResourceConfig struct {
	// Groups holds a collection of API group, all resources under this group will be skipped.
	Groups map[string]struct{}
	// GroupVersions holds a collection of API GroupVersion, all resource under this GroupVersion will be skipped.
	GroupVersions map[schema.GroupVersion]struct{}
	// GroupVersionKinds holds a collection of resource that should be skipped.
	GroupVersionKinds map[schema.GroupVersionKind]struct{}
}

SkippedResourceConfig represents the configuration that identifies the API resources should be skipped from propagating.

func NewSkippedResourceConfig added in v0.7.0

func NewSkippedResourceConfig() *SkippedResourceConfig

NewSkippedResourceConfig to create SkippedResourceConfig

func (*SkippedResourceConfig) DisableGroup added in v0.7.0

func (r *SkippedResourceConfig) DisableGroup(g string)

DisableGroup to disable group.

func (*SkippedResourceConfig) DisableGroupVersion added in v1.3.0

func (r *SkippedResourceConfig) DisableGroupVersion(gv schema.GroupVersion)

DisableGroupVersion to disable GroupVersion.

func (*SkippedResourceConfig) DisableGroupVersionKind added in v0.10.0

func (r *SkippedResourceConfig) DisableGroupVersionKind(gvk schema.GroupVersionKind)

DisableGroupVersionKind to disable GroupVersionKind.

func (*SkippedResourceConfig) GroupDisabled added in v0.7.0

func (r *SkippedResourceConfig) GroupDisabled(g string) bool

GroupDisabled returns whether Group is disabled.

func (*SkippedResourceConfig) GroupVersionDisabled added in v0.7.0

func (r *SkippedResourceConfig) GroupVersionDisabled(gv schema.GroupVersion) bool

GroupVersionDisabled returns whether GroupVersion is disabled.

func (*SkippedResourceConfig) GroupVersionKindDisabled added in v0.7.0

func (r *SkippedResourceConfig) GroupVersionKindDisabled(gvk schema.GroupVersionKind) bool

GroupVersionKindDisabled returns whether GroupVersionKind is disabled.

func (*SkippedResourceConfig) Parse added in v0.7.0

func (r *SkippedResourceConfig) Parse(c string) error

Parse parses the --skipped-propagating-apis input.

Directories

Path Synopsis
Package lifted contains the files lifted from other projects.
Package lifted contains the files lifted from other projects.

Jump to

Keyboard shortcuts

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