|
| 1 | +package util |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/sirupsen/logrus" |
| 8 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 9 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 10 | + "k8s.io/apimachinery/pkg/labels" |
| 11 | + "k8s.io/client-go/kubernetes" |
| 12 | +) |
| 13 | + |
| 14 | +// CleanupTerminatingPods forcibly deletes pods with the specified component label |
| 15 | +// that have been stuck in the Terminating state for longer than the given |
| 16 | +// threshold. |
| 17 | +func CleanupTerminatingPods(ctx context.Context, client kubernetes.Interface, namespace, component string, threshold time.Duration) { |
| 18 | + if client == nil || namespace == "" || component == "" { |
| 19 | + return |
| 20 | + } |
| 21 | + |
| 22 | + selector := labels.Set{"app.kubernetes.io/component": component}.AsSelector().String() |
| 23 | + ticker := time.NewTicker(threshold / 2) |
| 24 | + defer ticker.Stop() |
| 25 | + |
| 26 | + for { |
| 27 | + select { |
| 28 | + case <-ctx.Done(): |
| 29 | + return |
| 30 | + case <-ticker.C: |
| 31 | + pods, err := client.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{LabelSelector: selector}) |
| 32 | + if err != nil { |
| 33 | + logrus.Errorf("(CleanupTerminatingPods) list pods error: %v", err) |
| 34 | + continue |
| 35 | + } |
| 36 | + |
| 37 | + for i := range pods.Items { |
| 38 | + pod := &pods.Items[i] |
| 39 | + if pod.DeletionTimestamp == nil { |
| 40 | + continue |
| 41 | + } |
| 42 | + if time.Since(pod.DeletionTimestamp.Time) < threshold { |
| 43 | + continue |
| 44 | + } |
| 45 | + |
| 46 | + logrus.Infof("(CleanupTerminatingPods) force deleting stuck pod %s/%s", pod.Namespace, pod.Name) |
| 47 | + grace := int64(0) |
| 48 | + if err := client.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{GracePeriodSeconds: &grace}); err != nil && !apierrors.IsNotFound(err) { |
| 49 | + logrus.Errorf("(CleanupTerminatingPods) delete pod %s/%s error: %v", pod.Namespace, pod.Name, err) |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments