-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsunshine.go
148 lines (128 loc) · 4.65 KB
/
sunshine.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
package main
import (
"fmt"
appsV1 "k8s.io/api/apps/v1"
coreV1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
listerAppsV1 "k8s.io/client-go/listers/apps/v1"
listerCoreV1 "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
"log"
"os"
"strconv"
"time"
)
var err error
var config *rest.Config
var restartNumber string
func getKubeConfig() *kubernetes.Clientset {
kubeconfig := fmt.Sprintf("%s%s", os.Getenv("HOME"), "/.kube/config")
if config, err = rest.InClusterConfig(); err != nil {
fmt.Println(err)
if config, err = clientcmd.BuildConfigFromFlags("", kubeconfig); err != nil {
panic(err.Error())
}
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
return clientset
}
func createInformer(clientset *kubernetes.Clientset, listTime time.Duration) (informers.SharedInformerFactory, listerAppsV1.DeploymentLister, listerCoreV1.PodLister) {
informerFactory := informers.NewSharedInformerFactory(clientset, listTime)
podInformer := informerFactory.Core().V1().Pods()
deployInformer := informerFactory.Apps().V1().Deployments()
pinformer := podInformer.Informer()
podLister := podInformer.Lister()
deployLister := deployInformer.Lister()
pinformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: onAdd,
UpdateFunc: onUpdate,
DeleteFunc: onDelete,
})
log.Println("informerFactory deployLister podLister initialization completed")
return informerFactory, deployLister, podLister
}
func offUnHealthyDeployment(deploy []*appsV1.Deployment,
namespace string,
clientset *kubernetes.Clientset,
deployName string) error {
for _, dp := range deploy {
//找到对应的deployName
if dp.Name == deployName {
//判断deployment是否是属于开启状态 不等于0就是开启状态
if dp.Status.UpdatedReplicas != 0 && dp.Status.AvailableReplicas == 0 {
//判断当前运行的pod 等于0就是deployment是开启状态且running的pod为0 确认为0了以后才可以执行
var replicas int32 = 0
dp.Spec.Replicas = &replicas
_, err := clientset.AppsV1().Deployments(dp.Namespace).Update(dp)
if err != nil {
log.Fatal("deployment replica set to 0 failed", err)
}
}
}
}
return nil
}
func resouceRegistry(podLister listerCoreV1.PodLister, deployLister listerAppsV1.DeploymentLister, namespace string) ([]*coreV1.Pod, []*appsV1.Deployment) {
pod, err := podLister.Pods(namespace).List(labels.Everything())
if err != nil {
log.Fatalf("PodLister Get Pod List Fatal %s\n", err)
}
deploy, err := deployLister.Deployments(namespace).List(labels.Everything())
if err != nil {
log.Fatalf("DeployLister Get Deployment List Fatal %s\n", err)
}
return pod, deploy
}
func offUnHealthyApp(pod []*coreV1.Pod, namespace string, restartNumber int32, deploy []*appsV1.Deployment, clientset *kubernetes.Clientset) {
var rslice []string
for _, p := range pod {
//判断是否为ReplicaSet资源
//这不是一个呆b行为 二次range是有原因的
for _, owner := range p.OwnerReferences {
//完成kind判断以后 就可以避开静态pod不存在这个字段而报错 index out of range [0] with length 0
if owner.Kind == "ReplicaSet" &&
len(p.Status.ContainerStatuses) != 0 &&
p.Status.ContainerStatuses[0].Ready == false &&
p.Status.ContainerStatuses[0].RestartCount >= restartNumber {
//将获取的relicaset名字切割末尾的11位字符串(包含-)得到deployment名字 存入切片为了pod去重
rslice = append(rslice, p.OwnerReferences[0].Name[0:len(p.OwnerReferences[0].Name)-11])
}
}
}
if len(rslice) != 0 {
offUnHealthyDeployment(deploy, namespace, clientset, rslice[0])
}
return
}
func init() {
restartNumber = fmt.Sprintf(os.Getenv("POD_RESTART_NUMBER"))
}
func main() {
log.Println("Project address: https://github.com/huangjc7/sunshine")
r, _ := strconv.ParseInt(restartNumber, 10, 32) //string转int32
clientset := getKubeConfig()
stopCh := make(chan struct{})
informerFactory, deployLister, podLister := createInformer(clientset, time.Minute*5)
informerFactory.Start(stopCh)
log.Println("informerFactory started")
informerFactory.WaitForCacheSync(stopCh)
log.Println("Start successfully")
for {
time.Sleep(time.Second * 2)
pod, deploy := resouceRegistry(podLister, deployLister, "")
offUnHealthyApp(pod, "", int32(r), deploy, clientset)
}
}
func onAdd(obj interface{}) {}
func onUpdate(old, new interface{}) {}
func onDelete(obj interface{}) {
pod := obj.(*coreV1.Pod) //断言 是否是deployment类型
log.Printf("Delete Pod Namespace:%s Pod Name: %s\n", pod.Namespace, pod.Name)
}