Karmada 状态化工作负载集群故障转移(Cluster Failover)方案解读:StatePreservation 状态保留与标签注入恢复机制

原创2026-09-17 23:46:211,710 阅读
文章标签:云原生容器编排集群管理微服务后端高可用

Karmada 状态化工作负载集群故障转移(Cluster Failover)方案解读:StatePreservation 状态保留与标签注入恢复机制

本篇文章围绕 Karmada 社区关于状态化工作负载集群故障转移的设计提案(对应仓库文档 stateful-workload-cluster-failover.md)展开,深入讲解当集群本身发生故障(节点宕机、网络分区、控制面不可用)时,如何将 Flink、Spark 等依赖检查点(checkpoint)恢复的状态化应用迁移到新集群并从中断点无缝续跑。读完本文,你将掌握 Karmada 的 FailoverBehavior / StatePreservation API 设计、StatefulFailoverInjection 特性开关的启用方式,以及通过 PropagationPolicy 配置状态保留规则、利用标签注入实现状态恢复的完整实操路径,并理解其背后的控制器源码实现原理。

背景:为什么状态化工作负载需要集群故障转移

在 Karmada 的多集群编排模型中,工作负载的故障转移(failover)场景可以分为两类:

  1. 工作负载自身故障:应用实例本身出现故障(如健康检查失败),需要被迁移到另一个集群;
  2. 集群故障:集群遭遇节点宕机、网络分区或控制面故障,需要将受影响的工作负载迁出。

无状态(stateless)工作负载的容错优势在于,实例丢失不影响应用正确性,也无需数据恢复;而有状态(stateful)工作负载(典型如 Flink)依赖检查点或保存点(savepoint)状态来恢复。一旦状态丢失,作业可能无法从上次中断的位置继续执行,甚至可能产生重复计算。

