-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
158 lines (125 loc) · 3.04 KB
/
watch.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
package main
import (
"context"
"fmt"
"log"
"net"
"time"
"k8s.io/api/core/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
type Server struct {
IP net.IP
Port int32
}
type ServerList []Server
func watchService(ctx context.Context) (_ <-chan ServerList, err error) {
icc, err := getConfig()
if err != nil {
return
}
client, err := kubernetes.NewForConfig(icc)
if err != nil {
return
}
ep := startWatch(client)
ch := make(chan ServerList)
ticker := time.NewTicker(cfg.WatchTimeout)
go func() {
for {
select {
case <-ctx.Done():
ticker.Stop()
go stopWatch(ep)
close(ch)
return
case <-ticker.C:
log.Printf("restarting the watch after timeout")
go stopWatch(ep)
ep = startWatch(client)
case res := <-ep.ResultChan():
endpoint, ok := res.Object.(*v1.Endpoints)
if !ok {
log.Printf("watch encountered an error: %+v", res.Object)
go stopWatch(ep)
ep = startWatch(client)
continue
}
if cfg.Namespace != "" && endpoint.Namespace != cfg.Namespace {
continue
}
if endpoint.Name != cfg.Service {
continue
}
var ips []string
var ports []int32
for _, subset := range endpoint.Subsets {
for _, addr := range subset.Addresses {
ips = append(ips, addr.IP)
}
for _, port := range subset.Ports {
if cfg.TargetPort == "" || port.Name == cfg.TargetPort {
ports = append(ports, port.Port)
}
}
}
var servers []Server
for _, addr := range ips {
for _, port := range ports {
servers = append(servers, Server{IP: net.ParseIP(addr), Port: port})
}
}
ch <- servers
}
}
}()
return ch, nil
}
func startWatch(client *kubernetes.Clientset) watch.Interface {
log.Printf("start watching endpoints in '%s' with labels '%s'", cfg.Namespace, cfg.LabelSelector)
for i := 0; i < cfg.WatchMaxRetries; i++ {
ep, err := client.CoreV1().Endpoints(cfg.Namespace).Watch(meta_v1.ListOptions{
LabelSelector: cfg.LabelSelector,
Watch: true,
})
if err == nil {
return ep
}
log.Println("couldn't start watch:", err.Error())
log.Printf("retrying in %s ...", cfg.WatchRetryDelay)
time.Sleep(cfg.WatchRetryDelay)
}
panic(fmt.Sprintf("couldn't start watch after %d retries", cfg.WatchMaxRetries))
}
func stopWatch(w watch.Interface) {
log.Printf("stopping a watch endpoint")
done := make(chan bool)
go func() {
w.Stop()
done <- true
}()
select {
case <-time.After(5 * time.Minute):
log.Println("closing a watch timed out after 5m")
case <-done:
log.Println("successfully stopped a watch")
}
}
func getConfig() (cfg *rest.Config, err error) {
cfg, err = rest.InClusterConfig()
if err != nil {
loader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
clientcmd.NewDefaultClientConfigLoadingRules(),
&clientcmd.ConfigOverrides{},
)
cfg, err = loader.ClientConfig()
if err != nil {
return
}
}
return
}