forked from estafette/estafette-gke-preemptible-killer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
364 lines (294 loc) · 9.73 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
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package main
import (
stdlog "log"
"math/rand"
"net/http"
"os"
"os/signal"
"runtime"
"sync"
"syscall"
"time"
"github.com/alecthomas/kingpin"
apiv1 "github.com/ericchiang/k8s/api/v1"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
const (
// annotationGKEPreemptibleKillerState is the key of the annotation to use to store the expiry datetime
annotationGKEPreemptibleKillerState string = "estafette.io/gke-preemptible-killer-state"
)
// GKEPreemptibleKillerState represents the state of gke-preemptible-killer
type GKEPreemptibleKillerState struct {
ExpiryDatetime string `json:"expiryDatetime"`
}
var (
// flags
blacklist = kingpin.Flag("blacklist-hours", "List of UTC time intervals in the form of `09:00 - 12:00, 13:00 - 18:00` in which deletion is NOT allowed").
Envar("BLACKLIST_HOURS").
Default("").
Short('b').
String()
drainTimeout = kingpin.Flag("drain-timeout", "Max time in second to wait before deleting a node.").
Envar("DRAIN_TIMEOUT").
Default("300").
Int()
kubeConfigPath = kingpin.Flag("kubeconfig", "Provide the path to the kube config path, usually located in ~/.kube/config. For out of cluster execution").
Envar("KUBECONFIG").
String()
interval = kingpin.Flag("interval", "Time in second to wait between each node check.").
Envar("INTERVAL").
Default("600").
Short('i').
Int()
prometheusAddress = kingpin.Flag("metrics-listen-address", "The address to listen on for Prometheus metrics requests.").
Envar("METRICS_LISTEN_ADDRESS").
Default(":9001").
String()
prometheusMetricsPath = kingpin.Flag("metrics-path", "The path to listen for Prometheus metrics requests.").
Envar("METRICS_PATH").
Default("/metrics").
String()
whitelist = kingpin.Flag("whitelist-hours", "List of UTC time intervals in the form of `09:00 - 12:00, 13:00 - 18:00` in which deletion is allowed and preferred").
Envar("WHITELIST_HOURS").
Default("").
Short('w').
String()
// define prometheus counter
nodeTotals = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "estafette_gke_preemptible_killer_node_totals",
Help: "Number of processed nodes.",
},
[]string{"status"},
)
// application version
version string
branch string
revision string
buildDate string
goVersion = runtime.Version()
// Various internals
randomEstafette = rand.New(rand.NewSource(time.Now().UnixNano()))
whitelistInstance WhitelistInstance
)
func init() {
// Metrics have to be registered to be exposed:
prometheus.MustRegister(nodeTotals)
}
func main() {
kingpin.Parse()
initializeLogger()
whitelistInstance.parseArguments()
kubernetes, err := NewKubernetesClient(os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT"),
os.Getenv("KUBERNETES_NAMESPACE"), *kubeConfigPath)
if err != nil {
log.Fatal().Err(err).Msg("Error initializing Kubernetes client")
}
// start prometheus
go func() {
log.Info().
Str("port", *prometheusAddress).
Str("path", *prometheusMetricsPath).
Msg("Serving Prometheus metrics...")
http.Handle(*prometheusMetricsPath, promhttp.Handler())
if err := http.ListenAndServe(*prometheusAddress, nil); err != nil {
log.Fatal().Err(err).Msg("Starting Prometheus listener failed")
}
}()
// define channel and wait group to gracefully shutdown the application
gracefulShutdown := make(chan os.Signal)
signal.Notify(gracefulShutdown, syscall.SIGTERM, syscall.SIGINT)
waitGroup := &sync.WaitGroup{}
// process nodes
go func(waitGroup *sync.WaitGroup) {
for {
log.Info().Msg("Listing all preemptible nodes for cluster...")
sleepTime := ApplyJitter(*interval)
nodes, err := kubernetes.GetPreemptibleNodes()
if err != nil {
log.Error().Err(err).Msg("Error while getting the list of preemptible nodes")
log.Info().Msgf("Sleeping for %v seconds...", sleepTime)
time.Sleep(time.Duration(sleepTime) * time.Second)
continue
}
log.Info().Msgf("Cluster has %v preemptible nodes", len(nodes.Items))
for _, node := range nodes.Items {
waitGroup.Add(1)
err := processNode(kubernetes, node)
waitGroup.Done()
if err != nil {
nodeTotals.With(prometheus.Labels{"status": "failed"}).Inc()
log.Error().
Err(err).
Str("host", *node.Metadata.Name).
Msg("Error while processing node")
continue
}
}
log.Info().Msgf("Sleeping for %v seconds...", sleepTime)
time.Sleep(time.Duration(sleepTime) * time.Second)
}
}(waitGroup)
signalReceived := <-gracefulShutdown
log.Info().
Msgf("Received signal %v. Sending shutdown and waiting on goroutines...", signalReceived)
waitGroup.Wait()
log.Info().Msg("Shutting down...")
}
func initializeLogger() {
// log as severity for stackdriver logging to recognize the level
zerolog.LevelFieldName = "severity"
// set some default fields added to all logs
log.Logger = zerolog.New(os.Stdout).With().
Timestamp().
Str("app", "estafette-gke-preemptible-killer").
Str("version", version).
Logger()
// use zerolog for any logs sent via standard log library
stdlog.SetFlags(0)
stdlog.SetOutput(log.Logger)
// log startup message
log.Info().
Str("branch", branch).
Str("revision", revision).
Str("buildDate", buildDate).
Str("goVersion", goVersion).
Msg("Starting estafette-gke-preemptible-killer...")
}
// getCurrentNodeState return the state of the node by reading its metadata annotations
func getCurrentNodeState(node *apiv1.Node) (state GKEPreemptibleKillerState) {
var ok bool
state.ExpiryDatetime, ok = node.Metadata.Annotations[annotationGKEPreemptibleKillerState]
if !ok {
state.ExpiryDatetime = ""
}
return
}
// getDesiredNodeState define the state of the node, update node annotations if not present
func getDesiredNodeState(k KubernetesClient, node *apiv1.Node) (state GKEPreemptibleKillerState, err error) {
t := time.Unix(*node.Metadata.CreationTimestamp.Seconds, 0).UTC()
drainTimeoutTime := time.Duration(*drainTimeout) * time.Second
// 43200 = 12h * 60m * 60s
randomTimeBetween0to12 := time.Duration(randomEstafette.Intn((43200)-*drainTimeout)) * time.Second
timeToBeAdded := 12*time.Hour + drainTimeoutTime + randomTimeBetween0to12
expiryDatetime := whitelistInstance.getExpiryDate(t, timeToBeAdded)
state.ExpiryDatetime = expiryDatetime.Format(time.RFC3339)
log.Info().
Str("host", *node.Metadata.Name).
Msgf("Annotation not found, adding %s to %s", annotationGKEPreemptibleKillerState, state.ExpiryDatetime)
err = k.SetNodeAnnotation(*node.Metadata.Name, annotationGKEPreemptibleKillerState, state.ExpiryDatetime)
if err != nil {
log.Warn().
Err(err).
Str("host", *node.Metadata.Name).
Msg("Error updating node metadata, continuing with node CreationTimestamp value instead")
state.ExpiryDatetime = t.Format(time.RFC3339)
nodeTotals.With(prometheus.Labels{"status": "failed"}).Inc()
return
}
nodeTotals.With(prometheus.Labels{"status": "annotated"}).Inc()
return
}
// processNode returns the time to delete a node after n minutes
func processNode(k KubernetesClient, node *apiv1.Node) (err error) {
// get current node state
state := getCurrentNodeState(node)
// set node state if doesn't already have annotations
if state.ExpiryDatetime == "" {
state, _ = getDesiredNodeState(k, node)
}
// compute time difference
now := time.Now().UTC()
expiryDatetime, err := time.Parse(time.RFC3339, state.ExpiryDatetime)
if err != nil {
log.Error().
Err(err).
Str("host", *node.Metadata.Name).
Msgf("Error parsing expiry datetime with value '%s'", state.ExpiryDatetime)
return
}
timeDiff := expiryDatetime.Sub(now).Minutes()
// check if we need to delete the node or not
if timeDiff < 0 {
log.Info().
Str("host", *node.Metadata.Name).
Msgf("Node expired %.0f minute(s) ago, deleting...", timeDiff)
// set node unschedulable
err = k.SetUnschedulableState(*node.Metadata.Name, true)
if err != nil {
log.Error().
Err(err).
Str("host", *node.Metadata.Name).
Msg("Error setting node to unschedulable state")
return
}
var projectID string
var zone string
projectID, zone, err = k.GetProjectIdAndZoneFromNode(*node.Metadata.Name)
if err != nil {
log.Error().
Err(err).
Str("host", *node.Metadata.Name).
Msg("Error getting project id and zone from node")
return
}
var gcloud GCloudClient
gcloud, err = NewGCloudClient(projectID, zone)
if err != nil {
log.Error().
Err(err).
Str("host", *node.Metadata.Name).
Msg("Error creating GCloud client")
return
}
// drain kubernetes node
err = k.DrainNode(*node.Metadata.Name, *drainTimeout)
if err != nil {
log.Error().
Err(err).
Str("host", *node.Metadata.Name).
Msg("Error draining kubernetes node")
return
}
// drain kube-dns from kubernetes node
err = k.DrainKubeDNSFromNode(*node.Metadata.Name, *drainTimeout)
if err != nil {
log.Error().
Err(err).
Str("host", *node.Metadata.Name).
Msg("Error draining kube-dns from kubernetes node")
return
}
// delete node from kubernetes cluster
err = k.DeleteNode(*node.Metadata.Name)
if err != nil {
log.Error().
Err(err).
Str("host", *node.Metadata.Name).
Msg("Error deleting node")
return
}
// delete gcloud instance
err = gcloud.DeleteNode(*node.Metadata.Name)
if err != nil {
log.Error().
Err(err).
Str("host", *node.Metadata.Name).
Msg("Error deleting GCloud instance")
return
}
nodeTotals.With(prometheus.Labels{"status": "killed"}).Inc()
log.Info().
Str("host", *node.Metadata.Name).
Msg("Node deleted")
return
}
nodeTotals.With(prometheus.Labels{"status": "skipped"}).Inc()
log.Info().
Str("host", *node.Metadata.Name).
Msgf("%.0f minute(s) to go before kill, keeping node", timeDiff)
return
}