-
Notifications
You must be signed in to change notification settings - Fork 13
/
k8s.go
90 lines (83 loc) · 2.11 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
90
package k8s
import (
"context"
"github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"path/filepath"
)
type Provider struct {
namespace string
clientset *kubernetes.Clientset
}
func NewInClusterProvider(namespace string) (*Provider, error) {
if namespace == "" {
namespace = "default"
}
config, err := rest.InClusterConfig()
if err != nil {
return nil, errors.Wrap(err, "failed to get in cluster config")
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, errors.Wrap(err, "failed to get in cluster clientset")
}
return &Provider{
namespace: namespace,
clientset: clientset,
}, nil
}
func NewOutOfClusterProvider(namespace string) (*Provider, error) {
if namespace == "" {
namespace = "default"
}
dir, _ := homedir.Dir()
kubeconfig := filepath.Join(dir, ".kube", "config")
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
return nil, errors.Wrap(err, "failed to get in cluster config")
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, errors.Wrap(err, "failed to get in cluster clientset")
}
return &Provider{
namespace: namespace,
clientset: clientset,
}, nil
}
func (p *Provider) Pods(ctx context.Context) (map[string]string, error) {
pods, err := p.clientset.CoreV1().Pods(p.namespace).List(
ctx,
metav1.ListOptions{
LabelSelector: "app = graphik",
})
if err != nil {
return nil, err
}
data := map[string]string{}
p.loopPods(pods, data)
return data, nil
}
func (p *Provider) loopPods(pods *v1.PodList, addrs map[string]string) {
for _, pod := range pods.Items {
if pod.Status.Phase != v1.PodRunning {
continue
}
//for _, condition := range pod.Status.Conditions {
// if condition.Type == v1.PodReady && condition.Status != v1.ConditionTrue {
// p.loopPods(pods, addrs)
// }
//}
addr := pod.Status.PodIP
if addr == "" {
continue
}
addrs[pod.Name] = addr
}
}