-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathingress_controller.go
More file actions
471 lines (414 loc) · 14.7 KB
/
ingress_controller.go
File metadata and controls
471 lines (414 loc) · 14.7 KB
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
package controller
import (
"context"
"fmt"
"reflect"
"github.com/api7/api7-ingress-controller/internal/controller/config"
"github.com/api7/api7-ingress-controller/internal/controller/indexer"
"github.com/api7/api7-ingress-controller/internal/provider"
"github.com/api7/gopkg/pkg/log"
"github.com/go-logr/logr"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
discoveryv1 "k8s.io/api/discovery/v1"
networkingv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
// IngressReconciler reconciles a Ingress object.
type IngressReconciler struct { //nolint:revive
client.Client
Scheme *runtime.Scheme
Log logr.Logger
Provider provider.Provider
}
// SetupWithManager sets up the controller with the Manager.
func (r *IngressReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&networkingv1.Ingress{},
builder.WithPredicates(
predicate.NewPredicateFuncs(r.checkIngressClass),
),
).
WithEventFilter(
predicate.Or(
predicate.GenerationChangedPredicate{},
predicate.AnnotationChangedPredicate{},
),
).
Watches(
&networkingv1.IngressClass{},
handler.EnqueueRequestsFromMapFunc(r.listIngressForIngressClass),
builder.WithPredicates(
predicate.NewPredicateFuncs(r.matchesIngressController),
),
).
Watches(
&discoveryv1.EndpointSlice{},
handler.EnqueueRequestsFromMapFunc(r.listIngressesByService),
).
Watches(
&corev1.Secret{},
handler.EnqueueRequestsFromMapFunc(r.listIngressesBySecret),
).
Complete(r)
}
// Reconcile handles the reconciliation of Ingress resources
func (r *IngressReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
ingress := new(networkingv1.Ingress)
if err := r.Get(ctx, req.NamespacedName, ingress); err != nil {
if client.IgnoreNotFound(err) == nil {
// Ingress was deleted, clean up corresponding resources
ingress.Namespace = req.Namespace
ingress.Name = req.Name
ingress.TypeMeta = metav1.TypeMeta{
Kind: KindIngress,
APIVersion: networkingv1.SchemeGroupVersion.String(),
}
if err := r.Provider.Delete(ctx, ingress); err != nil {
r.Log.Error(err, "failed to delete ingress resources", "ingress", ingress.Name)
return ctrl.Result{}, err
}
r.Log.Info("deleted ingress resources", "ingress", ingress.Name)
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
r.Log.Info("reconciling ingress", "ingress", ingress.Name)
// create a translate context
tctx := provider.NewDefaultTranslateContext(ctx)
// process TLS configuration
if err := r.processTLS(tctx, ingress); err != nil {
r.Log.Error(err, "failed to process TLS configuration", "ingress", ingress.Name)
return ctrl.Result{}, err
}
// process backend services
if err := r.processBackends(tctx, ingress); err != nil {
r.Log.Error(err, "failed to process backend services", "ingress", ingress.Name)
return ctrl.Result{}, err
}
// update the ingress resources
if err := r.Provider.Update(ctx, tctx, ingress); err != nil {
r.Log.Error(err, "failed to update ingress resources", "ingress", ingress.Name)
return ctrl.Result{}, err
}
// update the ingress status
if err := r.updateStatus(ctx, ingress); err != nil {
r.Log.Error(err, "failed to update ingress status", "ingress", ingress.Name)
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
// checkIngressClass check if the ingress uses the ingress class that we control
func (r *IngressReconciler) checkIngressClass(obj client.Object) bool {
ingress := obj.(*networkingv1.Ingress)
if ingress.Spec.IngressClassName == nil {
// handle the case where IngressClassName is not specified
// find all ingress classes and check if any of them is marked as default
ingressClassList := &networkingv1.IngressClassList{}
if err := r.List(context.Background(), ingressClassList, client.MatchingFields{
indexer.IngressClass: config.GetControllerName(),
}); err != nil {
r.Log.Error(err, "failed to list ingress classes")
return false
}
// find the ingress class that is marked as default
for _, ic := range ingressClassList.Items {
if IsDefaultIngressClass(&ic) && matchesController(ic.Spec.Controller) {
log.Debugw("match the default ingress class")
return true
}
}
log.Debugw("no default ingress class found")
return false
}
configuredClass := config.GetIngressClass()
// if the ingress class name matches the configured ingress class name, return true
if *ingress.Spec.IngressClassName == configuredClass {
log.Debugw("match the configured ingress class name")
return true
}
// if it does not match, check if the ingress class is controlled by us
ingressClass := networkingv1.IngressClass{}
if err := r.Client.Get(context.Background(), client.ObjectKey{Name: *ingress.Spec.IngressClassName}, &ingressClass); err != nil {
return false
}
return matchesController(ingressClass.Spec.Controller)
}
// matchesIngressController check if the ingress class is controlled by us
func (r *IngressReconciler) matchesIngressController(obj client.Object) bool {
ingressClass, ok := obj.(*networkingv1.IngressClass)
if !ok {
r.Log.Error(fmt.Errorf("unexpected object type"), "failed to convert object to IngressClass")
return false
}
return matchesController(ingressClass.Spec.Controller)
}
// listIngressForIngressClass list all ingresses that use a specific ingress class
func (r *IngressReconciler) listIngressForIngressClass(ctx context.Context, obj client.Object) []reconcile.Request {
ingressClass, ok := obj.(*networkingv1.IngressClass)
if !ok {
r.Log.Error(fmt.Errorf("unexpected object type"), "failed to convert object to IngressClass")
return nil
}
// check if the ingress class is the default ingress class
if IsDefaultIngressClass(ingressClass) {
ingressList := &networkingv1.IngressList{}
if err := r.List(ctx, ingressList); err != nil {
r.Log.Error(err, "failed to list ingresses for ingress class", "ingressclass", ingressClass.GetName())
return nil
}
requests := make([]reconcile.Request, 0, len(ingressList.Items))
for _, ingress := range ingressList.Items {
if ingress.Spec.IngressClassName == nil || *ingress.Spec.IngressClassName == "" ||
*ingress.Spec.IngressClassName == ingressClass.GetName() {
requests = append(requests, reconcile.Request{
NamespacedName: client.ObjectKey{
Namespace: ingress.Namespace,
Name: ingress.Name,
},
})
}
}
return requests
} else {
ingressList := &networkingv1.IngressList{}
if err := r.List(ctx, ingressList, client.MatchingFields{
indexer.IngressClassRef: ingressClass.GetName(),
}); err != nil {
r.Log.Error(err, "failed to list ingresses for ingress class", "ingressclass", ingressClass.GetName())
return nil
}
requests := make([]reconcile.Request, 0, len(ingressList.Items))
for _, ingress := range ingressList.Items {
requests = append(requests, reconcile.Request{
NamespacedName: client.ObjectKey{
Namespace: ingress.Namespace,
Name: ingress.Name,
},
})
}
return requests
}
}
// listIngressesByService list all ingresses that use a specific service
func (r *IngressReconciler) listIngressesByService(ctx context.Context, obj client.Object) []reconcile.Request {
endpointSlice, ok := obj.(*discoveryv1.EndpointSlice)
if !ok {
r.Log.Error(fmt.Errorf("unexpected object type"), "failed to convert object to EndpointSlice")
return nil
}
namespace := endpointSlice.GetNamespace()
serviceName := endpointSlice.Labels[discoveryv1.LabelServiceName]
ingressList := &networkingv1.IngressList{}
if err := r.List(ctx, ingressList, client.MatchingFields{
indexer.ServiceIndexRef: indexer.GenIndexKey(namespace, serviceName),
}); err != nil {
r.Log.Error(err, "failed to list ingresses by service", "service", serviceName)
return nil
}
requests := make([]reconcile.Request, 0, len(ingressList.Items))
for _, ingress := range ingressList.Items {
if r.checkIngressClass(&ingress) {
requests = append(requests, reconcile.Request{
NamespacedName: client.ObjectKey{
Namespace: ingress.Namespace,
Name: ingress.Name,
},
})
}
}
return requests
}
// listIngressesBySecret list all ingresses that use a specific secret
func (r *IngressReconciler) listIngressesBySecret(ctx context.Context, obj client.Object) []reconcile.Request {
secret, ok := obj.(*corev1.Secret)
if !ok {
r.Log.Error(fmt.Errorf("unexpected object type"), "failed to convert object to Secret")
return nil
}
namespace := secret.GetNamespace()
name := secret.GetName()
ingressList := &networkingv1.IngressList{}
if err := r.List(ctx, ingressList, client.MatchingFields{
indexer.SecretIndexRef: indexer.GenIndexKey(namespace, name),
}); err != nil {
r.Log.Error(err, "failed to list ingresses by secret", "secret", name)
return nil
}
requests := make([]reconcile.Request, 0, len(ingressList.Items))
for _, ingress := range ingressList.Items {
if r.checkIngressClass(&ingress) {
requests = append(requests, reconcile.Request{
NamespacedName: client.ObjectKey{
Namespace: ingress.Namespace,
Name: ingress.Name,
},
})
}
}
return requests
}
// processTLS process the TLS configuration of the ingress
func (r *IngressReconciler) processTLS(tctx *provider.TranslateContext, ingress *networkingv1.Ingress) error {
for _, tls := range ingress.Spec.TLS {
if tls.SecretName == "" {
continue
}
secret := corev1.Secret{}
if err := r.Get(tctx, client.ObjectKey{
Namespace: ingress.Namespace,
Name: tls.SecretName,
}, &secret); err != nil {
log.Error(err, "failed to get secret", "namespace", ingress.Namespace, "name", tls.SecretName)
return err
}
if secret.Data == nil {
log.Warnw("secret data is nil", zap.String("secret", secret.Namespace+"/"+secret.Name))
continue
}
// add the secret to the translate context
tctx.Secrets[types.NamespacedName{Namespace: ingress.Namespace, Name: tls.SecretName}] = &secret
}
return nil
}
// processBackends process the backend services of the ingress
func (r *IngressReconciler) processBackends(tctx *provider.TranslateContext, ingress *networkingv1.Ingress) error {
var terr error
// process all the backend services in the rules
for _, rule := range ingress.Spec.Rules {
if rule.HTTP == nil {
continue
}
for _, path := range rule.HTTP.Paths {
if path.Backend.Service == nil {
continue
}
service := path.Backend.Service
if err := r.processBackendService(tctx, ingress.Namespace, service); err != nil {
terr = err
}
}
}
return terr
}
// processBackendService process a single backend service
func (r *IngressReconciler) processBackendService(tctx *provider.TranslateContext, namespace string, backendService *networkingv1.IngressServiceBackend) error {
// get the service
var service corev1.Service
if err := r.Get(tctx, client.ObjectKey{
Namespace: namespace,
Name: backendService.Name,
}, &service); err != nil {
if client.IgnoreNotFound(err) == nil {
r.Log.Info("service not found", "namespace", namespace, "name", backendService.Name)
return nil
}
return err
}
// verify if the port exists
var portExists bool
if backendService.Port.Number != 0 {
for _, servicePort := range service.Spec.Ports {
if servicePort.Port == backendService.Port.Number {
portExists = true
break
}
}
} else if backendService.Port.Name != "" {
for _, servicePort := range service.Spec.Ports {
if servicePort.Name == backendService.Port.Name {
portExists = true
break
}
}
}
if !portExists {
err := fmt.Errorf("port(name: %s, number: %d) not found in service %s/%s", backendService.Port.Name, backendService.Port.Number, namespace, backendService.Name)
r.Log.Error(err, "service port not found")
return err
}
// get the endpoint slices
endpointSliceList := &discoveryv1.EndpointSliceList{}
if err := r.List(tctx, endpointSliceList,
client.InNamespace(namespace),
client.MatchingLabels{
discoveryv1.LabelServiceName: backendService.Name,
},
); err != nil {
r.Log.Error(err, "failed to list endpoint slices", "namespace", namespace, "name", backendService.Name)
return err
}
// save the endpoint slices to the translate context
tctx.EndpointSlices[client.ObjectKey{
Namespace: namespace,
Name: backendService.Name,
}] = endpointSliceList.Items
tctx.Services[client.ObjectKey{
Namespace: namespace,
Name: backendService.Name,
}] = &service
return nil
}
// updateStatus update the status of the ingress
func (r *IngressReconciler) updateStatus(ctx context.Context, ingress *networkingv1.Ingress) error {
var loadBalancerStatus networkingv1.IngressLoadBalancerStatus
// 1. use the IngressStatusAddress in the config
statusAddresses := config.GetIngressStatusAddress()
if len(statusAddresses) > 0 {
for _, addr := range statusAddresses {
if addr == "" {
continue
}
loadBalancerStatus.Ingress = append(loadBalancerStatus.Ingress, networkingv1.IngressLoadBalancerIngress{
IP: addr,
})
}
} else {
// 2. if the IngressStatusAddress is not configured, try to use the PublishService
publishService := config.GetIngressPublishService()
if publishService != "" {
// parse the namespace/name format
namespace, name, err := SplitMetaNamespaceKey(publishService)
if err != nil {
return fmt.Errorf("invalid ingress-publish-service format: %s, expected format: namespace/name", publishService)
}
// if the namespace is not specified, use the ingress namespace
if namespace == "" {
namespace = ingress.Namespace
}
svc := &corev1.Service{}
if err := r.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, svc); err != nil {
return fmt.Errorf("failed to get publish service %s: %w", publishService, err)
}
if svc.Spec.Type == corev1.ServiceTypeLoadBalancer {
// get the LoadBalancer IP and Hostname of the service
for _, ip := range svc.Status.LoadBalancer.Ingress {
if ip.IP != "" {
loadBalancerStatus.Ingress = append(loadBalancerStatus.Ingress, networkingv1.IngressLoadBalancerIngress{
IP: ip.IP,
})
}
if ip.Hostname != "" {
loadBalancerStatus.Ingress = append(loadBalancerStatus.Ingress, networkingv1.IngressLoadBalancerIngress{
Hostname: ip.Hostname,
})
}
}
}
}
}
// update the load balancer status
if len(loadBalancerStatus.Ingress) > 0 && !reflect.DeepEqual(ingress.Status.LoadBalancer, loadBalancerStatus) {
ingress.Status.LoadBalancer = loadBalancerStatus
return r.Status().Update(ctx, ingress)
}
return nil
}