-
Notifications
You must be signed in to change notification settings - Fork 0
/
k8s.go
257 lines (210 loc) · 7.79 KB
/
k8s.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package k8s
import (
"bytes"
"context"
"flag"
"io"
"os"
"path/filepath"
"strconv"
"time"
"github.com/kevin-shelaga/cronjob-cleaner/logging"
batch "k8s.io/api/batch/v1"
core "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kubernetes "k8s.io/client-go/kubernetes"
rest "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
"k8s.io/client-go/util/retry"
_ "k8s.io/client-go/plugin/pkg/client/auth" //all auths
)
//k8s interface for k8s package
type k8s interface {
Connect(inCluster bool) *kubernetes.Clientset
GetNamespaces([]string) []string
GetjobsForCleanup(namespace string, activeDeadlineSeconds float64) []batch.Job
GetJobsPod(job batch.Job) *core.PodList
GetPodLogs(pod core.Pod, tail *int64)
DeletePod(pod core.Pod)
}
//KubernetesAPI is the struct for k8s
type KubernetesAPI struct {
Clientset kubernetes.Interface
}
//Connect returns new kubernetes Client
func (k KubernetesAPI) Connect(inCluster bool) kubernetes.Interface {
var clientset kubernetes.Interface
if k.Clientset == nil && inCluster {
logging.Information("In cluster config will be used!")
logging.Information("Connecting...")
// creates the in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
logging.Error(err.Error())
panic(err.Error())
}
// creates the Clientset
cs, err := kubernetes.NewForConfig(config)
if err != nil {
logging.Error(err.Error())
panic(err.Error())
}
clientset = cs
logging.Information("Connected!")
} else if k.Clientset == nil && !inCluster {
logging.Information("Out of cluster config will be used!")
logging.Information("Connecting...")
var kubeconfig *string
if home := homedir.HomeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
logging.Error(err.Error())
panic(err.Error())
}
// creates the Clientset
cs, err := kubernetes.NewForConfig(config)
if err != nil {
logging.Error(err.Error())
panic(err.Error())
}
clientset = cs
logging.Information("Connected!")
}
return clientset
}
//GetNamespaces returns slice of all namespaces
func (k KubernetesAPI) GetNamespaces(excludedNamespaces []string) []string {
var result []string
namespaces, err := k.Clientset.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{})
if err != nil {
logging.Error(err.Error())
}
logging.Information("There is " + strconv.Itoa(len(namespaces.Items)) + " namespace(s) in the cluster!")
for _, n := range namespaces.Items {
logging.Information(n.Name)
result = append(result, n.Name)
}
//Remove ExcludedNamespaces
if excludedNamespaces != nil {
loop:
for i := 0; i < len(result); i++ {
url := result[i]
for _, rem := range excludedNamespaces {
if url == rem {
result = append(result[:i], result[i+1:]...)
i-- // Important: decrease index
continue loop
}
}
}
}
return result
}
//GetjobsForCleanup return list of jobs in the requested namespace that exceed the max run time in second
func (k KubernetesAPI) GetjobsForCleanup(namespace string, activeDeadlineSeconds float64) []batch.Job {
var jobsToCleanup []batch.Job
jobs, err := k.Clientset.BatchV1().Jobs(namespace).List(context.TODO(), metav1.ListOptions{})
if err != nil {
logging.Error(err.Error())
}
logging.Information("There is " + strconv.Itoa(len(jobs.Items)) + " job(s) in the " + namespace + " namespace!")
for _, j := range jobs.Items {
if j.Status.Active == 1 && j.Status.Failed == 0 && j.Status.CompletionTime == nil {
if time.Now().Sub(j.CreationTimestamp.UTC()).Seconds() > activeDeadlineSeconds {
logging.Warning("Job " + j.Name + " has been running for " + strconv.FormatFloat(time.Now().Sub(j.CreationTimestamp.UTC()).Seconds(), 'f', 6, 64) + " seconds and has been flagged for cleanup due to exceeding the active deadline seconds of " + strconv.FormatFloat(activeDeadlineSeconds, 'f', 6, 64))
jobsToCleanup = append(jobsToCleanup, j)
} else {
logging.Information("Job " + j.Name + " has been running for " + strconv.FormatFloat(time.Now().Sub(j.CreationTimestamp.UTC()).Seconds(), 'f', 6, 64) + " seconds and has not exceeded the active deadline seconds of " + strconv.FormatFloat(activeDeadlineSeconds, 'f', 6, 64))
}
} else {
logging.Information("Job " + j.Name + " is not active")
}
cleanFailedJob, _ := strconv.ParseBool(os.Getenv("CleanFailedJob"))
if cleanFailedJob == true && j.Status.Failed == 1 {
logging.Warning("Job " + j.Name + " has been flagged for cleanup due to being in a failed state")
jobsToCleanup = append(jobsToCleanup, j)
}
}
return jobsToCleanup
}
//GetJobsPod gets the pod associated to a job based on the job-name label
func (k KubernetesAPI) GetJobsPod(job batch.Job) *core.PodList {
pods, err := k.Clientset.CoreV1().Pods(job.Namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: "job-name=" + job.Name})
if err != nil {
logging.Error(err.Error())
return nil
}
if pods != nil && len(pods.Items) > 0 {
if len(pods.Items) > 1 {
logging.Error("Found more than 1 pod matching label " + ("job-name:" + job.Name) + ", cleanup will be skipped")
return nil
}
logging.Information("Found pod " + pods.Items[0].Name + " for job " + job.Name + " with label " + ("job-name:" + job.Name))
return pods
} else {
return nil
}
}
//GetPodLogs logs a list of logs for a given pod name
func (k KubernetesAPI) GetPodLogs(pod core.Pod, tail *int64) {
logging.Information("Getting the last " + strconv.FormatInt(*tail, 10) + " logs for pod " + pod.Name)
for _, c := range pod.Spec.Containers {
req := k.Clientset.CoreV1().Pods(pod.Namespace).GetLogs(pod.Name, &core.PodLogOptions{Container: c.Name, TailLines: tail})
podLogs, err := req.Stream(context.TODO())
if err != nil {
logging.Error("error in opening stream")
}
defer podLogs.Close()
buf := new(bytes.Buffer)
_, err = io.Copy(buf, podLogs)
if err != nil {
logging.Error("error in copy information from podLogs to buf")
}
logging.Information(buf.String())
}
}
//DeletePod deletes pod from kubernetes
func (k KubernetesAPI) DeletePod(pod core.Pod) {
logging.Warning("Deleting pod " + pod.Name + "...")
derr := k.Clientset.CoreV1().Pods(pod.Namespace).Delete(context.TODO(), pod.Name, metav1.DeleteOptions{})
if derr != nil {
logging.Error(derr.Error())
return
}
logging.Warning("Deleted pod " + pod.Name + "!")
}
//DeleteJob deletes pod from kubernetes
func (k KubernetesAPI) DeleteJob(job batch.Job) {
logging.Warning("Deleting job " + job.Name + "...")
derr := k.Clientset.BatchV1().Jobs(job.Namespace).Delete(context.TODO(), job.Name, metav1.DeleteOptions{})
if derr != nil {
logging.Error(derr.Error())
return
}
logging.Warning("Deleted jod " + job.Name + "!")
}
//LabelJob labels a job when the underlying pod has been identified for cleanup
func (k KubernetesAPI) LabelJob(job batch.Job) {
logging.Warning("Labeling job " + job.Name + "...")
retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
result, getErr := k.Clientset.BatchV1().Jobs(job.Namespace).Get(context.TODO(), job.Name, metav1.GetOptions{})
if getErr != nil {
logging.Error("Failed to get latest version of Job: " + getErr.Error())
}
time.Now().UnixNano()
result.Labels["deleted-pod-timestamp"] = strconv.FormatInt(time.Now().Unix(), 10)
_, updateErr := k.Clientset.BatchV1().Jobs(job.Namespace).Update(context.TODO(), result, metav1.UpdateOptions{})
return updateErr
})
if retryErr != nil {
logging.Error("Update failed: " + retryErr.Error())
}
logging.Warning("Labeled pod " + job.Name + "!")
}