-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
endpoints.go
520 lines (472 loc) · 16.2 KB
/
endpoints.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package k8s
import (
"fmt"
"net"
"net/netip"
"sort"
"strconv"
"strings"
corev1 "k8s.io/api/core/v1"
cmtypes "github.com/cilium/cilium/pkg/clustermesh/types"
slim_corev1 "github.com/cilium/cilium/pkg/k8s/slim/k8s/api/core/v1"
slim_discovery_v1 "github.com/cilium/cilium/pkg/k8s/slim/k8s/api/discovery/v1"
slim_discovery_v1beta1 "github.com/cilium/cilium/pkg/k8s/slim/k8s/api/discovery/v1beta1"
slim_metav1 "github.com/cilium/cilium/pkg/k8s/slim/k8s/apis/meta/v1"
"github.com/cilium/cilium/pkg/k8s/types"
"github.com/cilium/cilium/pkg/loadbalancer"
"github.com/cilium/cilium/pkg/metrics"
"github.com/cilium/cilium/pkg/option"
serviceStore "github.com/cilium/cilium/pkg/service/store"
)
// Endpoints is an abstraction for the Kubernetes endpoints object. Endpoints
// consists of a set of backend IPs in combination with a set of ports and
// protocols. The name of the backend ports must match the names of the
// frontend ports of the corresponding service.
//
// The Endpoints object is parsed from either an EndpointSlice (preferred) or Endpoint
// Kubernetes objects depending on the Kubernetes version.
//
// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +deepequal-gen=true
// +deepequal-gen:private-method=true
type Endpoints struct {
types.UnserializableObject
slim_metav1.ObjectMeta
EndpointSliceID
// Backends is a map containing all backend IPs and ports. The key to
// the map is the backend IP in string form. The value defines the list
// of ports for that backend IP, plus an additional optional node name.
// Backends map[cmtypes.AddrCluster]*Backend
Backends map[cmtypes.AddrCluster]*Backend
}
// DeepEqual returns true if both endpoints are deep equal.
func (e *Endpoints) DeepEqual(o *Endpoints) bool {
switch {
case (e == nil) != (o == nil):
return false
case (e == nil) && (o == nil):
return true
}
return e.deepEqual(o)
}
func (in *Endpoints) DeepCopyInto(out *Endpoints) {
*out = *in
if in.Backends != nil {
in, out := &in.Backends, &out.Backends
*out = make(map[cmtypes.AddrCluster]*Backend, len(*in))
for key, val := range *in {
var outVal *Backend
if val == nil {
(*out)[key] = nil
} else {
in, out := &val, &outVal
*out = new(Backend)
(*in).DeepCopyInto(*out)
}
(*out)[key] = outVal
}
}
}
func (in *Endpoints) DeepCopy() *Endpoints {
if in == nil {
return nil
}
out := new(Endpoints)
in.DeepCopyInto(out)
return out
}
// Backend contains all ports, terminating state, and the node name of a given backend
//
// +k8s:deepcopy-gen=true
// +deepequal-gen=true
type Backend struct {
Ports serviceStore.PortConfiguration
NodeName string
Hostname string
Terminating bool
HintsForZones []string
Preferred bool
Zone string
}
// String returns the string representation of an endpoints resource, with
// backends and ports sorted.
func (e *Endpoints) String() string {
if e == nil {
return ""
}
backends := []string{}
for addrCluster, be := range e.Backends {
for _, port := range be.Ports {
if be.Zone != "" {
backends = append(backends, fmt.Sprintf("%s/%s[%s]", net.JoinHostPort(addrCluster.Addr().String(), strconv.Itoa(int(port.Port))), port.Protocol, be.Zone))
} else {
backends = append(backends, fmt.Sprintf("%s/%s", net.JoinHostPort(addrCluster.Addr().String(), strconv.Itoa(int(port.Port))), port.Protocol))
}
}
}
sort.Strings(backends)
return strings.Join(backends, ",")
}
// newEndpoints returns a new Endpoints
func newEndpoints() *Endpoints {
return &Endpoints{
Backends: map[cmtypes.AddrCluster]*Backend{},
}
}
// Prefixes returns the endpoint's backends as a slice of netip.Prefix.
func (e *Endpoints) Prefixes() []netip.Prefix {
prefixes := make([]netip.Prefix, 0, len(e.Backends))
for addrCluster := range e.Backends {
addr := addrCluster.Addr()
prefixes = append(prefixes, netip.PrefixFrom(addr, addr.BitLen()))
}
return prefixes
}
// ParseEndpointsID parses a Kubernetes endpoints and returns the EndpointSliceID
func ParseEndpointsID(ep *slim_corev1.Endpoints) EndpointSliceID {
return EndpointSliceID{
ServiceID: ServiceID{
Name: ep.ObjectMeta.Name,
Namespace: ep.ObjectMeta.Namespace,
},
EndpointSliceName: ep.ObjectMeta.Name,
}
}
// ParseEndpoints parses a Kubernetes Endpoints resource
func ParseEndpoints(ep *slim_corev1.Endpoints) *Endpoints {
endpoints := newEndpoints()
endpoints.ObjectMeta = ep.ObjectMeta
for _, sub := range ep.Subsets {
for _, addr := range sub.Addresses {
addrCluster, err := cmtypes.ParseAddrCluster(addr.IP)
if err != nil {
continue
}
backend, ok := endpoints.Backends[addrCluster]
if !ok {
backend = &Backend{Ports: serviceStore.PortConfiguration{}}
endpoints.Backends[addrCluster] = backend
}
if addr.NodeName != nil {
backend.NodeName = *addr.NodeName
}
backend.Hostname = addr.Hostname
for _, port := range sub.Ports {
lbPort := loadbalancer.NewL4Addr(loadbalancer.L4Type(port.Protocol), uint16(port.Port))
backend.Ports[port.Name] = lbPort
}
}
}
endpoints.EndpointSliceID = ParseEndpointsID(ep)
return endpoints
}
type endpointSlice interface {
GetNamespace() string
GetName() string
GetLabels() map[string]string
}
// ParseEndpointSliceID parses a Kubernetes endpoints slice and returns a
// EndpointSliceID
func ParseEndpointSliceID(es endpointSlice) EndpointSliceID {
return EndpointSliceID{
ServiceID: ServiceID{
Name: es.GetLabels()[slim_discovery_v1.LabelServiceName],
Namespace: es.GetNamespace(),
},
EndpointSliceName: es.GetName(),
}
}
// ParseEndpointSliceV1Beta1 parses a Kubernetes EndpointsSlice v1beta1 resource
// It reads ready and terminating state of endpoints in the EndpointSlice to
// return an EndpointSlice ID and a filtered list of Endpoints for service load-balancing.
func ParseEndpointSliceV1Beta1(ep *slim_discovery_v1beta1.EndpointSlice) *Endpoints {
endpoints := newEndpoints()
endpoints.ObjectMeta = ep.ObjectMeta
endpoints.EndpointSliceID = ParseEndpointSliceID(ep)
// Validate AddressType before parsing. Currently, we only support IPv4 and IPv6.
if ep.AddressType != slim_discovery_v1beta1.AddressTypeIPv4 &&
ep.AddressType != slim_discovery_v1beta1.AddressTypeIPv6 {
return endpoints
}
for _, sub := range ep.Endpoints {
skipEndpoint := false
// ready indicates that this endpoint is prepared to receive traffic,
// according to whatever system is managing the endpoint. A nil value
// indicates an unknown state. In most cases consumers should interpret this
// unknown state as ready.
// More info: vendor/k8s.io/api/discovery/v1beta1/types.go
if sub.Conditions.Ready != nil && !*sub.Conditions.Ready {
skipEndpoint = true
if option.Config.EnableK8sTerminatingEndpoint {
// Terminating indicates that the endpoint is getting terminated. A
// nil values indicates an unknown state. Ready is never true when
// an endpoint is terminating. Propagate the terminating endpoint
// state so that we can gracefully remove those endpoints.
// More details : vendor/k8s.io/api/discovery/v1/types.go
if sub.Conditions.Terminating != nil && *sub.Conditions.Terminating {
skipEndpoint = false
}
}
}
if skipEndpoint {
continue
}
for _, addr := range sub.Addresses {
addrCluster, err := cmtypes.ParseAddrCluster(addr)
if err != nil {
continue
}
backend, ok := endpoints.Backends[addrCluster]
if !ok {
backend = &Backend{Ports: serviceStore.PortConfiguration{}}
endpoints.Backends[addrCluster] = backend
if nodeName, ok := sub.Topology[corev1.LabelHostname]; ok {
backend.NodeName = nodeName
}
if sub.Hostname != nil {
backend.Hostname = *sub.Hostname
}
if option.Config.EnableK8sTerminatingEndpoint {
if sub.Conditions.Terminating != nil && *sub.Conditions.Terminating {
backend.Terminating = true
metrics.TerminatingEndpointsEvents.Inc()
}
}
if zoneName, ok := sub.Topology[corev1.LabelTopologyZone]; ok {
backend.Zone = zoneName
}
}
for _, port := range ep.Ports {
name, lbPort := parseEndpointPortV1Beta1(port)
if lbPort != nil {
backend.Ports[name] = lbPort
}
}
}
}
return endpoints
}
// parseEndpointPortV1Beta1 returns the port name and the port parsed as a
// L4Addr from the given port.
func parseEndpointPortV1Beta1(port slim_discovery_v1beta1.EndpointPort) (string, *loadbalancer.L4Addr) {
proto := loadbalancer.TCP
if port.Protocol != nil {
switch *port.Protocol {
case slim_corev1.ProtocolTCP:
proto = loadbalancer.TCP
case slim_corev1.ProtocolUDP:
proto = loadbalancer.UDP
case slim_corev1.ProtocolSCTP:
proto = loadbalancer.SCTP
default:
return "", nil
}
}
if port.Port == nil {
return "", nil
}
var name string
if port.Name != nil {
name = *port.Name
}
lbPort := loadbalancer.NewL4Addr(proto, uint16(*port.Port))
return name, lbPort
}
// ParseEndpointSliceV1 parses a Kubernetes EndpointSlice resource.
// It reads ready and terminating state of endpoints in the EndpointSlice to
// return an EndpointSlice ID and a filtered list of Endpoints for service load-balancing.
func ParseEndpointSliceV1(ep *slim_discovery_v1.EndpointSlice) *Endpoints {
endpoints := newEndpoints()
endpoints.ObjectMeta = ep.ObjectMeta
endpoints.EndpointSliceID = ParseEndpointSliceID(ep)
// Validate AddressType before parsing. Currently, we only support IPv4 and IPv6.
if ep.AddressType != slim_discovery_v1.AddressTypeIPv4 &&
ep.AddressType != slim_discovery_v1.AddressTypeIPv6 {
return endpoints
}
log.Debugf("Processing %d endpoints for EndpointSlice %s", len(ep.Endpoints), ep.Name)
for _, sub := range ep.Endpoints {
// ready indicates that this endpoint is prepared to receive traffic,
// according to whatever system is managing the endpoint. A nil value
// indicates an unknown state. In most cases consumers should interpret this
// unknown state as ready.
// More info: vendor/k8s.io/api/discovery/v1/types.go
isReady := sub.Conditions.Ready == nil || *sub.Conditions.Ready
// serving is identical to ready except that it is set regardless of the
// terminating state of endpoints. This condition should be set to true for
// a ready endpoint that is terminating. If nil, consumers should defer to
// the ready condition.
// More info: vendor/k8s.io/api/discovery/v1/types.go
isServing := (sub.Conditions.Serving == nil && isReady) || (sub.Conditions.Serving != nil && *sub.Conditions.Serving)
// Terminating indicates that the endpoint is getting terminated. A
// nil values indicates an unknown state. Ready is never true when
// an endpoint is terminating. Propagate the terminating endpoint
// state so that we can gracefully remove those endpoints.
// More info: vendor/k8s.io/api/discovery/v1/types.go
isTerminating := sub.Conditions.Terminating != nil && *sub.Conditions.Terminating
// if is not Ready and EnableK8sTerminatingEndpoint is set
// allow endpoints that are Serving and Terminating
if !isReady {
if !option.Config.EnableK8sTerminatingEndpoint {
log.Debugf("discarding Endpoint on EndpointSlice %s: not Ready and EnableK8sTerminatingEndpoint %v", ep.Name, option.Config.EnableK8sTerminatingEndpoint)
continue
}
// filter not Serving endpoints since those can not receive traffic
if !isServing {
log.Debugf("discarding Endpoint on EndpointSlice %s: not Serving and EnableK8sTerminatingEndpoint %v", ep.Name, option.Config.EnableK8sTerminatingEndpoint)
continue
}
}
for _, addr := range sub.Addresses {
addrCluster, err := cmtypes.ParseAddrCluster(addr)
if err != nil {
log.WithError(err).Infof("Unable to parse address %s for EndpointSlices %s", addr, ep.Name)
continue
}
backend, ok := endpoints.Backends[addrCluster]
if !ok {
backend = &Backend{Ports: serviceStore.PortConfiguration{}}
endpoints.Backends[addrCluster] = backend
if sub.NodeName != nil {
backend.NodeName = *sub.NodeName
} else {
if nodeName, ok := sub.DeprecatedTopology[corev1.LabelHostname]; ok {
backend.NodeName = nodeName
}
}
if sub.Hostname != nil {
backend.Hostname = *sub.Hostname
}
if sub.Zone != nil {
backend.Zone = *sub.Zone
} else if zoneName, ok := sub.DeprecatedTopology[corev1.LabelTopologyZone]; ok {
backend.Zone = zoneName
}
// If is not ready check if is serving and terminating
if !isReady && option.Config.EnableK8sTerminatingEndpoint &&
isServing && isTerminating {
log.Debugf("Endpoint address %s on EndpointSlice %s is Terminating", addr, ep.Name)
backend.Terminating = true
metrics.TerminatingEndpointsEvents.Inc()
}
}
for _, port := range ep.Ports {
name, lbPort := parseEndpointPortV1(port)
if lbPort != nil {
backend.Ports[name] = lbPort
}
}
if sub.Hints != nil && (*sub.Hints).ForZones != nil {
hints := (*sub.Hints).ForZones
backend.HintsForZones = make([]string, len(hints))
for i, hint := range hints {
backend.HintsForZones[i] = hint.Name
}
}
}
}
log.Debugf("EndpointSlice %s has %d backends", ep.Name, len(endpoints.Backends))
return endpoints
}
// parseEndpointPortV1 returns the port name and the port parsed as a L4Addr from
// the given port.
func parseEndpointPortV1(port slim_discovery_v1.EndpointPort) (string, *loadbalancer.L4Addr) {
proto := loadbalancer.TCP
if port.Protocol != nil {
switch *port.Protocol {
case slim_corev1.ProtocolTCP:
proto = loadbalancer.TCP
case slim_corev1.ProtocolUDP:
proto = loadbalancer.UDP
case slim_corev1.ProtocolSCTP:
proto = loadbalancer.SCTP
default:
return "", nil
}
}
if port.Port == nil {
return "", nil
}
var name string
if port.Name != nil {
name = *port.Name
}
lbPort := loadbalancer.NewL4Addr(proto, uint16(*port.Port))
return name, lbPort
}
// EndpointSlices is the collection of all endpoint slices of a service.
// The map key is the name of the endpoint slice or the name of the legacy
// v1.Endpoint. The endpoints stored here are not namespaced since this
// structure is only used as a value of another map that is already namespaced.
// (see ServiceCache.endpoints).
//
// +deepequal-gen=true
type EndpointSlices struct {
epSlices map[string]*Endpoints
}
// newEndpointsSlices returns a new EndpointSlices
func newEndpointsSlices() *EndpointSlices {
return &EndpointSlices{
epSlices: map[string]*Endpoints{},
}
}
// GetEndpoints returns a read only a single *Endpoints structure with all
// Endpoints' backends joined.
func (es *EndpointSlices) GetEndpoints() *Endpoints {
if es == nil || len(es.epSlices) == 0 {
return nil
}
allEps := newEndpoints()
for _, eps := range es.epSlices {
for backend, ep := range eps.Backends {
// EndpointSlices may have duplicate addresses on different slices.
// kubectl get endpointslices -n endpointslicemirroring-4896
// NAME ADDRESSTYPE PORTS ENDPOINTS AGE
// example-custom-endpoints-f6z84 IPv4 9090 10.244.1.49 28s
// example-custom-endpoints-g6r6v IPv4 8090 10.244.1.49 28s
b, ok := allEps.Backends[backend]
if !ok {
allEps.Backends[backend] = ep.DeepCopy()
} else {
clone := b.DeepCopy()
for k, v := range ep.Ports {
clone.Ports[k] = v
}
allEps.Backends[backend] = clone
}
}
}
return allEps
}
// Upsert maps the 'esname' to 'e'.
// - 'esName': Name of the Endpoint Slice
// - 'e': Endpoints to store in the map
func (es *EndpointSlices) Upsert(esName string, e *Endpoints) {
if es == nil {
panic("BUG: EndpointSlices is nil")
}
es.epSlices[esName] = e
}
// Delete deletes the endpoint slice in the internal map. Returns true if there
// are not any more endpoints available in the map.
func (es *EndpointSlices) Delete(esName string) bool {
if es == nil || len(es.epSlices) == 0 {
return true
}
delete(es.epSlices, esName)
return len(es.epSlices) == 0
}
// externalEndpoints is the collection of external endpoints in all remote
// clusters. The map key is the name of the remote cluster.
type externalEndpoints struct {
endpoints map[string]*Endpoints
}
// newExternalEndpoints returns a new ExternalEndpoints
func newExternalEndpoints() externalEndpoints {
return externalEndpoints{
endpoints: map[string]*Endpoints{},
}
}