-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
endpoints.go
384 lines (340 loc) · 10.9 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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2018-2021 Authors of Cilium
package k8s
import (
"fmt"
"net"
"sort"
"strconv"
"strings"
"github.com/cilium/cilium/pkg/ip"
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"
"github.com/cilium/cilium/pkg/k8s/version"
"github.com/cilium/cilium/pkg/loadbalancer"
"github.com/cilium/cilium/pkg/option"
serviceStore "github.com/cilium/cilium/pkg/service/store"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
)
// 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.
//
// +k8s:deepcopy-gen=true
// +deepequal-gen=true
// +deepequal-gen:private-method=true
type Endpoints struct {
// 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[string]*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)
}
// Backend contains all ports and the node name of a given backend
//
// +k8s:deepcopy-gen=true
// +deepequal-gen=true
type Backend struct {
Ports serviceStore.PortConfiguration
NodeName 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 ip, be := range e.Backends {
for _, port := range be.Ports {
backends = append(backends, fmt.Sprintf("%s/%s", net.JoinHostPort(ip, 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[string]*Backend{},
}
}
// CIDRPrefixes returns the endpoint's backends as a slice of IPNets.
func (e *Endpoints) CIDRPrefixes() ([]*net.IPNet, error) {
prefixes := make([]string, len(e.Backends))
index := 0
for ip := range e.Backends {
prefixes[index] = ip
index++
}
valid, invalid := ip.ParseCIDRs(prefixes)
if len(invalid) > 0 {
return nil, fmt.Errorf("invalid IPs specified as backends: %+v", invalid)
}
return valid, nil
}
// ParseEndpointsID parses a Kubernetes endpoints and returns the ServiceID
func ParseEndpointsID(svc *slim_corev1.Endpoints) ServiceID {
return ServiceID{
Name: svc.ObjectMeta.Name,
Namespace: svc.ObjectMeta.Namespace,
}
}
// ParseEndpoints parses a Kubernetes Endpoints resource
func ParseEndpoints(ep *slim_corev1.Endpoints) (ServiceID, *Endpoints) {
endpoints := newEndpoints()
for _, sub := range ep.Subsets {
for _, addr := range sub.Addresses {
backend, ok := endpoints.Backends[addr.IP]
if !ok {
backend = &Backend{Ports: serviceStore.PortConfiguration{}}
endpoints.Backends[addr.IP] = backend
}
if addr.NodeName != nil {
backend.NodeName = *addr.NodeName
}
for _, port := range sub.Ports {
lbPort := loadbalancer.NewL4Addr(loadbalancer.L4Type(port.Protocol), uint16(port.Port))
backend.Ports[port.Name] = lbPort
}
}
}
return ParseEndpointsID(ep), 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
func ParseEndpointSliceV1Beta1(ep *slim_discovery_v1beta1.EndpointSlice) (EndpointSliceID, *Endpoints) {
endpoints := newEndpoints()
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/v1beta1/types.go:114
if sub.Conditions.Ready != nil && !*sub.Conditions.Ready {
continue
}
for _, addr := range sub.Addresses {
backend, ok := endpoints.Backends[addr]
if !ok {
backend = &Backend{Ports: serviceStore.PortConfiguration{}}
endpoints.Backends[addr] = backend
if nodeName, ok := sub.Topology["kubernetes.io/hostname"]; ok {
backend.NodeName = nodeName
}
}
for _, port := range ep.Ports {
name, lbPort := parseEndpointPortV1Beta1(port)
if lbPort != nil {
backend.Ports[name] = lbPort
}
}
}
}
return ParseEndpointSliceID(ep), 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
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 Endpoints resource
func ParseEndpointSliceV1(ep *slim_discovery_v1.EndpointSlice) (EndpointSliceID, *Endpoints) {
endpoints := newEndpoints()
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:117
if sub.Conditions.Ready != nil && !*sub.Conditions.Ready {
continue
}
for _, addr := range sub.Addresses {
backend, ok := endpoints.Backends[addr]
if !ok {
backend = &Backend{Ports: serviceStore.PortConfiguration{}}
endpoints.Backends[addr] = backend
if sub.NodeName != nil {
backend.NodeName = *sub.NodeName
} else {
if nodeName, ok := sub.DeprecatedTopology["kubernetes.io/hostname"]; ok {
backend.NodeName = nodeName
}
}
}
for _, port := range ep.Ports {
name, lbPort := parseEndpointPortV1(port)
if lbPort != nil {
backend.Ports[name] = lbPort
}
}
}
}
return ParseEndpointSliceID(ep), 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
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 {
allEps.Backends[backend] = ep
}
}
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{},
}
}
// SupportsEndpointSlice returns true if cilium-operator or cilium-agent should
// watch and process endpoint slices.
func SupportsEndpointSlice() bool {
return version.Capabilities().EndpointSlice && option.Config.K8sEnableK8sEndpointSlice
}
// SupportsEndpointSliceV1 returns true if cilium-operator or cilium-agent should
// watch and process endpoint slices V1.
func SupportsEndpointSliceV1() bool {
return SupportsEndpointSlice() && version.Capabilities().EndpointSliceV1
}
// HasEndpointSlice returns true if the hasEndpointSlices is closed before the
// controller has been synchronized with k8s.
func HasEndpointSlice(hasEndpointSlices chan struct{}, controller cache.Controller) bool {
endpointSliceSynced := make(chan struct{})
go func() {
cache.WaitForCacheSync(wait.NeverStop, controller.HasSynced)
close(endpointSliceSynced)
}()
// Check if K8s has a single endpointslice endpoint. By default, k8s has
// always the kubernetes-apiserver endpoint. If the endpointSlice are synced
// but we haven't received any endpoint slice then it means k8s is not
// running with k8s endpoint slice enabled.
select {
case <-endpointSliceSynced:
select {
// In case both select cases are ready to be selected we will recheck if
// hasEndpointSlices was closed.
case <-hasEndpointSlices:
return true
default:
}
case <-hasEndpointSlices:
return true
}
return false
}