-
Notifications
You must be signed in to change notification settings - Fork 0
/
k8s.go
89 lines (81 loc) · 2.64 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
package client
import (
"context"
"fmt"
"github.com/just1689/kubernetes-warm-images/health"
"github.com/just1689/kubernetes-warm-images/util"
"github.com/sirupsen/logrus"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
var (
emptyArr = []string{}
HealthNameCastToPod = "CAST_TO_POD"
)
func ConnectToKubernetesAPI() *K8sClient {
result := &K8sClient{}
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
result.clientSet, err = kubernetes.NewForConfig(config)
if err != nil {
logrus.Errorln(util.LogPrepend(3, "could not connect to Kubernetes API in-cluster. Exiting"))
logrus.Panicln(err.Error())
}
return result
}
type K8sClient struct {
clientSet *kubernetes.Clientset
}
func (cl *K8sClient) WatchImages(namespaces chan string, nsIgnore []string) chan string {
result := make(chan string, 256)
for namespace := range namespaces {
if namespace == "*" {
namespace = ""
}
logrus.Infoln(util.LogPrepend(3, fmt.Sprintf("New watcher ns: '%s'", namespace)))
wi := cl.newWatcher(namespace)
go handleWatch(namespace, wi, result, nsIgnore)
}
return result
}
func handleWatch(namespace string, wi watch.Interface, imgChan chan string, nsIgnore []string) {
logrus.Infoln(util.LogPrepend(3, fmt.Sprintf("handleWatch namespace: '%s'", namespace)))
for event := range wi.ResultChan() {
util.StrArrToChan(getImages(event, nsIgnore), imgChan)
}
}
func getImages(event watch.Event, nsIgnore []string) []string {
if event.Type != "ADDED" {
return emptyArr
}
if p, ok := event.Object.(*v1.Pod); !ok {
logrus.Errorln(util.LogPrepend(3, fmt.Sprintf("could not cast as pod %s", event.Object)))
health.GlobalHealth.NotifyFail <- HealthNameCastToPod
return emptyArr
} else {
health.GlobalHealth.NotifyOK <- HealthNameCastToPod
if util.StrExistsIn(p.ObjectMeta.Namespace, nsIgnore) {
logrus.Infoln(util.LogPrepend(3, fmt.Sprintf("ignoring pod: '%s' as namespace: '%s'", p.ObjectMeta.Name, p.ObjectMeta.Namespace)))
return emptyArr
}
result := make([]string, len(p.Spec.Containers))
for i, container := range p.Spec.Containers {
result[i] = container.Image
}
return result
}
}
func (cl *K8sClient) newWatcher(namespace string) (wi watch.Interface) {
logrus.Infoln(util.LogPrepend(3, fmt.Sprintf("watching pods in ns: '%s'", namespace)))
var err error
if wi, err = cl.clientSet.CoreV1().Pods(namespace).Watch(context.TODO(), metav1.ListOptions{}); err != nil {
logrus.Errorln(util.LogPrepend(3, fmt.Sprintf("could not watch Pods in namespace `%s`", namespace)))
return
}
return
}