PodMigrationJob

Summary

This proposal defines a CRD-based Pod migration API, through which the descheduler or other automatic fault recovery components can evict or delete Pods more safely. At the same time, the proposal also describes the specific implementation details of the API.

Motivation

Migrating Pods is an important capability that many components (such as deschedulers) rely on, and can be used to optimize scheduling or help resolve workload runtime quality issues. We believe that pod migration is a complex process, involving steps such as auditing, resource allocation, and application startup, and is mixed with application upgrading, scaling scenarios, and resource operation and maintenance operations by cluster administrators. Therefore, how to manage the stability risk of this process to ensure that the application does not fail due to the migration of Pods is a very critical issue that must be resolved.

Therefore, it is necessary to realize a final state-oriented migration capability based on CRD, track the status of each process in the migration, and perceive scenarios such as upgrading and scaling of the application.

Goals

  1. Defines a CRD-based Pod Migration Job API, through which the descheduler can evict or delete Pods more safely.
  2. Describe in detail the design details behind the API.

Non-Goals/Future Work

  1. A new descheduler framework
  2. Descheduling capability for different scenarios such as load-aware descheduling, defragemention, etc.
  3. The details about Deterministic preemption that preempts other Pods for Reservation.

Proposal

User Stories

Story 1

The descheduler in the K8s community evicts pods to be rescheduled according to different strategies. However, it does not guarantee whether the evicted Pod has resources available after re-creation. If a large number of new Pods are in the Pending state when the resources in the cluster are tight, may lower the application availabilities.

Story 2

The descheduler evicts the Pod through the Eviction API, and the Eviction API decides whether to delete the Pod according to the PDB status. However, it is unable to perceive workload upgrades, scaling and other scenarios in which Pods are deleted, which will also bring security risks.

Story 3

The Pod migration capability itself can be provided to users as a service. Users can integrate this API in their own systems to achieve safe migration, and are no longer limited to deschedulers.

Basic Migration API

These APIs provide cluster administrators with more fine-grained migration control capabilities, which can better reduce risks.

  • scheduling.koordinator.sh/eviction-cost indicates the eviction cost. It can be used to set to an int32. The implicit eviction cost for pods that don’t set the annotation is 0, negative values are permitted. If set the cost ith math.MaxInt32, it means the Pod will not be evicted. Pods with lower eviction cost are preferred to be evicted before pods with higher eviction cost. If a batch of Pods to be evicted have the same priority, they will be sorted by cost, and the Pod with the smallest cost will be evicted. Although the K8s community has Pod Deletion Cost #2255, it is not a general mechanism. To avoid conflicts with components that use Pod Deletion Cost, users can individually mark the eviction cost for Pods.

Pod Migration Job CRD

In order to support the above user stories, a Custom Resource Definition(CRD) named PodMigrationJob is proposed to ensure the migration process safely.