Karmada 社区已在 v1.12 中完成了第一种场景(应用故障引发的状态化工作负载迁移)的设计与实现(对应社区 issue #5788 及相关 PR)。本文所解读的提案是在此前设计经验之上,扩展支持第二种场景——由集群故障引发的状态化工作负载迁移,并在 API 设计上统一两个场景的公共部分,避免冗余字段、改善用户体验。

本提案基于 Karmada 社区 PR #5116 的设计进行修改演进而来。

目标与非目标

Goals

  • 支持状态化应用的集群故障转移:允许用户在 Karmada 中自定义需要在故障集群中保留的工作负载状态信息;
  • 将保留的状态信息传递给迁移后的工作负载,使新启动的工作负载能够从原集群停止时的状态继续恢复。

No-Goals

  • 不对集群故障转移功能本身做额外优化;
  • 不对应用故障转移功能本身做额外优化。

提案概述:可配置的状态保留与恢复

本提案为用户提供了一种在集群故障转移迁移期间持久化应用所需状态的机制。一旦工作负载被重新调度,用户可以通过 Karmada 保存的标签来配置应用从中断处恢复。由于不同状态化应用"如何获取最近状态"的实现方式各不相同,因此该功能必须可配置。

支撑该特性至少需要三方面能力:

  1. 一种机制,让状态化应用在集群故障转移期间保留状态,并在恢复前重新加载;
  2. 一种让用户配置"Karmada 应保留哪些状态"的方式;
  3. 一种让用户配置"保留信息如何以标签形式展示在被恢复的状态化应用上"的方式。

重要前提:所有副本须整体迁移

提案明确指出一个关键细节:如果状态化应用的所有副本不是一起迁移的,则状态何时恢复是不明确的。因此本提案聚焦于"状态化应用的所有副本一起迁移"的场景。确保这一点的一种方式是使用 spreadConstraints 让所有副本调度到同一集群组:

spreadConstraints:
  - spreadByField: cluster
    maxGroups: 1
    minGroups: 1

Flink 应用场景举例

为了理解状态保留的价值,先看 Flink 应用的基本工作原理:检查点(checkpoint)是应用在某个时间点的状态快照,包含截至该时刻处理过的所有记录信息,并以固定间隔持续持久化到可靠存储中。Flink 的状态信息示例如下:

jobStatus:
  checkpointInfo:
    formatType: FULL
    lastCheckpoint:
      formatType: FULL
      timeStamp: 1734462491693
      triggerType: PERIODIC
    lastPeriodicCheckpointTimestamp: 1734462491693
    triggerId: 447b790bb9c88da9ae753f00f45acb0e
    triggerTimestamp: 1734462506836
    triggerType: PERIODIC
  jobId: e6fdb5c0997c11b0c62d796b3df25e86

要从持久化存储中恢复 Flink 应用的最新状态,需要两个信息:被恢复作业的 jobId 与 持久化状态的路径。Flink Operator 通过对 Flink 资源 spec 做少量修改即可据此恢复:

spec:
  jobSpec:
    initialSavepointPath: "desired checkpoint path to be resumed from (s3p://)"
    upgradeMode: savepoint
    state: running

用户故事:集群故障后 Flink 应用的状态恢复

作为管理员或运维人员,我可以为部署在 Karmada 上的 Flink 应用定义集群故障后的状态保留策略,包括保留 Flink 应用的 jobID,使应用在迁移后能凭借 jobID 从故障点恢复处理。

Flink 工作负载的恢复过程可总结为以下 5 步:

  1. Karmada 从故障集群中的 FlinkDeployment 获取 { .jobStatus.jobId };
  2. Karmada 以 <用户定义的标签键>:<jobId> 标签形式将 jobId 同步到迁移后的 FlinkDeployment;
  3. 用户利用 jobId 检索检查点数据,生成 initialSavepointPath:/<shared-path>/<job-namespace>/<jobID>/checkpoints/<checkpoint>;
  4. 用户将 initialSavepointPath 信息注入迁移后的 FlinkDeployment;
  5. Flink Operator 从 savepoint 重启 Flink。

对于第 3、4 步,可以在成员集群中部署 Kyverno,通过定义 Kyverno 策略拦截 FlinkDeployment 资源的分发并变更其 jobSpec,从而使新的 FlinkDeployment 在集群故障转移前从最后一个检查点恢复状态(相关讨论见社区 issue #4969 的评论)。

设计细节一:状态保留(State Preservation)

状态保留的关键设计点如下:

  1. 需要保留的状态信息从工作负载的 .status 字段解析而来;不在 .status 中的状态信息无法被保留;
  2. 用户可以自定义要保留的一条或多条状态信息;
  3. 状态保留方法对"集群故障"与"应用故障"引发的迁移可以统一处理;
  4. 保留的状态信息以键值对形式存储在与工作负载关联的 ResourceBinding 资源的 gracefulEvictionTask 中。

PropagationPolicy API 的修改

本提案在 FailoverBehavior 结构体中解除了 Cluster 字段的注释,用于定义集群故障相关行为;同时在 ClusterFailoverBehavior 中新增 StatePreservation 字段,其类型与 ApplicationFailoverBehavior 中的 StatePreservation 字段完全一致。核心 API 定义(与仓库中 propagation_types.go 的实现一致)如下:

// FailoverBehavior indicates failover behaviors in case of an application or
// cluster failure.
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.
    // +optional
    Cluster *ClusterFailoverBehavior `json:"cluster,omitempty"`
}

// ClusterFailoverBehavior indicates cluster failover behaviors.
type ClusterFailoverBehavior struct {
    // PurgeMode represents how to deal with the legacy applications on the
    // cluster from which the application is migrated.
    // Valid options are "Directly", "Gracefully".
    // Defaults to "Gracefully".
    // +kubebuilder:validation:Enum=Directly;Gracefully
    // +kubebuilder:default=Gracefully
    // +optional
    PurgeMode PurgeMode `json:"purgeMode,omitempty"`

    // StatePreservation defines the policy for preserving and restoring state data
    // during failover events for stateful applications.
    //
    // When an application fails over from one cluster to another, this policy enables
    // the extraction of critical data from the original resource configuration.
    // Upon successful migration, the extracted data is then re-injected into the new
    // resource, ensuring that the application can resume operation with its previous
    // state intact.
    // ...
    // Note: This requires the StatefulFailoverInjection feature gate to be enabled,
    // which is alpha.
    // +optional
    StatePreservation *StatePreservation `json:"statePreservation,omitempty"`
}

// StatePreservation defines the policy for preserving state during failover events.
type StatePreservation struct {
    // Rules contains a list of StatePreservationRule configurations.
    // Each rule specifies a JSONPath expression targeting specific pieces of
    // state data to be preserved during failover events. An AliasLabelName is associated
    // with each rule, serving as a label key when the preserved data is passed
    // to the new cluster.
    // +required
    Rules []StatePreservationRule `json:"rules"`
}

// StatePreservationRule defines a single rule for state preservation.
// It includes a JSONPath expression and an alias name that will be used
// as a label key when passing state information to the new cluster.
type StatePreservationRule struct {
    // AliasLabelName is the name that will be used as a label key when the preserved
    // data is passed to the new cluster.
    // +required
    AliasLabelName string `json:"aliasLabelName"`

    // JSONPath is the JSONPath template used to identify the state data
    // to be preserved from the original resource configuration.
    // The JSONPath syntax follows the Kubernetes specification.
    //
    // Note: The JSONPath expression will start searching from the "status" field of
    // the API resource object by default. For example, to extract the "availableReplicas"
    // from a Deployment, the JSONPath expression should be "{.availableReplicas}", not
    // "{.status.availableReplicas}".
    // +required
    JSONPath string `json:"jsonPath"`
}

各字段的语义要点如下:

字段 是否必填 说明
failover.cluster 可选 集群故障转移行为;为 nil 时由 controller-manager 的 no-execute-taint-eviction-purge-mode 参数决定迁移策略
cluster.purgeMode 可选,默认 Gracefully 处理被迁移集群上遗留应用的方式,取值 Directly(直接清除)或 Gracefully(优雅清除)
cluster.statePreservation 可选 状态保留策略;未指定表示不保留任何状态数据;需要启用 StatefulFailoverInjection 特性开关(alpha)
statePreservation.rules 必填 状态保留规则列表
rule.aliasLabelName 必填 状态数据传递到新集群时作为标签键使用
rule.jsonPath 必填 从原资源配置中提取状态数据的 JSONPath 模板;默认从 API 对象的 status 字段开始查找,因此提取 Deployment 的 availableReplicas 应写 "{.availableReplicas}" 而非 "{.status.availableReplicas}"

PurgeMode 语义

在仓库源码 propagation_types.go 中,PurgeMode 的完整取值定义如下:

  • Directly:Karmada 直接驱逐遗留应用。适用于不允许两个实例同时运行的场景。例如 Flink 支持 exactly-once 状态一致性,要求故障转移期间必须先移除旧应用再创建新应用,以避免重复处理并保持状态一致性;
  • Gracefully:Karmada 等待应用在新集群恢复健康,或达到超时后再驱逐旧应用(默认值);
  • Never(仅应用故障场景):Karmada 不驱逐应用,由用户手动确认如何清理冗余副本。

如果用户未指定 .spec.failover.cluster 字段,集群故障时的迁移策略将由 karmada-controller-manager 组件的 no-execute-taint-eviction-purge-mode 参数决定。

ResourceBinding 的复用

ResourceBinding API 已满足设计目标,可直接复用其 gracefulEvictionTask 中的 PreservedLabelState 与 ClustersBeforeFailover 字段,无需引入新的修改。在仓库源码 binding_types.go 中可以看到这两个字段的定义:

// GracefulEvictionTask represents a graceful eviction task.
type GracefulEvictionTask struct {
    // FromCluster which cluster the eviction perform from.
    // +required
    FromCluster string `json:"fromCluster"`
    // ...
    // PreservedLabelState represents the application state information collected from the original cluster,
    // and it will be injected into the new cluster in form of application labels.
    // +optional
    PreservedLabelState map[string]string `json:"preservedLabelState,omitempty"`
    // ...
    // ClustersBeforeFailover records the clusters where running the application before failover.
    ClustersBeforeFailover []string `json:"clustersBeforeFailover,omitempty"`
}

配置示例:Flink 应用的状态保留策略

apiVersion: policy.karmada.io/v1alpha1
kind: PropagationPolicy
metadata:
  name: foo
spec:
  resourceSelectors:
    - apiVersion: flink.apache.org/v1beta1
      kind: FlinkDeployment
      name: foo
  placement:
    clusterAffinity:
      clusterNames:
        - member1
        - member2
    spreadConstraints:
      - maxGroups: 1
        minGroups: 1
        spreadByField: cluster
  failover:
    cluster:
      purgeMode: Directly
      statePreservation:
        rules:
          - aliasLabelName: cluster.karmada.io/failover-jobid
            jsonPath: "{ .jobStatus.jobID }"

当 Flink 应用因集群故障触发迁移时,Karmada 控制器将依据上述配置,从故障集群中 Flink 资源的 .jobStatus.jobID 路径提取 jobID;迁移完成后,控制器以标签形式将 jobID 注入新集群上的 Flink 资源,标签键为 cluster.karmada.io/failover-jobid,值为该 jobID。

源码级实现:如何从 status 构建保留状态

状态提取的核心逻辑在仓库 failover.go 中,BuildPreservedLabelState 函数遍历 StatePreservation.Rules,对每条规则使用 Kubernetes 官方的 client-go/jsonpath 解析器从工作负载的原始 status 字节流中提取值:

// BuildPreservedLabelState builds preserved label state from the state preservation rules and raw status.
func BuildPreservedLabelState(statePreservation *policyv1alpha1.StatePreservation, rawStatus []byte) (map[string]string, error) {
    results := make(map[string]string, len(statePreservation.Rules))
    for _, rule := range statePreservation.Rules {
        value, err := parseJSONValue(rawStatus, rule.JSONPath)
        if err != nil {
            klog.ErrorS(err, "Failed to parse value with jsonPath from status",
                "jsonPath", rule.JSONPath,
                "status", string(rawStatus))
            return nil, err
        }
        results[rule.AliasLabelName] = value
    }
    return results, nil
}

对应的单元测试位于 failover_test.go,覆盖了成功解析(如 {"replicas": 2, "health": true} 解析出 {"key-a": "2", "key-b": "true"})以及规则指向不存在字段等错误场景。

在集群故障迁移的触发链路上,NoExecuteTaintManager(taint_manager.go 中的 extractStateForEviction 函数)会先检查是否配置了 StatePreservation,然后从聚合状态中查找目标集群的状态项并调用 BuildPreservedLabelState 完成提取,最终把保留状态写入 eviction task。需要注意的是:如果集群状态尚未被收集(Status.Raw 为空),该函数会直接报错,这要求故障触发前集群状态采集必须可用。

设计细节二:状态恢复(State Recovery)

状态恢复的关键设计点如下:

  1. 状态恢复通过将保留的状态信息以标签形式注入迁移后的新工作负载来实现;
  2. 标签注入的时机是工作负载迁移到新集群时(为了确认该集群是新调度结果,需要在 gracefulEvictionTask 中保存迁移前的集群调度信息)。在工作负载传播过程中,控制器将保留的状态信息注入 work 对象的 manifest。

注:状态恢复的控制器逻辑可以完全复用此前为应用故障(application failover)所做的状态化工作负载支持改动,本提案无需新增改动。

PurgeMode = Directly 的特殊语义

需要特别强调:当应用的迁移模式 PurgeMode 为 Directly 时,Karmada 系统会先从原集群移除应用,待应用完全移除后才能调度到新集群。当前实现尚不完全满足这一要求,需要调整。状态恢复可以在应用被调度到新集群后执行。

在仓库源码 common.go 的 injectReservedLabelState 函数中,可以看到状态恢复注入的完整约束:

  • 只考虑"应用部署在一个集群并迁移到另一个集群"的场景;
  • 若发生连续故障转移(例如从集群 A 迁到 B、再迁到 C),使用最后一次故障转移前的 PreservedLabelState 进行注入;若该值为空则跳过注入;
  • 仅当 PurgeMode 为 Directly 时才执行注入操作。

对应实现片段:

// 1. Only the scenario where an application is deployed in one cluster and migrated to
//    another cluster is considered.
// 2. If consecutive failovers occur ... the PreservedLabelState before the last failover is
//    used for injection. If the PreservedLabelState is empty, the injection is skipped.
// 3. The injection operation is performed only when PurgeMode is set to Directly.
func injectReservedLabelState(bindingSpec workv1alpha2.ResourceBindingSpec, moveToCluster workv1alpha2.TargetCluster, workload *unstructured.Unstructured, clustersLen int) *unstructured.Unstructured {
    if clustersLen > 1 {
        return workload
    }
    if len(bindingSpec.GracefulEvictionTasks) == 0 {
        return workload
    }
    targetEvictionTask := bindingSpec.GracefulEvictionTasks[len(bindingSpec.GracefulEvictionTasks)-1]
    if targetEvictionTask.PurgeMode != policyv1alpha1.PurgeModeDirectly {
        return workload
    }
    clustersBeforeFailover := sets.NewString(targetEvictionTask.ClustersBeforeFailover...)
    if clustersBeforeFailover.Has(moveToCluster.Name) {
        return workload
    }
    for key, value := range targetEvictionTask.PreservedLabelState {
        util.MergeLabel(workload, key, value)
    }
    return workload
}

特性开关:StatefulFailoverInjection

在 Karmada v1.12 中引入了 StatefulFailoverInjection FeatureGate,用于控制状态化应用在应用故障后恢复过程中是否执行状态恢复。本提案将该特性开关的控制范围扩展至集群故障后的状态化应用恢复场景,从而统一控制状态化应用的故障转移恢复。

在仓库源码 features.go 中的定义如下:

// StatefulFailoverInjection controls whether Karmada collects state information
// from the source cluster during a failover event for stateful applications and
// injects this information into the application configuration when it is moved
// to the target cluster.
//
// owner: @mszacillo, @XiShanYongYe-Chang
// alpha: v1.12
StatefulFailoverInjection featuregate.Feature = "StatefulFailoverInjection"

其默认配置为:

StatefulFailoverInjection: {Default: false, PreRelease: featuregate.Alpha},

即该特性默认关闭、处于 alpha 阶段。若要在集群故障转移中使用状态保留与恢复,需要在 karmada-controller-manager 上显式启用该特性开关(例如以 --feature-gates=StatefulFailoverInjection=true 方式启动),并注意此特性尚处于 alpha 阶段,可能存在稳定性风险。

E2E 测试规划

提案的测试规划包括:UT——为新增函数补充单元测试;E2E——为集群故障转移后的状态化工作负载恢复补充端到端测试用例。以下三个 E2E 用例均采用"通过 PropagationPolicy 将资源传播到成员集群 → 为集群添加 NoExecute 污点触发应用迁移 → 检查迁移后资源上是否存在目标标签"的验证路径。

Case 1:Deployment 资源

apiVersion: policy.karmada.io/v1alpha1
kind: PropagationPolicy
metadata:
  name: deploy-propagation
spec:
  resourceSelectors:
    - apiVersion: apps/v1
      kind: Deployment
      name: deploy
  placement:
    clusterAffinity:
      clusterNames:
        - member1
        - member2
    spreadConstraints:
      - spreadByField: cluster
        maxGroups: 1
        minGroups: 1
  failover:
    cluster:
      purgeMode: Directly
      statePreservation:
        rules:
          - aliasLabelName: failover.karmada.io/replicas
            jsonPath: "{ .replicas }"
          - aliasLabelName: failover.karmada.io/readyReplicas
            jsonPath: "{ .readyReplicas }"

Case 2:StatefulSet 资源

apiVersion: policy.karmada.io/v1alpha1
kind: PropagationPolicy
metadata:
  name: sts-propagation
spec:
  resourceSelectors:
    - apiVersion: apps/v1
      kind: StatefulSet
      name: sts
  placement:
    clusterAffinity:
      clusterNames:
        - member1
        - member2
    spreadConstraints:
      - spreadByField: cluster
        maxGroups: 1
        minGroups: 1
  failover:
    cluster:
      purgeMode: Directly
      statePreservation:
        rules:
          - aliasLabelName: failover.karmada.io/replicas
            jsonPath: "{ .replicas }"
          - aliasLabelName: failover.karmada.io/readyReplicas
            jsonPath: "{ .readyReplicas }"

Case 3:FlinkDeployment 资源

apiVersion: policy.karmada.io/v1alpha1
kind: PropagationPolicy
metadata:
  name: foo
spec:
  resourceSelectors:
    - apiVersion: flink.apache.org/v1beta1
      kind: FlinkDeployment
      name: foo
  placement:
    clusterAffinity:
      clusterNames:
        - member1
        - member2
    spreadConstraints:
      - maxGroups: 1
        minGroups: 1
        spreadByField: cluster
  failover:
    cluster:
      purgeMode: Directly
      statePreservation:
        rules:
          - aliasLabelName: failover.karmada.io/failover-jobid
            jsonPath: "{ .jobStatus.jobID }"

三个用例的共同验证点是:Deployment / StatefulSet / FlinkDeployment 资源被传播到其中一个集群后,为该集群添加 NoExecute 污点触发应用迁移,然后检查迁移后的资源上是否存在配置的目标标签(如 failover.karmada.io/replicas、failover.karmada.io/readyReplicas、failover.karmada.io/failover-jobid)。

约束、风险与演进路径

约束与注意事项

如前面反复强调的,本提案只覆盖状态化应用所有副本一起迁移的场景。如果用户将状态化应用的副本拆分并跨集群传播,而系统只迁移部分副本,那么状态化应用的故障转移恢复特性可能无法正常工作。

已知风险与缓解措施

  1. 集群故障检测尚不够精确:当前检测方法相对简单,可能在检测准确性上存在不足;
  2. Directly 模式可能被阻断:如果 Karmada 与目标集群之间的连接中断,Directly 清除模式可能无法执行。

影响分析与升级影响

  • 相关功能影响:当前无相关功能受到影响;
  • 升级影响:无。

毕业标准(Graduation Criteria)

Alpha → Beta:

  • 决定是否从 ApplicationFailoverBehavior 与 ClusterFailoverBehavior 结构中移除冗余字段;
  • 完成端到端(E2E)测试(参考上文测试规划);
  • StatefulFailoverInjection FeatureGate 默认启用。

GA 毕业:

  • 完成可扩展性与性能测试;
  • 修复所有已知功能缺陷;
  • 废弃 StatefulFailoverInjection FeatureGate。

设计问答

Q:为什么在 ClusterFailoverBehavior 和 ApplicationFailoverBehavior 中使用相同的 StatePreservation 字段?

A: 目前在两处都定义 StatePreservation 确实显得有些冗余。但我们也考虑到另一点:目前可能还没有足够的场景来证明"集群故障引发的迁移"与"应用故障引发的迁移"中获取信息的方法完全相同。因此在两种行为中分别保留独立字段,为将来两种场景的差异化演进留出空间。

总结:一套统一的"状态保留 + 标签注入"故障转移机制

综合来看,本提案为 Karmada 引入了完整的状态化工作负载集群故障转移能力:

  • 配置面:通过 PropagationPolicy.spec.failover.cluster 下的 purgeMode 与 statePreservation.rules(aliasLabelName + jsonPath),用户可以为每个工作负载定制"保留哪些状态"以及"以什么标签键注入";
  • 数据面:状态从工作负载 .status 通过 JSONPath 提取,键值对形式写入 ResourceBinding 的 gracefulEvictionTask.PreservedLabelState;
  • 恢复面:工作负载迁移到新集群后,injectReservedLabelState 在传播过程中把保留状态以标签形式合并进 work manifest,从而让 Flink 等状态化应用能基于 jobId 等标签信息从持久化的检查点/保存点无缝续跑;
  • 控制面:StatefulFailoverInjection 特性开关统一管控应用故障与集群故障两类状态化恢复场景,目前为 alpha、默认关闭。

对于需要在多集群环境中保障 Flink、Spark 等有状态数据处理作业连续性、避免故障后重复计算的团队,这套机制提供了在 Karmada 中声明式配置"集群级容灾 + 状态续跑"的完整技术路径。可以结合仓库中的设计文档 stateful-workload-cluster-failover.md、API 定义 propagation_types.go、核心实现 failover.go 与 taint_manager.go 继续深入研读。

登录后查看全文
karmada