-
Notifications
You must be signed in to change notification settings - Fork 321
/
apigateway_controller.go
558 lines (501 loc) · 17.3 KB
/
apigateway_controller.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
package controller
import (
"context"
"fmt"
"github.com/go-logr/logr"
"github.com/hashicorp/consul-k8s/control-plane/cache"
"github.com/hashicorp/consul-k8s/control-plane/consul"
"github.com/hashicorp/consul/api"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
gwapiv1a2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
gwapiv1b1 "sigs.k8s.io/gateway-api/apis/v1beta1"
)
const (
gatewaySecretCertificatesIndex = "__gateway-secret-certificates-index"
gatewayClassNameIndex = "__gateway-class-name-index"
referenceGrantTargetIndex = "__referencegrant-target-index"
httpRouteGatewayIndex = "__httproute-gateway-index"
httpRouteServiceIndex = "__httproute-service-index"
tcpRouteGatewayIndex = "__tcproute-gateway-index"
tcpRouteServiceIndex = "__tcproute-service-index"
kindSecret = "Secret"
kindService = "Service"
kindGateway = "Gateway"
gatewayControllerManagerName = "gateway-controller"
gatewayControllerClassName = "consul.hashicorp.com/gateway-controller"
)
type GatewayControllerConfig struct {
ConsulClientConfig *consul.Config
ConsulServerConnMgr consul.ServerConnectionManager
NamespacesEnabled bool
Partition string
Logger logr.Logger
}
// GatewayController handles reconciliations for Gateway objects.
type GatewayController struct {
cache *cache.Cache
client client.Client
controllerClassName gwapiv1b1.GatewayController
log logr.Logger
}
func (c *GatewayController) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var gateway gwapiv1b1.Gateway
if err := c.client.Get(ctx, req.NamespacedName, &gateway); err != nil {
if k8serrors.IsNotFound(err) {
// TODO: clean up resources
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
gatewayClassName := types.NamespacedName{Name: string(gateway.Spec.GatewayClassName)}
var gatewayclass gwapiv1b1.GatewayClass
if err := c.client.Get(ctx, gatewayClassName, &gatewayclass); err != nil {
if k8serrors.IsNotFound(err) {
// TODO: clean up resources
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
if gatewayclass.Spec.ControllerName != c.controllerClassName {
// TODO: clean up resources
return ctrl.Result{}, nil
}
// TODO: validate the class config
// TODO: validate a gateway finalizer
// TODO: reconcile resources
// TODO: sync any modified entries to Consul via cache.Write(entry)
return ctrl.Result{}, nil
}
// SetupGatewayControllerWithManager sets up the controller manager with the proper subscriptions for Gateways.
func SetupGatewayControllerWithManager(ctx context.Context, mgr ctrl.Manager, config GatewayControllerConfig) (*cache.Cache, error) {
if err := addIndexers(ctx, mgr, gatewayIndices...); err != nil {
return nil, err
}
cache := cache.New(cache.Config{
ConsulClientConfig: config.ConsulClientConfig,
ConsulServerConnMgr: config.ConsulServerConnMgr,
Logger: config.Logger,
NamespacesEnabled: config.NamespacesEnabled,
Partition: config.Partition,
Kinds: []string{
api.APIGateway,
api.HTTPRoute,
api.TCPRoute,
api.InlineCertificate,
},
})
c := &GatewayController{
client: mgr.GetClient(),
cache: cache,
controllerClassName: gwapiv1b1.GatewayController(gatewayControllerClassName),
log: config.Logger,
}
return cache, ctrl.NewControllerManagedBy(mgr).For(
&gwapiv1b1.Gateway{},
).Owns(
// Watch owned deployments we create and process owner Gateways.
&appsv1.Deployment{},
).Owns(
// Watch owned services we create and process owner Gateways.
&corev1.Service{},
).Owns(
// Watch owned pods we create and process owner Gateways.
&corev1.Pod{},
).Watches(
// Watch GatewayClass CRUDs and process affected Gateways.
source.NewKindWithCache(&gwapiv1b1.GatewayClass{}, mgr.GetCache()),
handler.EnqueueRequestsFromMapFunc(c.transformGatewayClass(ctx)),
).Watches(
// Watch HTTPRoute CRUDs and process affected Gateways.
source.NewKindWithCache(&gwapiv1b1.HTTPRoute{}, mgr.GetCache()),
handler.EnqueueRequestsFromMapFunc(c.transformHTTPRoute(ctx)),
).Watches(
// Watch TCPRoute CRUDs and process affected Gateways.
source.NewKindWithCache(&gwapiv1a2.TCPRoute{}, mgr.GetCache()),
handler.EnqueueRequestsFromMapFunc(c.transformTCPRoute(ctx)),
).Watches(
// Watch Secret CRUDs and process affected Gateways.
source.NewKindWithCache(&corev1.Secret{}, mgr.GetCache()),
handler.EnqueueRequestsFromMapFunc(c.transformSecret(ctx)),
).Watches(
// Watch ReferenceGrant CRUDs and process affected Gateways.
source.NewKindWithCache(&gwapiv1a2.ReferenceGrant{}, mgr.GetCache()),
handler.EnqueueRequestsFromMapFunc(c.transformReferenceGrant(ctx)),
).Watches(
// Subscribe to changes from Consul for APIGateways
&source.Channel{Source: cache.Subscribe(ctx, api.APIGateway, c.transformConsulGateway(ctx)).Events()},
&handler.EnqueueRequestForObject{},
).Watches(
// Subscribe to changes from Consul for HTTPRoutes
&source.Channel{Source: cache.Subscribe(ctx, api.APIGateway, c.transformConsulHTTPRoute(ctx)).Events()},
&handler.EnqueueRequestForObject{},
).Watches(
// Subscribe to changes from Consul for TCPRoutes
&source.Channel{Source: cache.Subscribe(ctx, api.APIGateway, c.transformConsulTCPRoute(ctx)).Events()},
&handler.EnqueueRequestForObject{},
).Watches(
// Subscribe to changes from Consul for InlineCertificates
&source.Channel{Source: cache.Subscribe(ctx, api.InlineCertificate, c.transformConsulInlineCertificate(ctx)).Events()},
&handler.EnqueueRequestForObject{},
).Complete(c)
}
func (c *GatewayController) transformGatewayClass(ctx context.Context) func(o client.Object) []reconcile.Request {
return func(o client.Object) []reconcile.Request {
gatewayclass := o.(*gwapiv1b1.GatewayClass)
gatewayList := &gwapiv1b1.GatewayList{}
if err := c.client.List(ctx, gatewayList, &client.ListOptions{
FieldSelector: fields.OneTermEqualSelector(gatewayClassNameIndex, gatewayclass.Name),
}); err != nil {
return nil
}
return objectsToRequests(pointersOf(gatewayList.Items))
}
}
func (c *GatewayController) transformHTTPRoute(ctx context.Context) func(o client.Object) []reconcile.Request {
return func(o client.Object) []reconcile.Request {
route := o.(*gwapiv1b1.HTTPRoute)
return refsToRequests(parentRefs(betaGroup, kindGateway, route.Namespace, route.Spec.ParentRefs))
}
}
func (c *GatewayController) transformTCPRoute(ctx context.Context) func(o client.Object) []reconcile.Request {
return func(o client.Object) []reconcile.Request {
route := o.(*gwapiv1a2.TCPRoute)
return refsToRequests(parentRefs(betaGroup, kindGateway, route.Namespace, route.Spec.ParentRefs))
}
}
func (c *GatewayController) transformReferenceGrant(ctx context.Context) func(o client.Object) []reconcile.Request {
return func(o client.Object) []reconcile.Request {
// just reconcile all gateways within the namespace
grant := o.(*gwapiv1b1.ReferenceGrant)
gatewayList := &gwapiv1b1.GatewayList{}
if err := c.client.List(ctx, gatewayList, &client.ListOptions{
Namespace: grant.Namespace,
}); err != nil {
return nil
}
return objectsToRequests(pointersOf(gatewayList.Items))
}
}
func (c *GatewayController) transformSecret(ctx context.Context) func(o client.Object) []reconcile.Request {
return func(o client.Object) []reconcile.Request {
secret := o.(*corev1.Secret)
gatewayList := &gwapiv1b1.GatewayList{}
if err := c.client.List(ctx, gatewayList, &client.ListOptions{
FieldSelector: fields.OneTermEqualSelector(gatewaySecretCertificatesIndex, secret.Name),
}); err != nil {
return nil
}
return objectsToRequests(pointersOf(gatewayList.Items))
}
}
func (c *GatewayController) transformConsulGateway(ctx context.Context) func(config api.ConfigEntry) []types.NamespacedName {
return func(config api.ConfigEntry) []types.NamespacedName {
meta, ok := metaToK8sMeta(config)
if !ok {
return nil
}
return []types.NamespacedName{meta}
}
}
func (c *GatewayController) transformConsulHTTPRoute(ctx context.Context) func(config api.ConfigEntry) []types.NamespacedName {
return func(config api.ConfigEntry) []types.NamespacedName {
route, ok := config.(*api.HTTPRouteConfigEntry)
if !ok {
return nil
}
return consulRefsToMeta(c.cache, route.Parents)
}
}
func (c *GatewayController) transformConsulTCPRoute(ctx context.Context) func(config api.ConfigEntry) []types.NamespacedName {
return func(config api.ConfigEntry) []types.NamespacedName {
route, ok := config.(*api.TCPRouteConfigEntry)
if !ok {
return nil
}
return consulRefsToMeta(c.cache, route.Parents)
}
}
func (c *GatewayController) transformConsulInlineCertificate(ctx context.Context) func(config api.ConfigEntry) []types.NamespacedName {
return func(config api.ConfigEntry) []types.NamespacedName {
meta, ok := metaToK8sMeta(config)
if !ok {
return nil
}
return requestsToRefs(c.transformSecret(ctx)(&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: meta.Name,
Namespace: meta.Namespace,
},
}))
}
}
var (
betaGroup = gwapiv1b1.GroupVersion.Group
betaVersion = gwapiv1b1.GroupVersion.Version
alphaGroup = gwapiv1a2.GroupVersion.Group
alphaVersion = gwapiv1a2.GroupVersion.Version
)
type Indexer struct {
Kind client.Object
Name string
Extractor client.IndexerFunc
}
func addIndexer(ctx context.Context, mgr manager.Manager, indexer Indexer) error {
return mgr.GetFieldIndexer().IndexField(ctx, indexer.Kind, indexer.Name, indexer.Extractor)
}
func addIndexers(ctx context.Context, mgr manager.Manager, indexers ...Indexer) error {
for _, indexer := range indexers {
if err := addIndexer(ctx, mgr, indexer); err != nil {
return err
}
}
return nil
}
func serviceRefsForHTTPRoute(route *gwapiv1b1.HTTPRoute) []types.NamespacedName {
var refs []types.NamespacedName
for _, rule := range route.Spec.Rules {
for _, backend := range rule.BackendRefs {
if nilOrEqual(backend.Group, "") && nilOrEqual(backend.Kind, kindService) {
// If an explicit Service namespace is not provided, use the route namespace to lookup the provided Service Name.
refs = append(refs, indexedNamespacedNameWithDefault(backend.Name, backend.Namespace, route.Namespace))
}
}
}
return refs
}
func serviceRefsForTCPRoute(route *gwapiv1a2.TCPRoute) []types.NamespacedName {
var refs []types.NamespacedName
for _, rule := range route.Spec.Rules {
for _, backend := range rule.BackendRefs {
if nilOrEqual(backend.Group, "") && nilOrEqual(backend.Kind, kindService) {
// If an explicit Service namespace is not provided, use the route namespace to lookup the provided Service Name.
refs = append(refs, indexedNamespacedNameWithDefault(backend.Name, backend.Namespace, route.Namespace))
}
}
}
return refs
}
var gatewayIndices = []Indexer{
// Gateway indexers
// extract class names from gateways
{
Name: gatewayClassNameIndex,
Kind: &gwapiv1b1.Gateway{},
Extractor: func(o client.Object) []string {
return []string{string(o.(*gwapiv1b1.Gateway).Spec.GatewayClassName)}
},
},
// extract secret-based certificates from gateways
{
Name: gatewaySecretCertificatesIndex,
Kind: &gwapiv1b1.Gateway{},
Extractor: func(o client.Object) []string {
gateway := o.(*gwapiv1b1.Gateway)
var secretReferences []string
for _, listener := range gateway.Spec.Listeners {
if listener.TLS == nil || *listener.TLS.Mode != gwapiv1b1.TLSModeTerminate {
continue
}
for _, cert := range listener.TLS.CertificateRefs {
if nilOrEqual(cert.Group, "") && nilOrEqual(cert.Kind, kindSecret) {
// If an explicit Secret namespace is not provided, use the Gateway namespace to lookup the provided Secret Name.
secretReferences = append(secretReferences, indexedNamespacedNameWithDefault(cert.Name, cert.Namespace, gateway.Namespace).String())
}
}
}
return secretReferences
},
},
// ReferenceGrant indexers
{
Name: referenceGrantTargetIndex,
Kind: &gwapiv1b1.ReferenceGrant{},
Extractor: func(o client.Object) []string {
grant := o.(*gwapiv1a2.ReferenceGrant)
var kinds []string
for _, target := range grant.Spec.To {
kinds = append(kinds, string(target.Kind))
}
return kinds
},
},
// HTTPRoute indexers
// extract gateway parents from http route
{
Name: httpRouteGatewayIndex,
Kind: &gwapiv1b1.HTTPRoute{},
Extractor: func(o client.Object) []string {
route := o.(*gwapiv1b1.HTTPRoute)
// If an explicit Gateway namespace is not provided, use the route namespace to lookup the provided Gateway Name.
return parentRefsToIndexed(betaGroup, kindGateway, route.Namespace, route.Spec.ParentRefs)
},
},
// extract service upstreams from http route
{
Name: httpRouteGatewayIndex,
Kind: &gwapiv1b1.HTTPRoute{},
Extractor: func(o client.Object) []string {
route := o.(*gwapiv1b1.HTTPRoute)
return stringArray(serviceRefsForHTTPRoute(route))
},
},
// TCPRoute indexers
// extract gateway parents from tcp route
{
Name: tcpRouteGatewayIndex,
Kind: &gwapiv1a2.TCPRoute{},
Extractor: func(o client.Object) []string {
route := o.(*gwapiv1a2.TCPRoute)
// If an explicit Gateway namespace is not provided, use the route namespace to lookup the provided Gateway Name.
return parentRefsToIndexed(betaGroup, kindGateway, route.Namespace, route.Spec.ParentRefs)
},
},
// extract service upstreams from tcp route
{
Name: tcpRouteServiceIndex,
Kind: &gwapiv1a2.TCPRoute{},
Extractor: func(o client.Object) []string {
route := o.(*gwapiv1a2.TCPRoute)
return stringArray(serviceRefsForTCPRoute(route))
},
},
}
const (
metaKeyKubeNS = "k8s-namespace"
metaKeyKubeName = "k8s-name"
)
func nilOrEqual[T ~string](v *T, check string) bool {
return v == nil || string(*v) == check
}
func derefOr[T any](v *T, val T) T {
if v == nil {
return val
}
return *v
}
func pointerTo[T any](v T) *T {
return &v
}
func derefStringOr[T ~string, U ~string](v *T, val U) string {
if v == nil {
return string(val)
}
return string(*v)
}
func indexedNamespacedNameWithDefault[T ~string, U ~string, V ~string](t T, u *U, v V) types.NamespacedName {
return types.NamespacedName{
Namespace: derefStringOr(u, v),
Name: string(t),
}
}
func stringArray[T fmt.Stringer](t []T) []string {
strings := make([]string, 0, len(t))
for i, v := range t {
strings[i] = v.String()
}
return strings
}
func parentRefsToIndexed(group, kind, namespace string, refs []gwapiv1b1.ParentReference) []string {
return stringArray(parentRefs(group, kind, namespace, refs))
}
func parentRefs(group, kind, namespace string, refs []gwapiv1b1.ParentReference) []types.NamespacedName {
indexed := []types.NamespacedName{}
for _, parent := range refs {
if nilOrEqual(parent.Group, group) && nilOrEqual(parent.Kind, kind) {
indexed = append(indexed, indexedNamespacedNameWithDefault(parent.Name, parent.Namespace, namespace))
}
}
return indexed
}
func objectsToRequests[T metav1.Object](objects []T) []reconcile.Request {
var requests []reconcile.Request
for _, object := range objects {
requests = append(requests, reconcile.Request{
NamespacedName: types.NamespacedName{
Namespace: object.GetNamespace(),
Name: object.GetName(),
},
})
}
return requests
}
func objectsToMeta[T metav1.Object](objects []T) []types.NamespacedName {
var meta []types.NamespacedName
for _, object := range objects {
meta = append(meta, types.NamespacedName{
Namespace: object.GetNamespace(),
Name: object.GetName(),
})
}
return meta
}
func metaToK8sMeta(config api.ConfigEntry) (types.NamespacedName, bool) {
meta := config.GetMeta()
namespace, ok := meta[metaKeyKubeNS]
if !ok {
return types.NamespacedName{}, false
}
name, ok := meta[metaKeyKubeName]
if !ok {
return types.NamespacedName{}, false
}
return types.NamespacedName{
Namespace: namespace,
Name: name,
}, true
}
func k8sToMeta(o client.Object) map[string]string {
return map[string]string{
metaKeyKubeNS: o.GetNamespace(),
metaKeyKubeName: o.GetName(),
}
}
func consulRefsToMeta(cache *cache.Cache, refs []api.ResourceReference) []types.NamespacedName {
metaSet := map[types.NamespacedName]struct{}{}
for _, ref := range refs {
if parent := cache.Get(ref); parent != nil {
if k8sMeta, ok := metaToK8sMeta(parent); ok {
metaSet[k8sMeta] = struct{}{}
}
}
}
meta := []types.NamespacedName{}
for namespacedName := range metaSet {
meta = append(meta, namespacedName)
}
return meta
}
func refsToRequests(objects []types.NamespacedName) []reconcile.Request {
var requests []reconcile.Request
for _, object := range objects {
requests = append(requests, reconcile.Request{
NamespacedName: object,
})
}
return requests
}
func requestsToRefs(objects []reconcile.Request) []types.NamespacedName {
var refs []types.NamespacedName
for _, object := range objects {
refs = append(refs, object.NamespacedName)
}
return refs
}
func pointersOf[T any](objects []T) []*T {
pointers := make([]*T, 0, len(objects))
for i, object := range objects {
pointers[i] = pointerTo(object)
}
return pointers
}