Migration Job Spec

  1. // PodMigrationJob is the Schema for the PodMigrationJob API
  2. // +k8s:openapi-gen=true
  3. // +kubebuilder:resource:scope=Cluster
  4. type PodMigrationJob struct {
  5. metav1.TypeMeta `json:",inline"`
  6. metav1.ObjectMeta `json:"metadata,omitempty"`
  7. Spec PodMigrationJobSpec `json:"spec,omitempty"`
  8. Status PodMigrationJobStatus `json:"status,omitempty"`
  9. }
  10. type PodMigrationJobSpec struct {
  11. // Paused indicates whether the PodMigrationJob should to work or not.
  12. // Default is false
  13. // +optional
  14. Paused bool `json:"paused,omitempty"`
  15. // TTL controls the PodMigrationJob timeout duration.
  16. // +optional
  17. TTL *metav1.Duration `json:"ttl,omitempty"`
  18. // Mode represents the operating mode of the Job
  19. // Default is PodMigrationJobModeReservationFirst
  20. // +optional
  21. Mode PodMigrationJobMode `json:"mode,omitempty"`
  22. // PodRef represents the Pod that be migrated
  23. // +required
  24. PodRef *corev1.ObjectReference `json:"podRef"`
  25. // ReservationOptions defines the Reservation options for migrated Pod
  26. // +optional
  27. ReservationOptions *PodMigrateReservationOptions `json:"reservationOptions,omitempty"`
  28. // DeleteOptions defines the deleting options for the migrated Pod and preempted Pods
  29. // +optional
  30. DeleteOptions *metav1.DeleteOptions `json:"deleteOptions,omitempty"`
  31. }
  32. type PodMigrationJobMode string
  33. const (
  34. PodMigrationJobModeReservationFirst PodMigrationJobMode = "ReservationFirst"
  35. PodMigrationJobModeEvictionDirectly PodMigrationJobMode = "EvictDirectly"
  36. )
  37. type PodMigrateReservationOptions struct {
  38. // ReservationRef if specified, PodMigrationJob will check if the status of Reservation is available.
  39. // ReservationRef if not specified, PodMigrationJob controller will create Reservation by Template,
  40. // and update the ReservationRef to reference the Reservation
  41. // +optional
  42. ReservationRef *corev1.ObjectReference `json:"reservationRef,omitempty"`
  43. // Template is the object that describes the Reservation that will be created if not specified ReservationRef
  44. // +optional
  45. Template *ReservationTemplateSpec `json:"template,omitempty"`
  46. // PreemptionOption decides whether to preempt other Pods.
  47. // The preemption is safe and reserves resources for preempted Pods.
  48. // +optional
  49. PreemptionOptions *PodMigrationJobPreemptionOptions `json:"preemptionOptions,omitempty"`
  50. }
  51. type PodMigrationJobPreemptionOptions struct {
  52. // Reserved object.
  53. }
  • Paused indicates whether the PodMigrationJob should to work or not. In some scenarios, the user does not expect the PodMigrationJob Controller to process the PodMigrationJob immediately, but rather to decide whether to execute it after completing some operations similar to auditing.
  • TimeoutInSeconds controls the PodMigrationJob timeout duration.
  • The PodMigrationJob support two modes defined by the field Mode:
    • PodMigrationJobModeReservationFirst means that before migrating a Pod, try to reserve resources through the Reservation API, delete the Pod to be migrated after successfully reserved, and observe the status of the Reservation to ensure that the Reservation is consumed.
    • PodMigrationJobModeEvictionDirectly indicates that the user clearly knows the risk of evicting the Pod and decides to evict the Pod directly.
    • If Mode is not specified, PodMigrationJobModeReservationFirst is used by default
  • PodRef represents the Pod that be migrated. The field is required.
  • ReservationOptions defines options for how to reserve resource through Reservation API:
    • ReservationRef if is specified, the referenced Reservation instance is used first. In some scenarios, such as defragmentation, in order to ensure the reliability of the upper-layer logic, resources may have been reserved on the target node. In this case, the specified Reservation can be used directly.
    • Template describes the spec of Reservation. It is often not necessary to set this field. When neither ReservationRef nor Template is specified, the PodMigrationJob controller will construct the ReservationSpec reserved resources according to the Spec of the migrated Pod. If Template is set, the ReservationTemplateSpec and the Spec of the migrated Pod will be merged to construct the ReservationSpec reserved resources.
    • PreemptionOptions decides whether to preempt other Pods if reserved resources failed. The specific details of preemption will be submitted in a separate proposal description in future work, and will not be expanded here for the time being.
  • DeleteOptions defines the options of delete operation. Whether to delete a Pod through the K8s Delete API or evict a Pod through the K8s Eviction API depends on how the user configures the parameters of the PodMigrationJob Controller. Users only need to set DeleteOptions according to the workload in their own cluster.

