Skip to content

Commit

Permalink
some refinements and bugfix
Browse files Browse the repository at this point in the history
  • Loading branch information
emamihe committed Jan 30, 2024
1 parent e7fc1a4 commit 41b0b16
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions scripts/gitlab_cleanup/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -14,32 +17,35 @@ 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)
}
}
}
}

0 comments on commit 41b0b16

Please sign in to comment.