-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathk8s.go
72 lines (66 loc) · 1.79 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
package kubernetes
import (
"context"
"os"
"strings"
"github.com/bryopsida/http-healthcheck-sidecar/config"
"github.com/gofiber/fiber/v2/log"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
func getNamespace() string {
// namespace will be in /var/run/secrets/kubernetes.io/serviceaccount/namespace
data, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
if err != nil {
panic(err.Error())
}
return string(data)
}
func returnOverrideState() bool {
return config.GetStatusOverrideState()
}
func fetchPodState(podName string) *v1.Pod {
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
pod, err := clientset.CoreV1().Pods(getNamespace()).Get(context.TODO(), podName, metav1.GetOptions{})
if err != nil {
panic(err.Error())
}
return pod
}
func IsPodHealthy(podName string) bool {
log.Info("Fetching status for pod %s", podName)
if config.IsStatusOverriden() {
return config.GetStatusOverrideState()
} else {
podState := fetchPodState(podName)
for _, containerStatus := range podState.Status.ContainerStatuses {
if !containerStatus.Ready {
return false
}
}
return true
}
}
func IsPodContainerHealthy(podName string, containerName string) bool {
log.Info("Fetching status for container %s on pod %s", containerName, podName)
if config.IsStatusOverriden() {
return config.GetStatusOverrideState()
} else {
podState := fetchPodState(podName)
for _, containerStatus := range podState.Status.ContainerStatuses {
if strings.ToLower(containerStatus.Name) == strings.ToLower(containerName) {
return containerStatus.Ready
}
}
return false
}
}