Migration Job Status

  1. type PodMigrationJobStatus struct {
  2. // PodMigrationJobPhase represents the phase of a PodMigrationJob is a simple, high-level summary of where the PodMigrationJob is in its lifecycle.
  3. // e.g. Pending/Running/Failed
  4. Phase PodMigrationJobPhase `json:"phase,omitempty"`
  5. // Status represents the current status of PodMigrationJob
  6. // e.g. ReservationCreated
  7. Status string `json:"status,omitempty"`
  8. // Reason represents a brief CamelCase message indicating details about why the PodMigrationJob is in this state.
  9. Reason string `json:"reason,omitempty"`
  10. // Message represents a human-readable message indicating details about why the PodMigrationJob is in this state.
  11. Message string `json:"message,omitempty"`
  12. // Conditions records the stats of PodMigrationJob
  13. Conditions []PodMigrationJobCondition `json:"conditions,omitempty"`
  14. // NodeName represents the node's name of migrated Pod
  15. NodeName string `json:"nodeName,omitempty"`
  16. // PodRef represents the newly created Pod after being migrated
  17. PodRef *corev1.ObjectReference `json:"podRef,omitempty"`
  18. // PreemptedPodsRef represents the Pods that be preempted
  19. PreemptedPodsRef []corev1.ObjectReference `json:"preemptedPodsRef,omitempty"`
  20. // PreemptedPodsReservations records information about Reservations created due to preemption
  21. PreemptedPodsReservations []PodMigrationJobPreemptedReservation `json:"preemptedPodsReservation,omitempty"`
  22. }
  23. type PodMigrationJobPreemptedReservation struct {
  24. // Namespace represents the namespace of Reservation
  25. Namespace string `json:"namespace,omitempty"`
  26. // Name represents the name of Reservation
  27. Name string `json:"name,omitempty"`
  28. // NodeName represents the assigned node for Reservation by scheduler
  29. NodeName string `json:"nodeName,omitempty"`
  30. // Phase represents the Phase of Reservation
  31. Phase string `json:"phase,omitempty"`
  32. // PreemptedPodRef represents the Pod that be preempted
  33. PreemptedPodRef *corev1.ObjectReference `json:"preemptedPodRef,omitempty"`
  34. // PodsRef represents the newly created Pods after being preempted
  35. PodsRef []corev1.ObjectReference `json:"podsRef,omitempty"`
  36. }
  37. type PodMigrationJobCondition struct {
  38. // Type is the type of the condition.
  39. Type PodMigrationJobConditionType `json:"type"`
  40. // Status is the status of the condition.
  41. // Can be True, False, Unknown.
  42. Status PodMigrationJobConditionStatus `json:"status"`
  43. // Last time we probed the condition.
  44. // +nullable
  45. LastProbeTime metav1.Time `json:"lastProbeTime,omitempty"`
  46. // Last time the condition transitioned from one status to another.
  47. // +nullable
  48. LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty"`
  49. // Unique, one-word, CamelCase reason for the condition's last transition.
  50. Reason string `json:"reason,omitempty"`
  51. // Human-readable message indicating details about last transition.
  52. Message string `json:"message,omitempty"`
  53. }
  54. type PodMigrationJobPhase string
  55. const (
  56. // PodMigrationJobPending represents the initial status
  57. PodMigrationJobPending PodMigrationJobPhase = "Pending"
  58. // PodMigrationJobRunning represents the PodMigrationJob is being processed
  59. PodMigrationJobRunning PodMigrationJobPhase = "Running"
  60. // PodMigrationJobSucceed represents the PodMigrationJob processed successfully
  61. PodMigrationJobSucceed PodMigrationJobPhase = "Succeed"
  62. // PodMigrationJobFailed represents the PodMigrationJob process failed caused by Timeout, Reservation failed, etc.
  63. PodMigrationJobFailed PodMigrationJobPhase = "Failed"
  64. // PodMigrationJobAborted represents the user forcefully aborted the PodMigrationJob.
  65. PodMigrationJobAborted PodMigrationJobPhase = "Aborted"
  66. )
  67. // These are valid conditions of PodMigrationJob.
  68. const (
  69. PodMigrationJobConditionReservationCreated PodMigrationJobConditionType = "ReservationCreated"
  70. PodMigrationJobConditionReservationScheduled PodMigrationJobConditionType = "ReservationScheduled"
  71. PodMigrationJobConditionPreemption PodMigrationJobConditionType = "Preemption"
  72. PodMigrationJobConditionEviction PodMigrationJobConditionType = "Eviction"
  73. PodMigrationJobConditionPodScheduled PodMigrationJobConditionType = "PodScheduled"
  74. PodMigrationJobConditionReservationPodBoundReservation PodMigrationJobConditionType = "PodBoundReservation"
  75. PodMigrationJobConditionReservationBound PodMigrationJobConditionType = "ReservationBound"
  76. )
  77. // These are valid reasons of PodMigrationJob.
  78. const (
  79. PodMigrationJobReasonTimeout = "Timeout"
  80. PodMigrationJobReasonFailedCreateReservation = "FailedCreateReservation"
  81. PodMigrationJobReasonUnschedulable = "Unschedulable"
  82. PodMigrationJobReasonMissingPod = "MissingPod"
  83. PodMigrationJobReasonMissingReservation = "MissingReservation"
  84. PodMigrationJobReasonPreempting = "Preempting"
  85. PodMigrationJobReasonPreemptComplete = "PreemptComplete"
  86. PodMigrationJobReasonEvicting = "Evicting"
  87. PodMigrationJobReasonFailedEvict = "FailedEvict"
  88. PodMigrationJobReasonEvictComplete = "EvictComplete"
  89. PodMigrationJobReasonWaitForPodBindReservation = "WaitForPodBindReservation"
  90. )
  91. type PodMigrationJobConditionStatus string
  92. const (
  93. PodMigrationJobConditionStatusTrue PodMigrationJobConditionStatus = "True"
  94. PodMigrationJobConditionStatusFalse PodMigrationJobConditionStatus = "False"
  95. PodMigrationJobConditionStatusUnknown PodMigrationJobConditionStatus = "Unknown"
  96. )

