-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
337 lines (308 loc) · 9.54 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
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
package main
import (
"context"
"fmt"
"log"
"net"
"os"
"strings"
"sync"
"time"
crd "github.com/traefik/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned"
"github.com/traefik/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/retry"
dns "sigs.k8s.io/external-dns/endpoint"
)
const (
hostnameAnnotation = "external-dns.alpha.kubernetes.io/internal-hostname"
internalHostnameAnnotation = "external-dns.alpha.kubernetes.io/hostname"
)
var clientset *kubernetes.Clientset
var ctx context.Context = context.Background()
func main() {
var config *rest.Config
var err error
// create a Kubernetes client
kubeconfig := os.Getenv("KUBECONFIG")
if kubeconfig != "" {
config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err.Error())
}
} else {
config, err = rest.InClusterConfig()
if err != nil {
log.Fatalf("Failed to create Kubernetes config: %v", err)
}
}
// create the clientset
clientset, err = kubernetes.NewForConfig(config)
if err != nil {
log.Fatalln(err.Error())
return
}
traefikClient, err := crd.NewForConfig(config)
if err != nil {
log.Fatalf("Failed to create Kubernetes client: %v", err)
return
}
lbIPs, err := getLoadBalancerIP()
if err != nil {
log.Fatalf("Could not get load balancer IP(s): %v\n", err)
return
}
log.Printf("Detected load balancer IPs as %v\n", lbIPs)
var wg sync.WaitGroup
wg.Add(2)
go func() {
watchIngressRoute(traefikClient, lbIPs)
watchIngressRouteTCP(traefikClient, lbIPs)
wg.Done()
}()
wg.Wait()
}
func watchIngressRoute(traefikClient *crd.Clientset, lbIPs []string) {
log.Printf("Watching for changes to IngressRoute\n")
// create an informer to watch for changes in IngressRoute objects
informer := cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
return traefikClient.TraefikV1alpha1().IngressRoutes("").List(ctx, options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return traefikClient.TraefikV1alpha1().IngressRoutes("").Watch(ctx, options)
},
},
&v1alpha1.IngressRoute{},
0, // don't resync
cache.Indexers{},
)
// add an event handler for changes to IngressRoute objects
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
ingressRoute := obj.(*v1alpha1.IngressRoute)
log.Printf("IngressRoute %s/%s added\n", ingressRoute.Namespace, ingressRoute.Name)
if h := hosToAdd(ingressRoute.Annotations); h != "" {
hostsList := strings.Split(strings.Replace(h, " ", "", -1), ",")
for _, host := range hostsList {
log.Printf("Adding DNS entries for %s\n", host)
createDNSRecord(h, ingressRoute.Namespace, lbIPs)
}
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
ingressRoute := newObj.(*v1alpha1.IngressRoute)
log.Printf("IngressRoute %s/%s updated\n", ingressRoute.Namespace, ingressRoute.Name)
// if err := updateDNSRecord(ingressRoute.Name, ingressRoute.Namespace, ingressRoute); err != nil {
// log.Fatalf("Could not update DNSentry %s/%s: %v\n", ingressRoute.Namespace, ingressRoute.Name, err)
// }
},
DeleteFunc: func(obj interface{}) {
ingressRoute := obj.(*v1alpha1.IngressRoute)
if ingressRoute.Annotations["managed-by"] == "traefik2dns" {
log.Printf("IngressRoute %s/%s deleted\n", ingressRoute.Namespace, ingressRoute.Name)
if h := hosToAdd(ingressRoute.Annotations); h != "" {
hostsList := strings.Split(strings.Replace(h, " ", "", -1), ",")
for _, host := range hostsList {
if err := deleteDNSRecord(host, ingressRoute.Namespace); err != nil {
log.Printf("Error deleting record: %v\n", err)
}
}
}
} else {
log.Printf("IngressRoute %s/%s is not managed by traefik2dns. Ignored.\n", ingressRoute.Namespace, ingressRoute.Name)
}
},
})
// start the informer and wait for changes
informer.Run(make(chan struct{}))
for {
time.Sleep(time.Second * 30)
}
}
func watchIngressRouteTCP(traefikClient *crd.Clientset, lbIPs []string) {
log.Printf("Watching for changes to IngressRouteTCP\n")
// create an informer to watch for changes in IngressRouteTCP objects
informer := cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
return traefikClient.TraefikV1alpha1().IngressRouteTCPs("").List(ctx, options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return traefikClient.TraefikV1alpha1().IngressRouteTCPs("").Watch(ctx, options)
},
},
&v1alpha1.IngressRouteTCP{},
0, // don't resync
cache.Indexers{},
)
// add an event handler for changes to IngressRouteTCP objects
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
IngressRouteTCP := obj.(*v1alpha1.IngressRouteTCP)
log.Printf("IngressRouteTCP %s/%s added\n", IngressRouteTCP.Namespace, IngressRouteTCP.Name)
if h := hosToAdd(IngressRouteTCP.Annotations); h != "" {
hostsList := strings.Split(strings.Replace(h, " ", "", -1), ",")
for _, host := range hostsList {
log.Printf("Adding DNS entries for %s\n", host)
createDNSRecord(h, IngressRouteTCP.Namespace, lbIPs)
}
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
IngressRouteTCP := newObj.(*v1alpha1.IngressRouteTCP)
log.Printf("IngressRouteTCP %s/%s updated\n", IngressRouteTCP.Namespace, IngressRouteTCP.Name)
// if err := updateDNSRecord(IngressRouteTCP.Name, IngressRouteTCP.Namespace, IngressRouteTCP); err != nil {
// log.Fatalf("Could not update DNSentry %s/%s: %v\n", IngressRouteTCP.Namespace, IngressRouteTCP.Name, err)
// }
},
DeleteFunc: func(obj interface{}) {
IngressRouteTCP := obj.(*v1alpha1.IngressRouteTCP)
if IngressRouteTCP.Annotations["managed-by"] == "traefik2dns" {
log.Printf("IngressRouteTCP %s/%s deleted\n", IngressRouteTCP.Namespace, IngressRouteTCP.Name)
if h := hosToAdd(IngressRouteTCP.Annotations); h != "" {
hostsList := strings.Split(strings.Replace(h, " ", "", -1), ",")
for _, host := range hostsList {
if err := deleteDNSRecord(host, IngressRouteTCP.Namespace); err != nil {
log.Printf("Error deleting record: %v\n", err)
}
}
}
} else {
log.Printf("IngressRouteTCP %s/%s is not managed by traefik2dns. Ignored.\n", IngressRouteTCP.Namespace, IngressRouteTCP.Name)
}
},
})
// start the informer and wait for changes
informer.Run(make(chan struct{}))
for {
time.Sleep(time.Second * 30)
}
}
func hosToAdd(anns map[string]string) string {
if val, ok := anns[internalHostnameAnnotation]; ok {
return val
}
if val, ok := anns[hostnameAnnotation]; ok {
return val
}
return ""
}
func getLoadBalancerIP() ([]string, error) {
var ips []string
labels := getEnv("TRAEFIK_LABEL", "app.kubernetes.io/instance=traefik-traefik")
ns := getEnv("TRAEFIK_NAMESPACE", "traefik")
opts := metav1.ListOptions{
LabelSelector: labels,
}
services, err := clientset.CoreV1().Services(ns).List(ctx, opts)
if err != nil {
return ips, err
}
for _, service := range services.Items {
loadBalancerIPs := service.Status.LoadBalancer.Ingress
for _, loadBalancerIP := range loadBalancerIPs {
if loadBalancerIP.Hostname != "" {
res, err := getIPs(loadBalancerIP.Hostname)
if err != nil {
return ips, err
}
ips = append(ips, res...)
}
if loadBalancerIP.IP != "" {
fmt.Println(loadBalancerIP.IP)
ips = append(ips, loadBalancerIP.IP)
}
}
}
return ips, err
}
func updateDNSRecord(name string, namespace string, lbIPs []string) error {
return nil
}
func deleteDNSRecord(dnsName string, namespace string) error {
var err error
retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
err = clientset.CoreV1().RESTClient().
Delete().
AbsPath("/apis/externaldns.k8s.io/v1alpha1").
Namespace(namespace).
Name(dnsName).
Body(&metav1.DeleteOptions{}).
Do(ctx).
Error()
if err != nil {
return err
}
return nil
})
if retryErr != nil {
return retryErr
}
return nil
}
func createDNSRecord(dnsName string, namespace string, lbIPs []string) error {
dnsEndpoint := &dns.DNSEndpoint{
TypeMeta: metav1.TypeMeta{
Kind: "DNSEndpoint",
APIVersion: "externaldns.k8s.io/v1alpha1",
},
ObjectMeta: metav1.ObjectMeta{
Name: dnsName,
Namespace: namespace,
Annotations: map[string]string{
"managed-by": "traefik2dns",
},
Labels: map[string]string{
"managed-by": "traefik2dns",
},
},
Spec: dns.DNSEndpointSpec{
Endpoints: []*dns.Endpoint{
{
DNSName: dnsName,
Targets: lbIPs,
},
},
},
}
_, err := clientset.CoreV1().RESTClient().
Post().
AbsPath("/apis/externaldns.k8s.io/v1alpha1").
Namespace(namespace).
Body(dnsEndpoint).
Resource("dnsendpoints").
DoRaw(ctx)
if err != nil {
fmt.Println(err)
if errors.IsAlreadyExists(err) {
fmt.Println("DNS endpoint already exists")
} else {
panic(err.Error())
}
}
return err
}
func getIPs(hostname string) ([]string, error) {
// Resolve the hostname into a list of IPs
ips, err := net.LookupHost(hostname)
if err != nil {
fmt.Println("Error:", err)
return ips, err
}
return ips, err
}
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}