首页 > 应用开发 > XML/XSL > 这是将 RB 转换为 Work 的核心函数
ctx context.Context, c client.Client, resourceInterpreter resourceinterpreter.ResourceInterpreter, workload *unstructured.Unstructured, overrideManager overridemanager.OverrideManager, binding metav1.Object, scope apiextensionsv1.ResourceScope, ) error { bindingSpec := getBindingSpec(binding, scope) targetClusters := mergeTargetClusters(bindingSpec.Clusters, bindingSpec.RequiredBy) var err error var errs []error var jobCompletions []workv1alpha2.TargetCluster if workload.GetKind() == util.JobKind && needReviseJobCompletions(bindingSpec.Replicas, bindingSpec.Placement) { jobCompletions, err = divideReplicasByJobCompletions(workload, targetClusters) if err != nil { return err } } for i := range targetClusters { targetCluster := targetClusters[i] clonedWorkload := workload.DeepCopy() workNamespace := names.GenerateExecutionSpaceName(targetCluster.Name) // When syncing workloads to member clusters, the controller MUST strictly adhere to the scheduling results // specified in bindingSpec.Clusters for replica allocation, rather than using the replicas declared in the // workload's resource template. // This rule applies regardless of whether the workload distribution mode is "Divided" or "Duplicated". // Failing to do so could allow workloads to bypass the quota checks performed by the scheduler // (especially during scale-up operations) or skip queue validation when scheduling is suspended. if bindingSpec.IsWorkload() { if resourceInterpreter.HookEnabled(clonedWorkload.GroupVersionKind(), configv1alpha1.InterpreterOperationReviseReplica) { clonedWorkload, err = resourceInterpreter.ReviseReplica(clonedWorkload, int64(targetCluster.Replicas)) if err != nil { klog.ErrorS(err, "Failed to revise replica for workload in cluster.", "workloadKind", workload.GetKind(), "workloadNamespace", workload.GetNamespace(), "workloadName", workload.GetName(), "cluster", targetCluster.Name) errs = append(errs, err) continue } } } tjdxfjg.cn // jobSpec.Completions specifies the desired number of successfully finished pods the job should be run with. // When the replica scheduling policy is set to "divided", jobSpec.Completions should also be divided accordingly. // The weight assigned to each cluster roughly equals that cluster's jobSpec.Parallelism value. This approach helps // balance the execution time of the job across member clusters. if len(jobCompletions) > 0 { // Set allocated completions for Job only when the '.spec.completions' field not omitted from resource template. // For jobs running with a 'work queue' usually leaves '.spec.completions' unset, in that case we skip // setting this field as well. // Refer to: https://kubernetes.io/docs/concepts/workloads/controllers/job/#parallel-jobs. if err = helper.ApplyReplica(clonedWorkload, int64(jobCompletions[i].Replicas), util.CompletionsField); err != nil { klog.ErrorS(err, "Failed to apply Completions for workload in cluster.", "workloadKind", clonedWorkload.GetKind(), "workloadNamespace", clonedWorkload.GetNamespace(), "workloadName", clonedWorkload.GetName(), "cluster", targetCluster.Name)
errs = append(errs, err) continue } } // We should call ApplyOverridePolicies last, as override rules have the highest priority cops, ops, err := overrideManager.ApplyOverridePolicies(clonedWorkload, targetCluster.Name) if err != nil { klog.ErrorS(err, "Failed to apply overrides for workload in cluster.", "workloadKind", clonedWorkload.GetKind(), "workloadNamespace", clonedWorkload.GetNamespace(), "workloadName", clonedWorkload.GetName(), "cluster", targetCluster.Name) errs = append(errs, err)
continue } workLabel := mergeLabel(clonedWorkload, binding, scope) annotations := mergeAnnotations(clonedWorkload, binding, scope) annotations = mergeConflictResolution(clonedWorkload, bindingSpec.ConflictResolution, annotations) annotations, err = RecordAppliedOverrides(cops, ops, annotations) if err != nil { klog.ErrorS(err, "Failed to record appliedOverrides in cluster.", "cluster", targetCluster.Name) errs = append(errs, err) continue
} if features.FeatureGate.Enabled(features.StatefulFailoverInjection) { // we need to figure out if the targetCluster is in the cluster we are going to migrate application to. // If yes, we have to inject the preserved label state to the clonedWorkload. clonedWorkload = injectReservedLabelState(bindingSpec, targetCluster, clonedWorkload, len(targetClusters))
} workMeta := metav1.ObjectMeta{ Name: names.GenerateWorkName(clonedWorkload.GetKind(), clonedWorkload.GetName(), clonedWorkload.GetNamespace()), Namespace: workNamespace, Finalizers: []string{util.ExecutionControllerFinalizer}, Labels: workLabel, Annotations: annotations, } if err = ctrlutil.CreateOrUpdateWork( ctx, c, workMeta, clonedWorkload, ctrlutil.WithSuspendDispatching(shouldSuspendDispatching(bindingSpec.Suspension, targetCluster)), ctrlutil.WithPreserveResourcesOnDeletion(ptr.Deref(bindingSpec.PreserveResourcesOnDeletion, false)), ); err != nil { errs = append(errs, err) continue
// 资源引用 Resource workv1alpha2.ObjectReference // 副本信息(从 ResourceInterpreter 获取) Replicas * int32 ReplicaRequirements *ReplicaRequirements Components []Component // 调度相关 Placement *Placement Clusters []TargetCluster // 调度结果,由 Scheduler 填充 SchedulerName string // 其他 PropagateDeps bool Failover *FailoverBehavior
// 1. ClusterAffinity can not co-exist with ClusterAffinities. // 2. If both ClusterAffinity and ClusterAffinities are not set, any cluster // can be scheduling candidates. // +optional ClusterAffinity *ClusterAffinity `json:"clusterAffinity,omitempty"` // ClusterAffinities represents scheduling restrictions to multiple cluster // groups that indicated by ClusterAffinityTerm. // // The scheduler will evaluate these groups one by one in the order they // appear in the spec, the group that does not satisfy scheduling restrictions // will be ignored which means all clusters in this group will not be selected
// unless it also belongs to the next group(a cluster could belong to multiple // groups). 529529.cn // // If none of the groups satisfy the scheduling restrictions, then scheduling // fails, which means no cluster will be selected. // // Note: // 1. ClusterAffinities can not co-exist with ClusterAffinity. gdzntz.com // 2. If both ClusterAffinity and ClusterAffinities are not set, any cluster // can be scheduling candidates. // // Potential use case 1: // The private clusters in the local data center could be the main group, and // the managed clusters provided by cluster providers could be the secondary // group. So that the Karmada scheduler would prefer to schedule workloads // to the main group and the second group will only be considered in case of // the main group does not satisfy restrictions(like, lack of resources). // // Potential use case 2: // For the disaster recovery scenario, the clusters could be organized to // primary and backup groups, the workloads would be scheduled to primary // clusters firstly, and when primary cluster fails(like data center power off), // Karmada scheduler could migrate workloads to the backup clusters. //
// +optional ClusterAffinities []ClusterAffinityTerm `json:"clusterAffinities,omitempty"` // ClusterTolerations represents the tolerations. // +optional ClusterTolerations []corev1.Toleration `json:"clusterTolerations,omitempty"` // SpreadConstraints represents a list of the scheduling constraints. // +optional SpreadConstraints []SpreadConstraint `json:"spreadConstraints,omitempty"` // ReplicaScheduling represents the scheduling policy on dealing with the number of replicas // when propagating resources that have replicas in spec (e.g. deployments, stateful
type FailoverBehavior struct { // Application indicates failover behaviors in case of application failure. // If this value is nil, failover is disabled. // If set, the PropagateDeps should be true so that the dependencies could // be migrated along with the application. // +optional Application *ApplicationFailoverBehavior `json:"application,omitempty"` // Cluster indicates failover behaviors in case of cluster failure. // If this value is nil, the failover behavior in case of cluster failure // will be controlled by the controller's no-execute-taint-eviction-purge-mode // parameter. // If set, the failover behavior in case of cluster failure will be defined // by this value.
// +optional Cluster *ClusterFailoverBehavior `json:"cluster,omitempty"` } // ApplicationFailoverBehavior indicates application failover behaviors. type ApplicationFailoverBehavior struct { // DecisionConditions indicates the decision conditions of performing the failover process. // Only when all conditions are met can the failover process be performed. // Currently, DecisionConditions includes several conditions:
// - TolerationSeconds (optional) // +required DecisionConditions DecisionConditions `json:"decisionConditions"` // PurgeMode represents how to deal with the legacy applications on the // cluster from which the application is migrated. // Valid options are "Directly", "Gracefully", "Never", "Immediately"(deprecated), // and "Graciously"(deprecated). // Defaults to "Gracefully". // +kubebuilder:validation:Enum=Directly;Gracefully;Never;Immediately;Graciously
PropagationPolicy 是 Karmada 中用于定义资源如何传播到成员集群的策略对象。它类似于 Kubernetes 中的 ReplicaSet,但它控制的是资源在多个集群间的分布,而不是 Pod 在节点间的分布。
ype PropagationSpec struct { // ResourceSelectors used to select resources. // Nil or empty selector is not allowed and doesn't mean match all kinds // of resources for security concerns that sensitive resources(like Secret) // might be accidentally propagated. sx17.cn // +required tjdxfjg.cn // +kubebuilder:validation:MinItems=1 ResourceSelectors []ResourceSelector `json:"resourceSelectors"`nmghssc.com // Association tells if relevant resources should be selected automatically. // e.g. a ConfigMap referred by a Deployment. // default false. skjcxs.cn // Deprecated: in favor of PropagateDeps. // +optional Association bool `json:"association,omitempty"` // PropagateDeps tells if relevant resources should be propagated automatically. // Take 'Deployment' which referencing 'ConfigMap' and 'Secret' as an example, when 'propagateDeps' is 'true', // the referencing resources could be omitted(for saving config effort) from 'resourceSelectors' as they will be // propagated along with the Deployment. In addition to the propagating process, the referencing resources will be yqfh.cn // migrated along with the Deployment in the fail-over scenario. // // Defaults to false. // +optional PropagateDeps bool `json:"propagateDeps,omitempty"` // Placement represents the rule for select clusters to propagate resources.
// APIVersion represents the API version of the target resources. // +required APIVersion string `json:"apiVersion"` // Kind represents the Kind of the target resources. // +required Kind string `json:"kind"` // Namespace of the target resource. xmich.cn // Default is empty, which means inherit from the parent object scope. // +optional Namespace string `json:"namespace,omitempty"` // Name of the target resource. // Default is empty, which means selecting all resources. // +optional Name string `json:"name,omitempty"` // A label query over a set of resources. // If name is not empty, labelSelector will be ignored. // +optional
type Work struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` // Spec represents the desired behavior of Work. Spec WorkSpec `json:"spec"` // Status represents the status of PropagationStatus. // +optional Status WorkStatus `json:"status,omitempty"` } // WorkSpec defines the desired state of Work. type WorkSpec struct { // Workload represents the manifest workload to be deployed on managed cluster. Workload WorkloadTemplate `json:"workload,omitempty"` purongtech.com // SuspendDispatching controls whether dispatching should // be suspended, nil means not suspend.
// Note: true means stop propagating to the corresponding member cluster, and // does not prevent status collection. // +optional SuspendDispatching *bool `json:"suspendDispatching,omitempty"` // PreserveResourcesOnDeletion controls whether resources should be preserved on the // member cluster when the Work object is deleted. // If set to true, resources will be preserved on the member cluster. // Default is false, which means resources will be deleted along with the Work object. sytianxing.cn // +optional PreserveResourcesOnDeletion *bool `json:"preserveResourcesOnDeletion,omitempty"`
// Start initializes the resource interpreter and performs cache synchronization. Start(ctx context.Context) (err error) // HookEnabled tells if any hook exist for specific resource type and operation. HookEnabled(objGVK schema.GroupVersionKind, operationType configv1alpha1.InterpreterOperation) bool // GetReplicas returns the desired replicas of the object as well as the requirements of each replica. czjzz.com GetReplicas(object *unstructured.Unstructured) (replica int32, replicaRequires *workv1alpha2.ReplicaRequirements, err error) // ReviseReplica revises the replica of the given object. ReviseReplica(object *unstructured.Unstructured, replica int64) (*unstructured.Unstructured, error)hcsaikj.com // GetComponents extracts the resource requirements for multiple components from the given object. // This hook is designed for CRDs with multiple components (e.g., FlinkDeployment), but can // also be used for single-component resources like Deployment. huome.cn // If implemented, the controller will use this hook to obtain per-component replica and resource // requirements, and will not call GetReplicas. // If not implemented, the controller will fall back to GetReplicas for backward compatibility. // This hook will only be called when the feature gate 'MultiplePodTemplatesScheduling' is enabled. GetComponents(object *unstructured.Unstructured) (components []workv1alpha2.Component, err error)
// Retain returns the objects that based on the "desired" object but with values retained from the "observed" object. Retain(desired *unstructured.Unstructured, observed *unstructured.Unstructured) (retained *unstructured.Unstructured, err error)murnis.cn // AggregateStatus returns the objects that based on the 'object' but with status aggregated. AggregateStatus(object *unstructured.Unstructured, aggregatedStatusItems []workv1alpha2.AggregatedStatusItem) (*unstructured.Unstructured, error
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70048956/viewspace-3109304/ ,如需转载,请注明出处,否则将追究法律责任。