From 41b0b16f13f908dec2b895581f2f414f42a0b95b Mon Sep 17 00:00:00 2001 From: Hamid Emamian Date: Tue, 30 Jan 2024 13:33:20 +0300 Subject: [PATCH] some refinements and bugfix --- scripts/gitlab_cleanup/main.go | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/scripts/gitlab_cleanup/main.go b/scripts/gitlab_cleanup/main.go index 16315e31e..ccfbe1cee 100644 --- a/scripts/gitlab_cleanup/main.go +++ b/scripts/gitlab_cleanup/main.go @@ -3,8 +3,11 @@ package main import ( "context" "fmt" + "log" "os" + "strconv" "time" + "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -14,27 +17,31 @@ import ( func main() { config, err := rest.InClusterConfig() if err != nil { - fmt.Printf("Error creating in-cluster config: %s\n", err) - os.Exit(1) + log.Fatalf("Error creating in-cluster config: %s\n", err) } clientset, err := kubernetes.NewForConfig(config) if err != nil { - fmt.Printf("Error creating clientset: %s\n", err) - os.Exit(1) + log.Fatalf("Error creating clientset: %s\n", err) + } + + podAgeThresholdHours := 12 // default + if envVal, exists := os.LookupEnv("POD_AGE_THRESHOLD_HOURS"); exists { + if val, err := strconv.Atoi(envVal); err == nil { + podAgeThresholdHours = val + } } pods, err := clientset.CoreV1().Pods("gitlab").List(context.Background(), metav1.ListOptions{ - LabelSelector: "app=gitlab,selector=runner", + LabelSelector: "pod", }) if err != nil { - fmt.Printf("Error listing pods: %s\n", err) - os.Exit(1) + log.Fatalf("Error listing pods: %s\n", err) } for _, pod := range pods.Items { - if time.Since(pod.CreationTimestamp.Time).Hours() > 12 { - fmt.Printf("Deleting pod %s which is older than 12 hours\n", pod.Name) + if time.Since(pod.CreationTimestamp.Time).Hours() > float64(podAgeThresholdHours) && strings.HasPrefix(pod.Labels["pod"], "runner-") { + fmt.Printf("Deleting pod %s which is older than %d hours\n", pod.Name, podAgeThresholdHours) err := clientset.CoreV1().Pods(pod.Namespace).Delete(context.Background(), pod.Name, metav1.DeleteOptions{}) if err != nil { fmt.Printf("Error deleting pod %s: %s\n", pod.Name, err) @@ -42,4 +49,3 @@ func main() { } } } -