-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
166 lines (147 loc) · 4.52 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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
"k8s.io/client-go/rest"
"github.com/r3labs/diff"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
coreV1 "k8s.io/api/core/v1"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
)
var clientset *kubernetes.Clientset
const externalIPLabel = "k3s.io/external-ip"
const flannelPublicIPOverrideLabel = "flannel.alpha.coreos.com/public-ip-overwrite"
const flannelPublicIPLabel = "flannel.alpha.coreos.com/public-ip"
func bootstrap() {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
zerolog.TimeFieldFormat = time.RFC3339Nano
log.Logger = log.Output(zerolog.ConsoleWriter{
Out: os.Stderr,
TimeFormat: "15:04:05",
})
viper.AutomaticEnv()
viper.SetEnvPrefix("FFIXER")
viper.SetDefault("use_kubeconfig", false)
viper.SetDefault("kubeconfig", filepath.Join(os.Getenv("HOME"), ".kube", "config"))
var config *rest.Config
var err error
switch {
case viper.GetBool("use_kubeconfig"):
log.Debug().Msg("using kubeconfig configuration")
config, err = clientcmd.BuildConfigFromFlags("", viper.GetString("kubeconfig"))
if err != nil {
log.Fatal().Err(err).Msg("cannot build kubeconfig configuration")
}
default:
config, err = rest.InClusterConfig()
if err != nil {
log.Fatal().Err(err).Msg("cannot build kubeconfig configuration from cluster role")
}
}
clientset, err = kubernetes.NewForConfig(config)
if err != nil {
log.Fatal().Err(err).Msg("cannot connect to cluster")
}
http.Handle("/metrics", promhttp.Handler())
go func() {
_ = http.ListenAndServe(":2112", nil)
}()
}
func main() {
bootstrap()
watcher := cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), "nodes", metaV1.NamespaceAll, fields.Everything())
_, controller := cache.NewInformer(
watcher,
&coreV1.Node{},
0,
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
node, ok := obj.(*coreV1.Node)
if !ok {
log.Fatal().
Str("object_type", fmt.Sprintf("%T", node)).
Msg("list/watch returned non-node object")
}
log.Info().Str("node_name", node.Name).Msg("checking node")
updateNode(node)
},
UpdateFunc: func(oldObj, newObj interface{}) {
node, ok := newObj.(*coreV1.Node)
if !ok {
log.Fatal().
Str("object_type", fmt.Sprintf("%T", node)).
Msg("list/watch update returned non-node object")
}
if viper.GetBool("debug") {
diffs, _ := diff.Diff(oldObj.(*coreV1.Node).Annotations, node.Annotations)
change, _ := json.Marshal(diffs)
log.Debug().Str("change", string(change)).Msg("change")
}
updateNode(node)
},
},
)
// Now let's start the controller
stop := make(chan struct{})
defer close(stop)
go controller.Run(stop)
// Wait forever
select {}
}
func updateNode(node *coreV1.Node) {
publicIP := ""
for _, nodeAddress := range node.Status.Addresses {
if nodeAddress.Type == coreV1.NodeExternalIP {
publicIP = nodeAddress.Address
break
}
}
logEntry := log.Info().Str("node_name", node.Name)
if publicIP == "" {
//fallback on k3s label
var ok bool
publicIP, ok = node.Labels[externalIPLabel]
if !ok {
logEntry.Msg(fmt.Sprintf("node doesn't have public address or %s label, skipping", externalIPLabel))
return
}
}
logEntry.Str("public_ip", publicIP)
flannelPublicIP := getValueFromMap(flannelPublicIPLabel, node.Annotations)
flannelPublicIPOverride := getValueFromMap(flannelPublicIPOverrideLabel, node.Annotations)
logEntry.Str("public_ip", publicIP).
Str("old_flannel_public_ip", flannelPublicIP).
Str("old_flannel_public_ip_override", flannelPublicIPOverride)
if publicIP == flannelPublicIP && publicIP == flannelPublicIPOverride {
//all good, nothing to see here.
return
}
//set new values
node.Annotations[flannelPublicIPLabel] = publicIP
node.Annotations[flannelPublicIPOverrideLabel] = publicIP
logEntry.Str("new_flannel_public_ip", publicIP).
Str("new_flannel_public_ip_override", publicIP)
_, err := clientset.CoreV1().Nodes().Update(node)
if err != nil {
log.Fatal().Err(err).Str("node_name", node.Name).Msg("cannot update node annotation")
}
logEntry.Msg("updated node annotation")
}
// getValueFromMap returns value from map or an empty string in case it's not found
func getValueFromMap(key string, obj map[string]string) string {
if val, ok := obj[key]; ok {
return val
}
return ""
}