forked from sgirones/kube2consul
/
kube2consul.go
337 lines (285 loc) · 9.92 KB
/
kube2consul.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// kube2consul is a bridge between Kubernetes and Consul. It watches the
// Kubernetes master for changes in Services and creates new DNS records on the
// consul agent.
package main // import "github.com/jmccarty3/kube2consul"
import (
"flag"
"fmt"
"net/url"
"os"
"reflect"
"time"
"github.com/golang/glog"
consulapi "github.com/hashicorp/consul/api"
kapi "k8s.io/kubernetes/pkg/api"
kcache "k8s.io/kubernetes/pkg/client/cache"
kclient "k8s.io/kubernetes/pkg/client/unversioned"
kclientcmd "k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
kframework "k8s.io/kubernetes/pkg/controller/framework"
kSelector "k8s.io/kubernetes/pkg/fields"
"k8s.io/kubernetes/pkg/labels"
"k8s.io/kubernetes/pkg/util"
)
var (
argConsulAgent = flag.String("consul-agent", "http://127.0.0.1:8500", "URL to consul agent")
argKubecfgFile = flag.String("kubecfg_file", "", "Location of kubecfg file for access to kubernetes service")
argKubeMasterURL = flag.String("kube_master_url", "https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}", "Url to reach kubernetes master. Env variables in this flag will be expanded.")
argDryRun = flag.Bool("dryrun", false, "Runs without connecting to consul")
argChecks = flag.Bool("checks", false, "Adds TCP service checks for each TCP Service")
argConsulSync = flag.Int("consul-sync", 0, "Set >0 to run a consul sync loop. Useful for consul restarts")
argKubeSync = flag.Int("kube-sync", 0, "Set >0 to run a kube sync loop. Useful for kube sanity checks if a notifcation is missed")
argNodeSelector = flag.String("node-selector", "", "Node label selector to use for proxies. Leave blank for all")
argTCPDomainRedirect = flag.String("tcpDomainRedirect", "", "Specifies a domain to register all services as in order to act as a redirect")
nodeSelector = labels.Everything()
)
const (
// Maximum number of attempts to connect to consul server.
maxConnectAttempts = 12
// Resync period for the kube controller loop.
resyncPeriod = 5 * time.Second
)
//Contains checks if the requested string is in the slice
func Contains(s []string, e string) bool {
for _, i := range s {
if i == e {
return true
}
}
return false
}
func getKubeMasterURL() (string, error) {
if *argKubeMasterURL == "" {
return "", fmt.Errorf("no --kube_master_url specified")
}
parsedURL, err := url.Parse(os.ExpandEnv(*argKubeMasterURL))
if err != nil {
return "", fmt.Errorf("failed to parse --kube_master_url %s - %v", *argKubeMasterURL, err)
}
if parsedURL.Scheme == "" || parsedURL.Host == "" || parsedURL.Host == ":" {
return "", fmt.Errorf("invalid --kube_master_url specified %s", *argKubeMasterURL)
}
glog.Info("Parsed Master URL:", parsedURL.String())
return parsedURL.String(), nil
}
func createConsulClient(consulAgent string) (*consulapi.Client, error) {
var (
client *consulapi.Client
err error
)
consulConfig := consulapi.DefaultConfig()
consulAgentURL, err := url.Parse(consulAgent)
if err != nil {
glog.Infof("Error parsing Consul url")
return nil, err
}
if consulAgentURL.Host != "" {
consulConfig.Address = consulAgentURL.Host
}
if consulAgentURL.Scheme != "" {
consulConfig.Scheme = consulAgentURL.Scheme
}
client, err = consulapi.NewClient(consulConfig)
if err != nil {
glog.Infof("Error creating Consul client")
return nil, err
}
for attempt := 1; attempt <= maxConnectAttempts; attempt++ {
if _, err = client.Agent().Self(); err == nil {
break
}
if attempt == maxConnectAttempts {
break
}
glog.Infof("[Attempt: %d] Attempting access to Consul after 5 second sleep", attempt)
time.Sleep(5 * time.Second)
}
if err != nil {
return nil, fmt.Errorf("failed to connect to Consul agent: %v, error: %v", consulAgent, err)
}
glog.Infof("Consul agent found: %v", consulAgent)
return client, nil
}
func createKubeClient() (*kclient.Client, error) {
masterURL, err := getKubeMasterURL()
if err != nil {
return nil, err
}
overrides := &kclientcmd.ConfigOverrides{}
overrides.ClusterInfo.Server = masterURL
rules := kclientcmd.NewDefaultClientConfigLoadingRules()
kubeConfig, err := kclientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig()
kubeConfig.Host = masterURL
if err != nil {
glog.Error("Error creating Kube Config", err)
return nil, err
}
glog.Infof("Using %s for kubernetes master", kubeConfig.Host)
glog.Infof("Using kubernetes API %s", kubeConfig.Version)
return kclient.New(kubeConfig)
}
// Returns a cache.ListWatch that gets all changes to services.
func createServiceLW(kubeClient *kclient.Client) *kcache.ListWatch {
return kcache.NewListWatchFromClient(kubeClient, "services", kapi.NamespaceAll, kSelector.Everything())
}
// Returns a cache.ListWatch that gets all changes to nodes.
func createNodeLW(kubeClient *kclient.Client) *kcache.ListWatch {
return kcache.NewListWatchFromClient(kubeClient, "nodes", kapi.NamespaceAll, kSelector.Everything())
}
func nodeReady(node *kapi.Node) bool {
for i := range node.Status.Conditions {
if node.Status.Conditions[i].Type == kapi.NodeReady {
return node.Status.Conditions[i].Status == kapi.ConditionTrue
}
}
glog.Error("NodeReady condition is missing from node: ", node.Name)
return false
}
//TODO Make Generic with Service
func sendNodeWork(action KubeWorkAction, queue chan<- KubeWork, oldObject, newObject interface{}) {
if node, ok := newObject.(*kapi.Node); ok {
if nodeSelector.Matches(labels.Set(node.Labels)) == false {
glog.V(2).Infof("Ignoring node %s due to label selectors", node.Name)
return
}
glog.V(4).Info("Node Action: ", action, " for node ", node.Name)
work := KubeWork{
Action: action,
Node: node,
}
if action == KubeWorkUpdateNode {
if oldNode, ok := oldObject.(*kapi.Node); ok {
if nodeReady(node) != nodeReady(oldNode) {
glog.V(4).Info("Ready state change. Old:", nodeReady(oldNode), " New: ", nodeReady(node))
queue <- work
}
}
} else {
queue <- work
}
}
}
//TODO Make Generic with Node
func sendServiceWork(action KubeWorkAction, queue chan<- KubeWork, serviceObj interface{}) {
if service, ok := serviceObj.(*kapi.Service); ok {
glog.V(4).Info("Service Action: ", action, " for service ", service.Name)
queue <- KubeWork{
Action: action,
Service: service,
}
}
}
//TODO Combine with watchForServices
func watchForNodes(kubeClient *kclient.Client, queue chan<- KubeWork) {
_, nodeController := kframework.NewInformer(
createNodeLW(kubeClient),
&kapi.Node{},
resyncPeriod,
kframework.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
sendNodeWork(KubeWorkAddNode, queue, nil, obj)
},
DeleteFunc: func(obj interface{}) {
sendNodeWork(KubeWorkRemoveNode, queue, nil, obj)
},
UpdateFunc: func(newObj, oldObj interface{}) {
sendNodeWork(KubeWorkUpdateNode, queue, oldObj, newObj)
},
},
)
go nodeController.Run(util.NeverStop)
}
//TODO Combine with watchForNodes
func watchForServices(kubeClient *kclient.Client, queue chan<- KubeWork) {
_, nodeController := kframework.NewInformer(
createServiceLW(kubeClient),
&kapi.Service{},
resyncPeriod,
kframework.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
sendServiceWork(KubeWorkAddService, queue, obj)
},
DeleteFunc: func(obj interface{}) {
sendServiceWork(KubeWorkRemoveService, queue, obj)
},
UpdateFunc: func(newObj, oldObj interface{}) {
if reflect.DeepEqual(newObj, oldObj) == false {
sendServiceWork(KubeWorkUpdateService, queue, newObj)
}
},
},
)
go nodeController.Run(util.NeverStop)
}
func main() {
flag.Parse()
//Attempt to create Kube Client
kubeClient, err := createKubeClient()
if err != nil {
glog.Fatal("Could not connect to Kube Master", err)
}
if _, err := kubeClient.ServerVersion(); err != nil {
glog.Fatal("Could not connect to Kube Master", err)
} else {
glog.Info("Connected to K8S API Server")
}
nodeSelector, err = labels.Parse(*argNodeSelector)
if err != nil {
glog.Fatal("Could not parse node label selector. Error:", err)
}
//Attempt to create Consul Client (All ways needed so that channels are not blocked)
var consulClient *consulapi.Client
if *argDryRun == false {
consulClient, _ = createConsulClient(*argConsulAgent)
}
//Do System Setup stuff (create channels?)
kubeWorkQueue := make(chan KubeWork)
consulWorkQueue := make(chan ConsulWork)
go RunBookKeeper(kubeWorkQueue, consulWorkQueue, kubeClient)
//Launch KubeLoops
watchForNodes(kubeClient, kubeWorkQueue)
watchForServices(kubeClient, kubeWorkQueue)
cConfig := ConsulWorkerConfig{
TCPDomain: *argTCPDomainRedirect,
}
//Launch Consul Loops
go RunConsulWorker(consulWorkQueue, consulClient, cConfig)
//Launch Sync Loops (if needed)
if *argConsulSync > 0 {
glog.Info("Running Consul Sync loop every: ", *argConsulSync, " seconds")
syncer := time.NewTicker(time.Second * time.Duration(*argConsulSync))
go func() {
for t := range syncer.C {
glog.V(4).Info("Consul Sync request at:", t)
consulWorkQueue <- ConsulWork{
Action: ConsulWorkSyncDNS,
}
}
}()
}
if *argKubeSync > 0 {
glog.Info("Running Kube Sync loop every: ", *argConsulSync, " seconds")
syncer := time.NewTicker(time.Second * time.Duration(*argKubeSync))
go func() {
for t := range syncer.C {
glog.V(4).Info("Kube Sync request at:", t)
kubeWorkQueue <- KubeWork{
Action: KubeWorkSync,
}
}
}()
}
// Prevent exit
select {}
}