forked from combor/k8s-mongo-labeler-sidecar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
222 lines (202 loc) · 4.92 KB
/
main.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package main
import (
"context"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/mongodb/mongo-go-driver/x/bsonx"
"github.com/mongodb/mongo-go-driver/x/network/address"
"github.com/mongodb/mongo-go-driver/x/network/command"
"github.com/mongodb/mongo-go-driver/x/network/connection"
"github.com/mongodb/mongo-go-driver/x/network/wiremessage"
"github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
type Config struct {
LabelSelector string
Namespace string
Address string
LabelAll bool
LogLevel logrus.Level
}
type Labeler struct {
Config *Config
K8scli *kubernetes.Clientset
}
func New() (*Labeler, error) {
config, err := getConfigFromEnvironment()
if err != nil {
return nil, err
}
k8scli, err := getKubeClientSet()
if err != nil {
return nil, err
}
return &Labeler{
Config: config,
K8scli: k8scli,
}, nil
}
func (l *Labeler) setPrimaryLabel() error {
primary, err := l.getMongoPrimary()
if err != nil {
return err
}
listOptions := metav1.ListOptions{
LabelSelector: l.Config.LabelSelector,
}
pods, err := l.K8scli.CoreV1().Pods(l.Config.Namespace).List(listOptions)
if err != nil {
return err
}
var found bool
logrus.Debugf("Found %d pods", len(pods.Items))
for _, pod := range pods.Items {
name := pod.GetName()
labels := pod.GetLabels()
if name == primary {
if labels["primary"] != "true" {
logrus.Infof("Setting primary to true for pod %s", name)
}
labels["primary"] = "true"
found = true
} else {
if l.Config.LabelAll == true {
if labels["primary"] != "false" {
logrus.Infof("Setting primary to false for pod %s", name)
}
labels["primary"] = "false"
} else {
delete(labels, "primary")
}
}
logrus.Debugf("Setting labels %v", labels)
pod.SetLabels(labels)
_, err := l.K8scli.CoreV1().Pods(l.Config.Namespace).Update(&pod)
if err != nil {
return err
}
}
if !found {
return fmt.Errorf("Primary not found")
}
return nil
}
func getConfigFromEnvironment() (*Config, error) {
var l string
var ok bool
if l, ok = os.LookupEnv("LABEL_SELECTOR"); !ok {
return nil, fmt.Errorf("Please export LABEL_SELECTOR")
}
config := &Config{
LabelSelector: l,
Namespace: "default",
Address: "localhost:27017",
LabelAll: false,
LogLevel: logrus.InfoLevel,
}
if l, ok = os.LookupEnv("NAMESPACE"); ok {
config.Namespace = l
}
if l, ok = os.LookupEnv("MONGO_ADDRESS"); ok {
config.Address = l
}
if _, ok = os.LookupEnv("LABEL_ALL"); ok {
config.LabelAll = true
}
if _, ok = os.LookupEnv("DEBUG"); ok {
config.LogLevel = logrus.DebugLevel
}
return config, nil
}
func getKubeClientSet() (*kubernetes.Clientset, error) {
if _, ok := os.LookupEnv("KUBERNETES_SERVICE_HOST"); ok {
config, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
return kubernetes.NewForConfig(config)
}
var kubeconfig *string
if home := homeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
return nil, err
}
return kubernetes.NewForConfig(config)
}
func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}
func (l *Labeler) getMongoPrimary() (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
var addr address.Address
addr = address.Address(l.Config.Address)
c, _, err := connection.New(ctx, addr)
if err != nil {
return "", err
}
defer c.Close()
isMaster, err := (&command.IsMaster{}).Encode()
err = c.WriteWireMessage(ctx, isMaster)
if err != nil {
return "", err
}
wm, err := c.ReadWireMessage(ctx)
if err != nil {
return "", err
}
reply := wm.(wiremessage.Reply)
doc, err := reply.GetMainDocument()
var hosts bsonx.Arr
var ok bool
if hosts, ok = doc.Lookup("hosts").ArrayOK(); !ok {
return "", fmt.Errorf("No hosts found for replica")
}
logrus.Debugf("Hosts %s", hosts)
if primaryHost, ok := doc.Lookup("primary").StringValueOK(); ok {
primary := strings.Split(primaryHost, ".")[0]
if len(primary) != 0 {
return primary, nil
}
}
return "", fmt.Errorf("Can't find primary server")
}
func main() {
labeler, err := New()
if err != nil {
logrus.Fatal(err)
}
logrus.SetLevel(labeler.Config.LogLevel)
logrus.Infof("Setting logging level to %s", labeler.Config.LogLevel.String())
ticker := time.NewTicker(5 * time.Second).C
done := make(chan bool)
for {
select {
case <-ticker:
err := labeler.setPrimaryLabel()
if err != nil {
logrus.Error(err)
}
case <-done:
logrus.Info("Done")
return
}
}
}