-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathk8s.go
68 lines (51 loc) · 1.53 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
package main
import (
"context"
"fmt"
"sort"
"time"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
func getNode(ctx context.Context, client *kubernetes.Clientset, olderThan time.Duration) (string, error) {
nodeGetter := client.CoreV1().Nodes()
nodes, err := nodeGetter.List(ctx, metav1.ListOptions{})
if err != nil {
return "", err
}
return oldestNode(nodes.Items, olderThan), nil
}
func oldestNode(nodes []corev1.Node, olderThan time.Duration) string {
sortNodes(nodes)
for _, node := range nodes {
log.Debugf("node: %s, creation: %s", node.Name, node.CreationTimestamp)
}
if time.Now().Sub(nodes[0].CreationTimestamp.Time) >= olderThan {
log.Infof("kubernetes node: %s will be terminated", nodes[0].Name)
return nodes[0].Spec.ProviderID
}
return ""
}
func sortNodes(nodes []corev1.Node) {
sort.Slice(nodes, func(i int, j int) bool {
return nodes[i].CreationTimestamp.Time.Before(nodes[j].CreationTimestamp.Time)
})
}
func createClientConfig(kubeconfig string) (*rest.Config, error) {
if kubeconfig != "" {
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
return nil, fmt.Errorf("error creating kube config from config file: %s", err)
}
return config, nil
}
config, err := rest.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("error creating kube config from in cluster config: %s", err)
}
return config, nil
}