Implementation Details/Notes/Constraints

PodMigrationJob Controller

The difference between PodMigrationJobController and general controller is that PodMigrationJobController will evaluate all pending PodMigrationJobs together (ie PodMigrationJob.Phase is Pending) and select a batch of PodMigrationJob and reconcile them. This selection process is called the arbitration mechanism. The reason why the arbitration mechanism is introduced is mainly to control the stability risk and control the cost of migrating Pods. The arbitration mechanism includes three stages: Group, Filter and Sort.

Group PodMigrationJob

Aggregate according to different workloads to facilitate the processing of subsequent processes

  • Aggregate PodMigrationJob by workload
  • Aggregate PodMigrationJob by Node
  • Aggregate PodMigrationJob by Namespace
Filter PodMigrationJob
  • Check how many PodMigrationJob of each workload are in the Running state, and record them as migratingReplicas. If the migratingReplicas reach a certain threshold, they will be excluded. The detailed algorithm of this threshold is described later.
  • Check the number of unavailableReplicas of each workload, and determine whether the unavailableReplicas + migratingReplicas conform to the corresponding PDB(Pod Disruption Budget) or PUB(Pod Unavailable Budget). If there is no PDB or PUB, use the algorithm to calculate dynamically. If not, exclude the corresponding PodMigrationJob.
  • Check the number of Pods being migrated on the node where each target Pod is located. If it exceeds the maximum migration amount for a single node, exclude it.
  • Check the number of Pods being migrated in the Namespace where each target Pod is located. If it exceeds the maximum migration amount for a single Namespace, exclude it

The detailed algorithm of Workload Max Migrating/Unavailable Replicas:

  1. func GetMaxMigrating(replicas int, intOrPercent *intstr.IntOrString) (int, error) {
  2. return GetMaxUnavailable(replicas, intOrPercent)
  3. }
  4. func GetMaxUnavailable(replicas int, intOrPercent *intstr.IntOrString) (int, error) {
  5. if intOrPercent == nil {
  6. if replicas > 10 {
  7. s := intstr.FromString("10%")
  8. intOrPercent = &s
  9. } else if replicas >= 4 && replicas <= 10 {
  10. s := intstr.FromInt(2)
  11. intOrPercent = &s
  12. } else {
  13. s := intstr.FromInt(1)
  14. intOrPercent = &s
  15. }
  16. }
  17. return intstr.GetValueFromIntOrPercent(intOrPercent, replicas, true)
  18. }
Sort PodMigrationJob
  • Pods with higher QoS requirements are given priority, LSE > LSR > LS > BE
  • Pods with higher priority will be processed first
  • The higher migration priority will be processed first
  • If the Pod has already initiated a migration job in the past and it fails, sort by the number of times. The lower the number of times, the priority will be given to processing
  • If the workload where the Pod is located has been descheduled for a certain number of times in the past, it is sorted according to the number of times. The lower the number of times, the priority will be processed.
  • Sort by the number of replicas being migrated by the workload. The lower the number of replicas being migrated, the priority will be given to processing.
