-
Notifications
You must be signed in to change notification settings - Fork 1
/
k8s.go
executable file
·80 lines (67 loc) · 2.04 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
package main
import (
"sync"
"time"
corev1 "k8s.io/api/core/v1"
extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
v1beta1 "k8s.io/api/networking/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kubernetes "k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
type k8sState struct {
Ingresses []v1beta1.Ingress `json:"ingresses"`
IngressesExtensions []extensionsv1beta1.Ingress `json:"ingressesExtension"`
Pods []corev1.Pod `json:"pods"`
Services []corev1.Service `json:"services"`
Timestamp time.Time `json:"timestamp"`
}
var (
clientset *kubernetes.Clientset = connect()
state k8sState = loadK8sState()
stateLoading sync.Mutex
)
func k8sStateCached(duration time.Duration) k8sState {
stateLoading.Lock()
if duration < time.Since(state.Timestamp) {
logger.Println("Refreshing k8s state, due to being outdated")
state = loadK8sState()
}
stateLoading.Unlock()
return state
}
func connect() *kubernetes.Clientset {
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
return clientset
}
func loadK8sState() k8sState {
pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
services, err := clientset.CoreV1().Services("").List(metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
ingresses, err := clientset.NetworkingV1beta1().Ingresses("").List(v1.ListOptions{})
// Fallback to old ingress definitions
ingressesExtensions, errExtensions := clientset.ExtensionsV1beta1().Ingresses("").List(v1.ListOptions{})
if err != nil && errExtensions != nil {
panic(err.Error())
}
return k8sState{
Ingresses: ingresses.Items,
IngressesExtensions: ingressesExtensions.Items,
Pods: pods.Items,
Services: services.Items,
Timestamp: time.Now(),
}
}