forked from target/pod-reaper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
80 lines (74 loc) · 1.91 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"fmt"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/rest"
"os"
"time"
)
func clientSet() *kubernetes.Clientset {
config, err := rest.InClusterConfig()
if err != nil {
panic(err)
}
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err)
}
return clientSet
}
func getPods(clientSet *kubernetes.Clientset, options options) *v1.PodList {
coreClient := clientSet.CoreV1()
pods := coreClient.Pods(options.namespace)
listOptions := v1.ListOptions{}
if options.labelExclusion != nil || options.labelRequirement != nil {
selector := labels.NewSelector()
if options.labelExclusion != nil {
selector = selector.Add(*options.labelExclusion)
}
if options.labelRequirement != nil {
selector = selector.Add(*options.labelRequirement)
}
listOptions.LabelSelector = selector.String()
}
podList, err := pods.List(listOptions)
if err != nil {
panic(err)
}
return podList
}
func reap(clientSet *kubernetes.Clientset, pod v1.Pod, reason string) {
fmt.Printf("Reaping Pod %s because %s\n", pod.Name, reason)
err := clientSet.Core().Pods(pod.Namespace).Delete(pod.Name, nil)
if err != nil {
// log the error, but continue on
fmt.Fprintf(os.Stderr, "unable to delete pod %s because %s", pod.Name, err)
}
}
func scytheCycle(clientSet *kubernetes.Clientset, options options) {
pods := getPods(clientSet, options)
for _, pod := range pods.Items {
shouldReap, reason := options.rules.ShouldReap(pod)
if shouldReap {
reap(clientSet, pod, reason)
}
}
}
func main() {
clientSet := clientSet()
options, err := loadOptions()
if err != nil {
panic(err)
}
runForever := options.runDuration == 0
cutoff := time.Now().Add(options.runDuration)
for {
scytheCycle(clientSet, options)
if !runForever && time.Now().After(cutoff) {
os.Exit(0) // successful exit
}
time.Sleep(options.pollInterval)
}
}