-
Notifications
You must be signed in to change notification settings - Fork 77
/
builder.go
299 lines (267 loc) · 7.79 KB
/
builder.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
package kuberesolver
import (
"context"
"fmt"
"io"
"net"
"strconv"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/resolver"
)
const (
kubernetesSchema = "kubernetes"
defaultFreq = time.Minute * 30
)
var (
endpointsForTarget = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Name: "kuberesolver_endpoints_total",
Help: "The number of endpoints for a given target",
},
[]string{"target"},
)
addressesForTarget = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Name: "kuberesolver_addresses_total",
Help: "The number of addresses for a given target",
},
[]string{"target"},
)
clientLastUpdate = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Name: "kuberesolver_client_last_update",
Help: "The last time the resolver client was updated",
},
[]string{"target"},
)
)
type targetInfo struct {
scheme string
serviceName string
serviceNamespace string
port string
resolveByPortName bool
useFirstPort bool
}
func (ti targetInfo) String() string {
if ti.scheme != "" {
return fmt.Sprintf("%s://%s/%s:%s", ti.scheme, ti.serviceNamespace, ti.serviceName, ti.port)
} else {
return fmt.Sprintf("kubernetes://%s/%s:%s", ti.serviceNamespace, ti.serviceName, ti.port)
}
}
// RegisterInCluster registers the kuberesolver builder to grpc with kubernetes schema
func RegisterInCluster() {
RegisterInClusterWithSchema(kubernetesSchema)
}
// RegisterInClusterWithSchema registers the kuberesolver builder to the grpc with custom schema
func RegisterInClusterWithSchema(schema string) {
resolver.Register(NewBuilder(nil, schema))
}
// NewBuilder creates a kubeBuilder which is used by grpc resolver.
func NewBuilder(client K8sClient, schema string) resolver.Builder {
return &kubeBuilder{
k8sClient: client,
schema: schema,
}
}
type kubeBuilder struct {
k8sClient K8sClient
schema string
}
func splitServicePortNamespace(hpn string) (service, port, namespace string) {
service = hpn
colon := strings.LastIndexByte(service, ':')
if colon != -1 {
service, port = service[:colon], service[colon+1:]
}
// we want to split into the service name, namespace, and whatever else is left
// this will support fully qualified service names, e.g. {service-name}.<namespace>.svc.<cluster-domain-name>.
// Note that since we lookup the endpoints by service name and namespace, we don't care about the
// cluster-domain-name, only that we can parse out the service name and namespace properly.
parts := strings.SplitN(service, ".", 3)
if len(parts) >= 2 {
service, namespace = parts[0], parts[1]
}
return
}
func parseResolverTarget(target resolver.Target) (targetInfo, error) {
var service, port, namespace string
if target.URL.Host == "" {
// kubernetes:///service.namespace:port
service, port, namespace = splitServicePortNamespace(target.Endpoint())
} else if target.URL.Port() == "" && target.Endpoint() != "" {
// kubernetes://namespace/service:port
service, port, _ = splitServicePortNamespace(target.Endpoint())
namespace = target.URL.Hostname()
} else {
// kubernetes://service.namespace:port
service, port, namespace = splitServicePortNamespace(target.URL.Host)
}
if service == "" {
return targetInfo{}, fmt.Errorf("target %s must specify a service", &target.URL)
}
resolveByPortName := false
useFirstPort := false
if port == "" {
useFirstPort = true
} else if _, err := strconv.Atoi(port); err != nil {
resolveByPortName = true
}
return targetInfo{
scheme: target.URL.Scheme,
serviceName: service,
serviceNamespace: namespace,
port: port,
resolveByPortName: resolveByPortName,
useFirstPort: useFirstPort,
}, nil
}
// Build creates a new resolver for the given target.
//
// gRPC dial calls Build synchronously, and fails if the returned error is
// not nil.
func (b *kubeBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
if b.k8sClient == nil {
if cl, err := NewInClusterK8sClient(); err == nil {
b.k8sClient = cl
} else {
return nil, err
}
}
ti, err := parseResolverTarget(target)
if err != nil {
return nil, err
}
if ti.serviceNamespace == "" {
ti.serviceNamespace = getCurrentNamespaceOrDefault()
}
ctx, cancel := context.WithCancel(context.Background())
r := &kResolver{
target: ti,
ctx: ctx,
cancel: cancel,
cc: cc,
k8sClient: b.k8sClient,
t: time.NewTimer(defaultFreq),
freq: defaultFreq,
endpoints: endpointsForTarget.WithLabelValues(ti.String()),
addresses: addressesForTarget.WithLabelValues(ti.String()),
lastUpdateUnix: clientLastUpdate.WithLabelValues(ti.String()),
}
go until(func() {
r.wg.Add(1)
err := r.watch()
if err != nil && err != io.EOF {
grpclog.Errorf("kuberesolver: watching ended with error='%v', will reconnect again", err)
}
}, time.Second, time.Second*30, ctx.Done())
return r, nil
}
// Scheme returns the scheme supported by this resolver.
// Scheme is defined at https://github.com/grpc/grpc/blob/master/doc/naming.md.
func (b *kubeBuilder) Scheme() string {
return b.schema
}
type kResolver struct {
target targetInfo
ctx context.Context
cancel context.CancelFunc
cc resolver.ClientConn
k8sClient K8sClient
// wg is used to enforce Close() to return after the watcher() goroutine has finished.
wg sync.WaitGroup
t *time.Timer
freq time.Duration
endpoints prometheus.Gauge
addresses prometheus.Gauge
// lastUpdateUnix is the timestamp of the last successful update to the resolver client
lastUpdateUnix prometheus.Gauge
}
// ResolveNow will be called by gRPC to try to resolve the target name again.
// It's just a hint, resolver can ignore this if it's not necessary.
func (k *kResolver) ResolveNow(resolver.ResolveNowOptions) {
// ignore
}
// Close closes the resolver.
func (k *kResolver) Close() {
k.cancel()
k.wg.Wait()
}
func (k *kResolver) makeAddresses(e Endpoints) ([]resolver.Address, string) {
var newAddrs []resolver.Address
for _, subset := range e.Subsets {
port := ""
if k.target.useFirstPort {
port = strconv.Itoa(subset.Ports[0].Port)
} else if k.target.resolveByPortName {
for _, p := range subset.Ports {
if p.Name == k.target.port {
port = strconv.Itoa(p.Port)
break
}
}
} else {
port = k.target.port
}
if len(port) == 0 {
port = strconv.Itoa(subset.Ports[0].Port)
}
for _, address := range subset.Addresses {
newAddrs = append(newAddrs, resolver.Address{
Addr: net.JoinHostPort(address.IP, port),
ServerName: fmt.Sprintf("%s.%s", k.target.serviceName, k.target.serviceNamespace),
Metadata: nil,
})
}
}
return newAddrs, ""
}
func (k *kResolver) handle(e Endpoints) {
addrs, _ := k.makeAddresses(e)
if len(addrs) > 0 {
k.cc.UpdateState(resolver.State{
Addresses: addrs,
})
k.lastUpdateUnix.Set(float64(time.Now().Unix()))
}
k.endpoints.Set(float64(len(e.Subsets)))
k.addresses.Set(float64(len(addrs)))
}
func (k *kResolver) resolve() {
e, err := getEndpoints(k.k8sClient, k.target.serviceNamespace, k.target.serviceName)
if err == nil {
k.handle(e)
} else {
grpclog.Errorf("kuberesolver: lookup endpoints failed: %v", err)
}
// Next lookup should happen after an interval defined by k.freq.
k.t.Reset(k.freq)
}
func (k *kResolver) watch() error {
defer k.wg.Done()
// watch endpoints lists existing endpoints at start
sw, err := watchEndpoints(k.ctx, k.k8sClient, k.target.serviceNamespace, k.target.serviceName)
if err != nil {
return err
}
for {
select {
case <-k.ctx.Done():
return nil
case <-k.t.C:
k.resolve()
case up, hasMore := <-sw.ResultChan():
if hasMore {
k.handle(up.Object)
} else {
return nil
}
}
}
}