generated from kubernetes/kubernetes-template-project
-
Notifications
You must be signed in to change notification settings - Fork 479
Implement the PodTermination controller to gracefully handle "stuck" pods
#7312
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
k8s-ci-robot
merged 31 commits into
kubernetes-sigs:main
from
kshalot:6757-gracefully-handle-zombie-pods
Nov 21, 2025
Merged
Changes from all commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
b4d8577
Add `FailureRecoveryPolicy` to `Configuration`
kshalot c8e14ce
Implement the `PodTermination` failure recovery action
kshalot e5e01fd
Add `failurerecovery` integration test suite
kshalot c1c3739
Use patch instead of update to terminate stuck pods
kshalot d18e6ba
Fix indendation in example failure recovery policy
kshalot 3c8a8ae
Realign the configuration with KEP changes
kshalot 4576252
Validate that `terminatePod` is set on failure policy
kshalot 9aa810a
Fix invalid label selector in config test
kshalot ec481a2
Remove the `FailureRecoveryPolicy` API
kshalot d379ac4
Add `FailureRecoveryPolicy` feature gate
kshalot 92c4e3a
Configure shorter termination grace period in test
kshalot 178119f
Rename `gracePeriodLeft` to `remainingTime`
kshalot 21ead2e
Fix option not being set on struct
kshalot 86e4bc8
Remove `util.node` in favor of `util.taints`
kshalot b2c6e58
Add missing copyright headers
kshalot 00254ab
Fix feature gate being true by default
kshalot a1a9346
Adjust timeouts in integration test
kshalot b494149
Consolidate unhappy path test cases into a single test
kshalot 68e1f58
Move annotation costants to the `constants` package
kshalot b981205
Remove helper methods from tests
kshalot 1044989
Fix counting deletion grace period twice
kshalot 3f11131
Use event filter to unburden the reconciler
kshalot 606dcc6
Adjust unit test
kshalot f5f1d2d
Move termination threshold check above node taint check
kshalot e0024de
Ignore node not found errors
kshalot 2b70919
Emit an event upon forceful pod termination
kshalot e266319
Add `KueueFailureRecovery` condition after forceful pod termination
kshalot bee8767
Add missing event filter unit tests
kshalot 20d4563
Simplify deletion update filter condition
kshalot c3a5c37
Rename integration test timeout variable
kshalot d15bb80
Fix extra lines at the start of block
kshalot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
199 changes: 199 additions & 0 deletions
199
pkg/controller/failurerecovery/pod_termination_controller.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,199 @@ | ||
| /* | ||
| Copyright The Kubernetes Authors. | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
|
|
||
| package failurerecovery | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "time" | ||
|
|
||
| corev1 "k8s.io/api/core/v1" | ||
| "k8s.io/apimachinery/pkg/types" | ||
| "k8s.io/client-go/tools/record" | ||
| "k8s.io/utils/clock" | ||
| "k8s.io/utils/ptr" | ||
| ctrl "sigs.k8s.io/controller-runtime" | ||
| "sigs.k8s.io/controller-runtime/pkg/client" | ||
| "sigs.k8s.io/controller-runtime/pkg/event" | ||
|
|
||
| "sigs.k8s.io/kueue/pkg/controller/constants" | ||
| utilpod "sigs.k8s.io/kueue/pkg/util/pod" | ||
| utiltaints "sigs.k8s.io/kueue/pkg/util/taints" | ||
| ) | ||
|
|
||
| // +kubebuilder:rbac:groups="",resources=pods,verbs=get;list;watch | ||
| // +kubebuilder:rbac:groups="",resources=pods/status,verbs=get;patch | ||
| // +kubebuilder:rbac:groups="",resources=nodes,verbs=get;list;watch | ||
|
|
||
| var realClock = clock.RealClock{} | ||
|
|
||
| const ( | ||
| KueueFailureRecoveryConditionType = "KueueFailureRecovery" | ||
| KueueForcefulTerminationReason = "KueueForcefullyTerminated" | ||
| ) | ||
|
|
||
| type TerminatingPodReconciler struct { | ||
| client client.Client | ||
| clock clock.Clock | ||
| forcefulTerminationGracePeriod time.Duration | ||
| recorder record.EventRecorder | ||
| } | ||
|
|
||
| type TerminatingPodReconcilerOptions struct { | ||
| clock clock.Clock | ||
| forcefulTerminationGracePeriod time.Duration | ||
| } | ||
|
|
||
| type TerminatingPodReconcilerOption func(*TerminatingPodReconcilerOptions) | ||
|
|
||
| func WithClock(c clock.Clock) TerminatingPodReconcilerOption { | ||
| return func(o *TerminatingPodReconcilerOptions) { | ||
| o.clock = c | ||
| } | ||
| } | ||
|
|
||
| func WithForcefulTerminationGracePeriod(t time.Duration) TerminatingPodReconcilerOption { | ||
| return func(o *TerminatingPodReconcilerOptions) { | ||
| o.forcefulTerminationGracePeriod = t | ||
| } | ||
| } | ||
|
|
||
| var defaultOptions = TerminatingPodReconcilerOptions{ | ||
| clock: realClock, | ||
| forcefulTerminationGracePeriod: time.Minute, | ||
| } | ||
|
|
||
| func NewTerminatingPodReconciler( | ||
| client client.Client, | ||
| recorder record.EventRecorder, | ||
| opts ...TerminatingPodReconcilerOption, | ||
| ) (*TerminatingPodReconciler, error) { | ||
| options := defaultOptions | ||
| for _, opt := range opts { | ||
| opt(&options) | ||
| } | ||
|
|
||
| return &TerminatingPodReconciler{ | ||
| client: client, | ||
| clock: options.clock, | ||
| forcefulTerminationGracePeriod: options.forcefulTerminationGracePeriod, | ||
| recorder: recorder, | ||
| }, nil | ||
| } | ||
|
|
||
| func (r *TerminatingPodReconciler) Generic(event.GenericEvent) bool { | ||
| return false | ||
| } | ||
|
|
||
| func (r *TerminatingPodReconciler) Create(e event.CreateEvent) bool { | ||
| pod := e.Object.(*corev1.Pod) | ||
|
|
||
| if !podOptedInToFailurePolicy(pod) { | ||
| return false | ||
| } | ||
|
|
||
| if pod.DeletionTimestamp.IsZero() { | ||
| return false | ||
| } | ||
|
|
||
| return true | ||
| } | ||
|
|
||
| func (r *TerminatingPodReconciler) Update(u event.UpdateEvent) bool { | ||
| oldPod := u.ObjectOld.(*corev1.Pod) | ||
| newPod := u.ObjectNew.(*corev1.Pod) | ||
|
|
||
| if !podOptedInToFailurePolicy(newPod) { | ||
| return false | ||
| } | ||
|
|
||
| // Pod was not marked for deletion in the update | ||
| if !oldPod.DeletionTimestamp.IsZero() || newPod.DeletionTimestamp.IsZero() { | ||
| return false | ||
| } | ||
|
|
||
| return true | ||
| } | ||
|
|
||
| func (r *TerminatingPodReconciler) Delete(event.DeleteEvent) bool { | ||
| return false | ||
| } | ||
|
|
||
| func podOptedInToFailurePolicy(p *corev1.Pod) bool { | ||
| annotationValue, hasAnnotation := p.Annotations[constants.SafeToForcefullyTerminateAnnotationKey] | ||
| return hasAnnotation && annotationValue == constants.SafeToForcefullyTerminateAnnotationValue | ||
| } | ||
|
|
||
| func (r *TerminatingPodReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { | ||
| pod := &corev1.Pod{} | ||
| if err := r.client.Get(ctx, req.NamespacedName, pod); err != nil { | ||
| return ctrl.Result{}, client.IgnoreNotFound(err) | ||
| } | ||
|
|
||
| // Pod was already terminated | ||
| if utilpod.IsTerminated(pod) { | ||
kshalot marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return ctrl.Result{}, nil | ||
| } | ||
|
|
||
| // Forceful termination threshold not reached | ||
| now := r.clock.Now() | ||
| forcefulTerminationThreshold := pod.DeletionTimestamp.Add(r.forcefulTerminationGracePeriod) | ||
| if now.Before(forcefulTerminationThreshold) { | ||
| remainingTime := forcefulTerminationThreshold.Sub(now) | ||
| return ctrl.Result{RequeueAfter: remainingTime}, nil | ||
| } | ||
|
|
||
| node := &corev1.Node{} | ||
| nodeKey := types.NamespacedName{Name: pod.Spec.NodeName} | ||
| if err := r.client.Get(ctx, nodeKey, node); err != nil { | ||
| return ctrl.Result{}, client.IgnoreNotFound(err) | ||
| } | ||
| // Pod is not scheduled on an unreachable node | ||
| if !utiltaints.TaintKeyExists(node.Spec.Taints, corev1.TaintNodeUnreachable) { | ||
| return ctrl.Result{}, nil | ||
| } | ||
|
|
||
| totalDeletionGracePeriod := time.Duration(ptr.Deref(pod.DeletionGracePeriodSeconds, 0)) + r.forcefulTerminationGracePeriod | ||
| eventMessage := fmt.Sprintf( | ||
| "Pod forcefully terminated after %s grace period due to unreachable node `%s` (triggered by `%s` annotation)", | ||
| totalDeletionGracePeriod, | ||
| node.Name, | ||
| constants.SafeToForcefullyTerminateAnnotationKey, | ||
| ) | ||
|
|
||
| podPatch := pod.DeepCopy() | ||
| podPatch.Status.Phase = corev1.PodFailed | ||
| podPatch.Status.Conditions = append(podPatch.Status.Conditions, corev1.PodCondition{ | ||
| Type: KueueFailureRecoveryConditionType, | ||
| Status: corev1.ConditionTrue, | ||
| Reason: KueueForcefulTerminationReason, | ||
| Message: eventMessage, | ||
| }) | ||
| if err := r.client.Status().Patch(ctx, podPatch, client.MergeFrom(pod)); err != nil { | ||
kshalot marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return ctrl.Result{}, err | ||
| } | ||
| r.recorder.Event(pod, corev1.EventTypeWarning, KueueForcefulTerminationReason, eventMessage) | ||
|
|
||
| return ctrl.Result{}, nil | ||
| } | ||
|
|
||
| func (r *TerminatingPodReconciler) SetupWithManager(mgr ctrl.Manager) error { | ||
| return ctrl.NewControllerManagedBy(mgr). | ||
| For(&corev1.Pod{}). | ||
| WithEventFilter(r). | ||
| Complete(r) | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.