-
Notifications
You must be signed in to change notification settings - Fork 0
/
drain.go
80 lines (72 loc) · 2.2 KB
/
drain.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 k8s
import (
"context"
"fmt"
v1 "k8s.io/api/core/v1"
policyv1beta1 "k8s.io/api/policy/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"github.com/wonderivan/logger"
)
const (
EvictionKind = "Eviction"
PolicyGroupVersion = "policy/v1beta1"
)
func EvictNodePods(nodeName string, k8sClient *kubernetes.Clientset) error {
pods, err := k8sClient.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{
FieldSelector: "spec.nodeName=" + nodeName,
})
if err != nil {
return err
}
for _, i := range pods.Items {
err := EvictPod(k8sClient, i, PolicyGroupVersion)
if err != nil {
return err
}
}
return nil
}
func EvictPod(k8sClient *kubernetes.Clientset, pod v1.Pod, policyGroupVersion string) error {
deleteOptions := &metav1.DeleteOptions{}
eviction := &policyv1beta1.Eviction{
TypeMeta: metav1.TypeMeta{
APIVersion: policyGroupVersion,
Kind: EvictionKind,
},
ObjectMeta: metav1.ObjectMeta{
Name: pod.Name,
Namespace: pod.Namespace,
},
DeleteOptions: deleteOptions,
}
return k8sClient.PolicyV1beta1().Evictions(eviction.Namespace).Evict(context.TODO(), eviction)
}
func CordonUnCordon(k8sClient *kubernetes.Clientset, nodeName string, cordoned bool) error {
node, err := GetNodeByName(k8sClient, nodeName)
if err != nil {
return err
}
if node.Spec.Unschedulable == cordoned {
logger.Info("Node %s is already Uncordoned, skip...", nodeName)
return nil
}
node.Spec.Unschedulable = cordoned
_, err = k8sClient.CoreV1().Nodes().Update(context.TODO(), node, metav1.UpdateOptions{})
if err != nil {
return fmt.Errorf("error setting cordoned state for %s node err: %v", nodeName, err)
}
return nil
}
func DeleteNamespace(ctx context.Context, client *kubernetes.Clientset, namespace string, ns *v1.Namespace) error {
deleteNs, err := client.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{})
if err != nil {
return err
}
if deleteNs.ObjectMeta.DeletionTimestamp.IsZero() {
err = client.CoreV1().Namespaces().Delete(context.Background(), namespace, metav1.DeleteOptions{})
} else {
_, err = client.CoreV1().Namespaces().Finalize(context.Background(), ns, metav1.UpdateOptions{})
}
return err
}