Execute PodMigrationJob
  • Update PodMigrationJobStatus.Phase to Running to trigger the PodMigrationJob controller reconcile these jobs
  • PodMigrationJob controller reconciles process:
    • If the mode of PodMigrationJob is EvictionDirectly, just delete the Pod through the delete method that configured in PodMigrationJob controller. And update the phase of PodMigrationJob to Success.
    • If not specified ReservationOptions.ReservationRef, create the Reservation instance by the reservation template or Pod spec to reserve resources. And updates the created Reservation instance to the ReservationOptions.ReservationRef.
    • Check the status of Reservation to determine whether reserve resource successfully.
    • If failed to reserve, abort the PodMigrationJob and update the phase of PodMigrationJob to Fail
    • If successfully reserve, delete the Pod through the delete method that configured in PodMigrationJob controller.
    • Check the Reservation status to determine whether the Reservation consumed.
    • If Reservation consumed, tracks the status of Reservation and update the status to PodMigrationJob
    • Update phase of PodMigrationJob to Success.
Migration Stability mechanism
  • Support for disabling this capability by configuration
  • Supports a simple central flow control mechanism to limit the number of migrations over a period of time.

See the Configuration section for more details

Controller Configuration

User can configure the MigrationControllerArgs through Koordinator Descheduler ConfigMap.

  1. // MigrationControllerArgs holds arguments used to configure the MigrationController
  2. type MigrationControllerArgs struct {
  3. metav1.TypeMeta
  4. // DryRun means only execute the entire migration logic except create Reservation or Delete Pod
  5. // Default is false
  6. DryRun bool `json:"dryRun,omitempty"`
  7. // EvictFailedBarePods allows pods without ownerReferences and in failed phase to be evicted.
  8. EvictFailedBarePods bool `json:"evictFailedBarePods"`
  9. // EvictLocalStoragePods allows pods using local storage to be evicted.
  10. EvictLocalStoragePods bool `json:"evictLocalStoragePods"`
  11. // EvictSystemCriticalPods allows eviction of pods of any priority (including Kubernetes system pods)
  12. EvictSystemCriticalPods bool `json:"evictSystemCriticalPods"`
  13. // IgnorePVCPods prevents pods with PVCs from being evicted.
  14. IgnorePvcPods bool `json:"ignorePvcPods"`
  15. // LabelSelector sets whether to apply label filtering when evicting.
  16. // Any pod matching the label selector is considered evictable.
  17. LabelSelector *metav1.LabelSelector `json:"labelSelector,omitempty"`
  18. // FlowControlQPS controls the number of arbitrations per second
  19. FlowControlQPS string `json:"flowControlQPS,omitempty"`
  20. // FlowControlBurst is the maximum number of tokens
  21. FlowControlBurst int32 `json:"flowControlBurst,omitempty"`
  22. // MaxMigratingPerNode represents he maximum number of pods that can be migrating during migrate per node.
  23. MaxMigratingPerNode *int32 `json:"maxMigratingPerNode,omitempty"`
  24. // MaxMigratingPerNamespace represents he maximum number of pods that can be migrating during migrate per namespace.
  25. MaxMigratingPerNamespace *int32 `json:"maxMigratingPerNamespace,omitempty"`
  26. // MaxMigratingPerWorkload represents he maximum number of pods that can be migrating during migrate per workload.
  27. // Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%).
  28. MaxMigratingPerWorkload *intstr.IntOrString `json:"maxMigratingPerWorkload,omitempty"`
  29. // MaxUnavailablePerWorkload represents he maximum number of pods that can be unavailable during migrate per workload.
  30. // The unavailable state includes NotRunning/NotReady/Migrating/Evicting
  31. // Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%).
  32. MaxUnavailablePerWorkload *intstr.IntOrString `json:"maxUnavailablePerWorkload,omitempty"`
  33. // EvictionPolicy represents how to delete Pod, support "Delete" and "Eviction", default value is "Eviction"
  34. EvictionPolicy string `json:"evictionPolicy,omitempty"`
  35. // DefaultDeleteOptions defines options when deleting migrated pods and preempted pods through the method specified by EvictionPolicy
  36. DefaultDeleteOptions *metav1.DeleteOptions `json:"defaultDeleteOptions,omitempty"`
  37. }