-
Notifications
You must be signed in to change notification settings - Fork 306
/
Copy pathtranslator.go
650 lines (567 loc) · 22.8 KB
/
translator.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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package translator
import (
"fmt"
"sort"
"strconv"
"strings"
"k8s.io/client-go/kubernetes"
"k8s.io/ingress-gce/pkg/healthchecks"
"k8s.io/ingress-gce/pkg/utils/endpointslices"
"k8s.io/klog/v2"
api_v1 "k8s.io/api/core/v1"
discoveryapi "k8s.io/api/discovery/v1"
v1 "k8s.io/api/networking/v1"
"k8s.io/apimachinery/pkg/api/meta"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/tools/cache"
"k8s.io/ingress-gce/pkg/annotations"
backendconfigv1 "k8s.io/ingress-gce/pkg/apis/backendconfig/v1"
"k8s.io/ingress-gce/pkg/backendconfig"
"k8s.io/ingress-gce/pkg/controller/errors"
"k8s.io/ingress-gce/pkg/flags"
"k8s.io/ingress-gce/pkg/utils"
namer_util "k8s.io/ingress-gce/pkg/utils/namer"
)
const (
// DefaultHost is the host used if none is specified. It is a valid value
// for the "Host" field recognized by GCE.
DefaultHost = "*"
// DefaultPath is the path used if none is specified. It is a valid path
// recognized by GCE.
DefaultPath = "/*"
)
// getServicePortParams allows for passing parameters to getServicePort()
type getServicePortParams struct {
isL7ILB bool
isL7XLBRegional bool
}
func (t *Translator) getServicePortParamsForIngress(ing *v1.Ingress) *getServicePortParams {
return &getServicePortParams{
isL7ILB: utils.IsGCEL7ILBIngress(ing),
isL7XLBRegional: t.enableL7XLBRegional && utils.IsGCEL7XLBRegionalIngress(ing),
}
}
// NewTranslator returns a new Translator.
func NewTranslator(serviceInformer cache.SharedIndexInformer,
backendConfigInformer cache.SharedIndexInformer,
nodeInformer cache.SharedIndexInformer,
podInformer cache.SharedIndexInformer,
endpointSliceInformer cache.SharedIndexInformer,
kubeClient kubernetes.Interface,
recorderGetter healthchecks.RecorderGetter,
enableTHC,
enableL7XLBRegional bool,
logger klog.Logger,
) *Translator {
return &Translator{
ServiceInformer: serviceInformer,
BackendConfigInformer: backendConfigInformer,
NodeInformer: nodeInformer,
PodInformer: podInformer,
EndpointSliceInformer: endpointSliceInformer,
KubeClient: kubeClient,
enableTHC: enableTHC,
enableL7XLBRegional: enableL7XLBRegional,
logger: logger.WithName("Translator"),
}
}
// Translator helps with kubernetes -> gce api conversion.
type Translator struct {
ServiceInformer cache.SharedIndexInformer
BackendConfigInformer cache.SharedIndexInformer
NodeInformer cache.SharedIndexInformer
PodInformer cache.SharedIndexInformer
EndpointSliceInformer cache.SharedIndexInformer
KubeClient kubernetes.Interface
enableTHC bool
enableL7XLBRegional bool
logger klog.Logger
}
func (t *Translator) getCachedService(id utils.ServicePortID) (*api_v1.Service, error) {
obj, exists, err := t.ServiceInformer.GetIndexer().Get(
&api_v1.Service{
ObjectMeta: meta_v1.ObjectMeta{
Name: id.Service.Name,
Namespace: id.Service.Namespace,
},
})
if !exists {
// This is a fatal error.
return nil, errors.ErrSvcNotFound{Service: id.Service}
}
if err != nil {
// This is a fatal error.
return nil, fmt.Errorf("error retrieving service %q: %v", id.Service, err)
}
svc, ok := obj.(*api_v1.Service)
if !ok {
return nil, fmt.Errorf("cannot convert to Service (%T)", svc)
}
return svc, nil
}
// GetService Implements ServiceGetter interface.
func (t *Translator) GetService(namespace, name string) (*api_v1.Service, error) {
dummyServicePort := utils.ServicePortID{Service: types.NamespacedName{Namespace: namespace, Name: name}}
return t.getCachedService(dummyServicePort)
}
// maybeEnableNEG enables NEG on the service port if necessary
func maybeEnableNEG(sp *utils.ServicePort, svc *api_v1.Service) error {
negAnnotation, ok, err := annotations.FromService(svc).NEGAnnotation()
if ok && err == nil {
sp.NEGEnabled = negAnnotation.NEGEnabledForIngress()
}
if !sp.NEGEnabled && svc.Spec.Type != api_v1.ServiceTypeNodePort &&
svc.Spec.Type != api_v1.ServiceTypeLoadBalancer {
// This is a fatal error.
return errors.ErrBadSvcType{Service: sp.ID.Service, ServiceType: svc.Spec.Type}
}
if sp.L7ILBEnabled || sp.L7XLBRegionalEnabled {
// L7-ILB and L7 Regional XLB require NEGs
sp.NEGEnabled = true
}
return nil
}
// setAppProtocol sets the app protocol on the service port
func setAppProtocol(sp *utils.ServicePort, svc *api_v1.Service, port *api_v1.ServicePort) error {
appProtocols, err := annotations.FromService(svc).ApplicationProtocols()
if err != nil {
return errors.ErrSvcAppProtosParsing{Service: sp.ID.Service, Err: err}
}
proto := annotations.ProtocolHTTP
if protoStr, exists := appProtocols[port.Name]; exists {
proto = annotations.AppProtocol(protoStr)
}
sp.Protocol = proto
return nil
}
func setTrafficScaling(sp *utils.ServicePort, svc *api_v1.Service) error {
const maxRatePerEndpointKey = "networking.gke.io/max-rate-per-endpoint"
if s, ok := svc.Annotations[maxRatePerEndpointKey]; ok {
val, err := strconv.ParseFloat(s, 64)
if err != nil || val < 0.0 {
return fmt.Errorf(`invalid value for Service annotation %s, should be an integer > 0, got %q`, maxRatePerEndpointKey, s)
}
sp.MaxRatePerEndpoint = &val
}
const capacityScalerKey = "networking.gke.io/capacity-scaler"
if s, ok := svc.Annotations[capacityScalerKey]; ok {
val, err := strconv.ParseFloat(s, 64)
if err != nil || (val < 0.0 || val > 1.0) {
return fmt.Errorf(`invalid value for Service annotation %s, should be a number >= 0.0 and <= 1.0, got %q`, capacityScalerKey, s)
}
sp.CapacityScaler = &val
}
return nil
}
// maybeEnableBackendConfig sets the backendConfig for the service port if necessary
func (t *Translator) maybeEnableBackendConfig(sp *utils.ServicePort, svc *api_v1.Service, port *api_v1.ServicePort) error {
var beConfig *backendconfigv1.BackendConfig
beConfig, err := backendconfig.GetBackendConfigForServicePort(t.BackendConfigInformer.GetIndexer(), svc, port)
if err != nil {
// If we could not find a backend config name for the current
// service port, then do not return an error. Removing a reference
// to a backend config from the service annotation is a valid
// step that a user could take.
if err != backendconfig.ErrNoBackendConfigForPort {
return errors.ErrSvcBackendConfig{ServicePortID: sp.ID, Err: err}
}
}
// Object in cache could be changed in-flight. Deepcopy to
// reduce race conditions.
beConfig = beConfig.DeepCopy()
if err = backendconfig.Validate(t.KubeClient, beConfig, sp); err != nil {
return errors.ErrBackendConfigValidation{BackendConfig: *beConfig, Err: err}
}
sp.BackendConfig = beConfig
return nil
}
// setThcOptInOnSvc sets the THCOptInOnSvc for the service port as true or false depending on whether
// Transparent Health Checks should be enabled.
func (t *Translator) setThcOptInOnSvc(sp *utils.ServicePort, svc *api_v1.Service) (flagWarning bool) {
thcOptIn, err := annotations.FromService(svc).IsThcAnnotated()
if err != nil {
t.logger.Info(fmt.Sprintf("Parsing THC annotation failed: %+v.", err))
}
if !thcOptIn {
sp.THCConfiguration.THCOptInOnSvc = false
t.logger.Info(fmt.Sprintf("THCOptInOnSvc=%v for the service", sp.THCConfiguration.THCOptInOnSvc), "serviceName", svc.Name, "servicePort", sp.Port, "servicePortName", sp.PortName)
return
}
// Feature flag for Transparent Health Checks not set.
if !t.enableTHC {
sp.THCConfiguration.THCEvents.THCAnnotationWithoutFlag = true
flagWarning = true
sp.THCConfiguration.THCOptInOnSvc = false
t.logger.Info(fmt.Sprintf("THCOptInOnSvc=%v for the service", sp.THCConfiguration.THCOptInOnSvc), "serviceName", svc.Name, "servicePort", sp.Port, "servicePortName", sp.PortName)
return
}
// There is a BackendConfig detailing the health check configuration for the service.
if sp.BackendConfig != nil && sp.BackendConfig.Spec.HealthCheck != nil {
sp.THCConfiguration.THCEvents.BackendConfigOverridesTHC = true
sp.THCConfiguration.THCOptInOnSvc = false
t.logger.Info(fmt.Sprintf("THCOptInOnSvc=%v for the service", sp.THCConfiguration.THCOptInOnSvc), "serviceName", svc.Name, "servicePort", sp.Port, "servicePortName", sp.PortName)
return
}
// THC works only with NEGs (not Instance Groups) and this is not a Service with NEG enabled.
if !sp.NEGEnabled {
sp.THCConfiguration.THCEvents.THCAnnotationWithoutNEG = true
sp.THCConfiguration.THCOptInOnSvc = false
t.logger.Info(fmt.Sprintf("THCOptInOnSvc=%v for the service", sp.THCConfiguration.THCOptInOnSvc), "serviceName", svc.Name, "servicePort", sp.Port, "servicePortName", sp.PortName)
return
}
sp.THCConfiguration.THCEvents.THCConfigured = true
sp.THCConfiguration.THCOptInOnSvc = true
t.logger.Info(fmt.Sprintf("THCOptInOnSvc=%v for the service", sp.THCConfiguration.THCOptInOnSvc), "serviceName", svc.Name, "servicePort", sp.Port, "servicePortName", sp.PortName)
return
}
// getServicePort looks in the svc store for a matching service:port,
// and returns the nodeport.
// The returned bool indicates whether there is a warning being returned or not.
func (t *Translator) getServicePort(id utils.ServicePortID, params *getServicePortParams, namer namer_util.BackendNamer) (*utils.ServicePort, error, bool) {
svc, err := t.getCachedService(id)
if err != nil {
return nil, err, false
}
port := ServicePort(*svc, id.Port)
if port == nil {
// This is a fatal error.
return nil, errors.ErrSvcPortNotFound{ServicePortID: id}, false
}
// We periodically add information to the ServicePort to ensure that we
// always return as much as possible, rather than nil, if there was a non-fatal error.
svcPort := &utils.ServicePort{
ID: id,
NodePort: int64(port.NodePort),
Port: port.Port,
PortName: port.Name,
TargetPort: port.TargetPort,
L7ILBEnabled: params.isL7ILB,
L7XLBRegionalEnabled: params.isL7XLBRegional,
BackendNamer: namer,
}
if err := maybeEnableNEG(svcPort, svc); err != nil {
return nil, err, false
}
if err := setAppProtocol(svcPort, svc, port); err != nil {
return svcPort, err, false
}
if flags.F.EnableTrafficScaling {
if err := setTrafficScaling(svcPort, svc); err != nil {
return nil, err, false
}
}
if err := t.maybeEnableBackendConfig(svcPort, svc, port); err != nil {
return svcPort, err, false
}
flagWarning := t.setThcOptInOnSvc(svcPort, svc)
return svcPort, nil, flagWarning
}
// TranslateIngress converts an Ingress into our internal UrlMap representation.
// The returned bool is for warnings (there is one type of warnings currently possible).
func (t *Translator) TranslateIngress(ing *v1.Ingress, systemDefaultBackend utils.ServicePortID, namer namer_util.BackendNamer) (*utils.GCEURLMap, []error, bool) {
var errs []error
var warnings bool
urlMap := utils.NewGCEURLMap(t.logger)
params := t.getServicePortParamsForIngress(ing)
for _, rule := range ing.Spec.Rules {
if rule.HTTP == nil {
continue
}
pathRules := []utils.PathRule{}
for _, p := range rule.HTTP.Paths {
svcPortID, err := utils.BackendToServicePortID(p.Backend, ing.Namespace)
if err != nil {
// Only error possible is Backend is not a Service Backend, so move to next path
errs = append(errs, err)
continue
}
svcPort, err, warning := t.getServicePort(svcPortID, params, namer)
warnings = warnings || warning
if err != nil {
errs = append(errs, err)
}
if svcPort != nil {
// The Ingress spec defines empty path as catch-all, so if a user
// asks for a single host and multiple empty paths, all traffic is
// sent to one of the last backend in the rules list.
paths, err := validateAndGetPaths(p)
if err != nil {
errs = append(errs, err)
continue
}
for _, path := range paths {
if path == "" {
path = DefaultPath
}
pathRules = append(pathRules, utils.PathRule{Path: path, Backend: *svcPort})
}
}
}
host := rule.Host
if host == "" {
host = DefaultHost
}
urlMap.PutPathRulesForHost(host, pathRules)
}
if ing.Spec.DefaultBackend != nil {
svcPortID, err := utils.BackendToServicePortID(*ing.Spec.DefaultBackend, ing.Namespace)
if err != nil {
errs = append(errs, err)
return urlMap, errs, warnings
}
svcPort, err, warning := t.getServicePort(svcPortID, params, namer)
warnings = warnings || warning
if err == nil {
urlMap.DefaultBackend = svcPort
return urlMap, errs, warnings
}
errs = append(errs, err)
return urlMap, errs, warnings
}
svcPort, err, warning := t.getServicePort(systemDefaultBackend, params, namer)
warnings = warnings || warning
if err == nil {
urlMap.DefaultBackend = svcPort
return urlMap, errs, warnings
}
errs = append(errs, fmt.Errorf("failed to retrieve the system default backend service %q with port %q: %v", systemDefaultBackend.Service.String(), systemDefaultBackend.Port.String(), err))
return urlMap, errs, warnings
}
// validateAndGetPaths will validate the path based on the specified path type and will return the
// the path rules that should be used. If no path type is provided, the path type will be assumed
// to be ImplementationSpecific. If a non existent path type is provided, an error will be returned.
func validateAndGetPaths(path v1.HTTPIngressPath) ([]string, error) {
pathType := v1.PathTypeImplementationSpecific
if path.PathType != nil {
pathType = *path.PathType
}
switch pathType {
case v1.PathTypeImplementationSpecific:
// ImplementationSpecific will have no validation to continue backwards compatibility
return []string{path.Path}, nil
case v1.PathTypeExact:
return validateExactPathType(path)
case v1.PathTypePrefix:
return validateAndModifyPrefixPathType(path)
default:
return nil, fmt.Errorf("unsupported path type: %s", pathType)
}
}
// validateExactPathType will validate the path provided does not have any wildcards and will
// return the path unmodified. If the path is in valid, an empty list and error is returned.
func validateExactPathType(path v1.HTTPIngressPath) ([]string, error) {
if path.Path == "" {
return nil, fmt.Errorf("failed to validate exact path type due to empty path")
}
if strings.Contains(path.Path, "*") {
return nil, fmt.Errorf("failed to validate exact path %s due to invalid wildcard", path.Path)
}
return []string{path.Path}, nil
}
// validateAndModifyPrefixPathType will validate the path provided does not have any wildcards
// and will return the path unmodified. If the path is in valid, an empty list and error is
// returned.
func validateAndModifyPrefixPathType(path v1.HTTPIngressPath) ([]string, error) {
if path.Path == "" {
return nil, fmt.Errorf("failed to validate prefix path type due to empty path")
}
// The Ingress spec defines Prefix path "/" as matching all paths
if path.Path == "/" {
return []string{"/*"}, nil
}
if strings.Contains(path.Path, "*") {
return nil, fmt.Errorf("failed to validate prefix path %s due to invalid wildcard", path.Path)
}
// Prefix path `/foo` or `/foo/` should support requests for `/foo`, `/foo/` and `/foo/bar`. URLMap requires two
// path rules 1) `/foo` & 2) `/foo/*` to support all three requests.
// Therefore each prefix path should result in two paths for the URLMap, one without a
// trailing '/' and one that ends with '/*'
if path.Path[len(path.Path)-1] == '/' {
return []string{path.Path[0 : len(path.Path)-1], path.Path + "*"}, nil
}
return []string{path.Path, path.Path + "/*"}, nil
}
// geHTTPProbe returns the http readiness probe from the first container
// that matches targetPort, from the set of pods matching the given labels.
func (t *Translator) getHTTPProbe(svc api_v1.Service, targetPort intstr.IntOrString, protocol annotations.AppProtocol) (*api_v1.Probe, error) {
l := svc.Spec.Selector
// Lookup any container with a matching targetPort from the set of pods
// with a matching label selector.
pl, err := listPodsBySelector(t.PodInformer.GetIndexer(), labels.SelectorFromSet(labels.Set(l)))
if err != nil {
return nil, err
}
// If multiple endpoints have different health checks, take the first
sort.Sort(orderedPods(pl))
for _, pod := range pl {
if pod.Namespace != svc.Namespace {
continue
}
logStr := fmt.Sprintf("Pod %v matching service selectors %v (targetport %+v)", pod.Name, l, targetPort)
for _, c := range pod.Spec.Containers {
if !isSimpleHTTPProbe(c.ReadinessProbe) || getProbeScheme(protocol) != c.ReadinessProbe.HTTPGet.Scheme {
continue
}
for _, p := range c.Ports {
if (targetPort.Type == intstr.Int && targetPort.IntVal == p.ContainerPort) ||
(targetPort.Type == intstr.String && targetPort.StrVal == p.Name) {
readinessProbePort := c.ReadinessProbe.ProbeHandler.HTTPGet.Port
switch readinessProbePort.Type {
case intstr.Int:
if readinessProbePort.IntVal == p.ContainerPort {
return c.ReadinessProbe, nil
}
case intstr.String:
if readinessProbePort.StrVal == p.Name {
return c.ReadinessProbe, nil
}
}
t.logger.Info(fmt.Sprintf("%v: found matching targetPort on container %v, but not on readinessProbe (%+v)",
logStr, c.Name, c.ReadinessProbe.ProbeHandler.HTTPGet.Port))
}
}
}
t.logger.V(5).Info(fmt.Sprintf("%v: lacks a matching HTTP probe for use in health checks.", logStr))
}
return nil, nil
}
// GatherEndpointPorts returns all ports needed to open NEG endpoints.
func (t *Translator) GatherEndpointPorts(svcPorts []utils.ServicePort) []string {
portMap := map[int64]bool{}
for _, p := range svcPorts {
if p.NEGEnabled {
// For NEG backend, need to open firewall to all endpoint target ports
// TODO(mixia): refactor firewall syncing into a separate go routine with different trigger.
// With NEG, endpoint changes may cause firewall ports to be different if user specifies inconsistent backends.
var endpointPorts []int
// if targetPort is integer, no need to look for ports from endpoints
if p.TargetPort.Type == intstr.Int {
endpointPorts = []int{p.TargetPort.IntValue()}
} else {
endpointPorts = listEndpointTargetPortsFromEndpointSlices(t.EndpointSliceInformer.GetIndexer(), p.ID.Service.Namespace, p.ID.Service.Name, p.PortName, t.logger)
}
for _, ep := range endpointPorts {
portMap[int64(ep)] = true
}
}
}
var portStrs []string
for p := range portMap {
portStrs = append(portStrs, strconv.FormatInt(p, 10))
}
return portStrs
}
// isSimpleHTTPProbe returns true if the given Probe is:
// - an HTTPGet probe, as opposed to a tcp or exec probe
// - has no special host or headers fields, except for possibly an HTTP Host header
func isSimpleHTTPProbe(probe *api_v1.Probe) bool {
return (probe != nil && probe.ProbeHandler.HTTPGet != nil && probe.ProbeHandler.HTTPGet.Host == "" &&
(len(probe.ProbeHandler.HTTPGet.HTTPHeaders) == 0 ||
(len(probe.ProbeHandler.HTTPGet.HTTPHeaders) == 1 && probe.ProbeHandler.HTTPGet.HTTPHeaders[0].Name == "Host")))
}
// getProbeScheme returns the Kubernetes API URL scheme corresponding to the
// protocol.
func getProbeScheme(protocol annotations.AppProtocol) api_v1.URIScheme {
if protocol == annotations.ProtocolHTTP2 {
return api_v1.URISchemeHTTPS
}
return api_v1.URIScheme(string(protocol))
}
// GetProbe returns a probe that's used for the given nodeport
func (t *Translator) GetProbe(port utils.ServicePort) (*api_v1.Probe, error) {
sl := t.ServiceInformer.GetIndexer().List()
// Find the label and target port of the one service with the given nodePort
var service api_v1.Service
var svcPort api_v1.ServicePort
var found bool
OuterLoop:
for _, as := range sl {
service = *as.(*api_v1.Service)
for _, sp := range service.Spec.Ports {
svcPort = sp
// If service is NEG enabled, compare the service name and namespace instead
// This is because NEG enabled service is not required to have nodePort
if port.NEGEnabled && port.ID.Service.Namespace == service.Namespace && port.ID.Service.Name == service.Name && port.Port == sp.Port {
found = true
break OuterLoop
}
// only one Service can match this nodePort, try and look up
// the readiness probe of the pods behind it
if port.NodePort != 0 && int32(port.NodePort) == sp.NodePort {
found = true
break OuterLoop
}
}
}
if !found {
return nil, fmt.Errorf("unable to find nodeport %v in any service", port)
}
return t.getHTTPProbe(service, svcPort.TargetPort, port.Protocol)
}
// listPodsBySelector returns a list of all pods based on selector
func listPodsBySelector(indexer cache.Indexer, selector labels.Selector) (ret []*api_v1.Pod, err error) {
err = listAll(indexer, selector, func(m interface{}) {
ret = append(ret, m.(*api_v1.Pod))
})
return ret, err
}
// listAll iterates a store and passes selected item to a func
func listAll(store cache.Store, selector labels.Selector, appendFn cache.AppendFunc) error {
for _, m := range store.List() {
metadata, err := meta.Accessor(m)
if err != nil {
return err
}
if selector.Matches(labels.Set(metadata.GetLabels())) {
appendFn(m)
}
}
return nil
}
// finds the actual target port behind named target port, the name of the target port is the same as service port name
func listEndpointTargetPortsFromEndpointSlices(indexer cache.Indexer, namespace, name, svcPortName string, logger klog.Logger) []int {
slices, err := indexer.ByIndex(endpointslices.EndpointSlicesByServiceIndex, endpointslices.FormatEndpointSlicesServiceKey(namespace, name))
if len(slices) == 0 {
logger.Error(nil, "No Endpoint Slices found for service", "serviceKey", klog.KRef(namespace, name))
return []int{}
}
if err != nil {
logger.Error(err, "Failed to retrieve endpoint slices for service", "serviceKey", klog.KRef(namespace, name))
return []int{}
}
ret := []int{}
for _, sliceObj := range slices {
slice := sliceObj.(*discoveryapi.EndpointSlice)
for _, port := range slice.Ports {
if port.Protocol != nil && *port.Protocol == api_v1.ProtocolTCP && port.Name != nil && *port.Name == svcPortName && port.Port != nil {
ret = append(ret, int(*port.Port))
}
}
}
return ret
}
// orderedPods sorts a list of Pods by creation timestamp, using their names as a tie breaker.
type orderedPods []*api_v1.Pod
func (o orderedPods) Len() int { return len(o) }
func (o orderedPods) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
func (o orderedPods) Less(i, j int) bool {
if o[i].CreationTimestamp.Equal(&o[j].CreationTimestamp) {
return o[i].Name < o[j].Name
}
return o[i].CreationTimestamp.Before(&o[j].CreationTimestamp)
}