-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathops_kongpluginbinding.go
More file actions
558 lines (492 loc) · 16.6 KB
/
ops_kongpluginbinding.go
File metadata and controls
558 lines (492 loc) · 16.6 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
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 ops
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"slices"
sdkkonnectgo "github.com/Kong/sdk-konnect-go"
sdkkonnectcomp "github.com/Kong/sdk-konnect-go/models/components"
sdkkonnectops "github.com/Kong/sdk-konnect-go/models/operations"
"github.com/samber/lo"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/kong/kong-operator/v2/api/common/consts"
commonv1alpha1 "github.com/kong/kong-operator/v2/api/common/v1alpha1"
configurationv1 "github.com/kong/kong-operator/v2/api/configuration/v1"
configurationv1alpha1 "github.com/kong/kong-operator/v2/api/configuration/v1alpha1"
configurationv1beta1 "github.com/kong/kong-operator/v2/api/configuration/v1beta1"
"github.com/kong/kong-operator/v2/controller/konnect/constraints"
"github.com/kong/kong-operator/v2/controller/pkg/patch"
"github.com/kong/kong-operator/v2/internal/utils/crossnamespace"
"github.com/kong/kong-operator/v2/pkg/metadata"
)
// -----------------------------------------------------------------------------
// Konnect KongPlugin - ops functions
// -----------------------------------------------------------------------------
// createPlugin creates the Konnect Plugin entity.
func createPlugin(
ctx context.Context,
cl client.Client,
sdk sdkkonnectgo.PluginsSDK,
pluginBinding *configurationv1alpha1.KongPluginBinding,
) error {
controlPlaneID := pluginBinding.GetControlPlaneID()
if controlPlaneID == "" {
return CantPerformOperationWithoutControlPlaneIDError{Entity: pluginBinding, Op: CreateOp}
}
pluginInput, err := kongPluginBindingToSDKPluginInput(ctx, cl, pluginBinding)
if err != nil {
return err
}
resp, err := sdk.CreatePlugin(ctx,
controlPlaneID,
*pluginInput,
)
if errWrapped := wrapErrIfKonnectOpFailed(err, CreateOp, pluginBinding); errWrapped != nil {
return errWrapped
}
if resp == nil || resp.Plugin == nil || resp.Plugin.ID == nil {
return fmt.Errorf("failed creating %s: %w", pluginBinding.GetTypeName(), ErrNilResponse)
}
pluginBinding.SetKonnectID(*resp.Plugin.ID)
return nil
}
// updatePlugin updates the Konnect Plugin entity.
// It is assumed that provided KongPluginBinding has Konnect ID set in status.
// It returns an error if the KongPluginBinding does not have a ControlPlaneRef or
// if the operation fails.
func updatePlugin(
ctx context.Context,
sdk sdkkonnectgo.PluginsSDK,
cl client.Client,
pluginBinding *configurationv1alpha1.KongPluginBinding,
) error {
controlPlaneID := pluginBinding.GetControlPlaneID()
if controlPlaneID == "" {
return CantPerformOperationWithoutControlPlaneIDError{Entity: pluginBinding, Op: UpdateOp}
}
pluginInput, err := kongPluginBindingToSDKPluginInput(ctx, cl, pluginBinding)
if err != nil {
return err
}
id := pluginBinding.GetKonnectID()
_, err = sdk.UpsertPlugin(ctx,
sdkkonnectops.UpsertPluginRequest{
ControlPlaneID: controlPlaneID,
PluginID: id,
Plugin: *pluginInput,
},
)
if errWrap := wrapErrIfKonnectOpFailed(err, UpdateOp, pluginBinding); errWrap != nil {
return errWrap
}
return nil
}
// deletePlugin deletes a plugin in Konnect.
// The KongPluginBinding is assumed to have a Konnect ID set in status.
// It returns an error if the operation fails.
func deletePlugin(
ctx context.Context,
sdk sdkkonnectgo.PluginsSDK,
pb *configurationv1alpha1.KongPluginBinding,
) error {
id := pb.GetKonnectID()
_, err := sdk.DeletePlugin(ctx, pb.GetControlPlaneID(), id)
if errWrap := wrapErrIfKonnectOpFailed(err, DeleteOp, pb); errWrap != nil {
return handleDeleteError(ctx, err, pb)
}
return nil
}
// getPluginForUID lists plugins in Konnect with given k8s uid as its tag.
func getPluginForUID(
ctx context.Context,
sdk sdkkonnectgo.PluginsSDK,
pluginBinding *configurationv1alpha1.KongPluginBinding,
) (string, error) {
cpID := pluginBinding.GetControlPlaneID()
reqList := sdkkonnectops.ListPluginRequest{
// NOTE: only filter on object's UID.
// Other fields like name might have changed in the meantime but that's OK.
// Those will be enforced via subsequent updates.
ControlPlaneID: cpID,
Tags: new(UIDLabelForObject(pluginBinding)),
}
resp, err := sdk.ListPlugin(ctx, reqList)
if err != nil {
return "", fmt.Errorf("failed listing %s: %w", pluginBinding.GetTypeName(), err)
}
if resp == nil || resp.Object == nil {
return "", fmt.Errorf("failed listing %s: %w", pluginBinding.GetTypeName(), ErrNilResponse)
}
_, id, err := getMatchingEntryFromListResponseData(sliceToEntityWithIDPtrSlice(resp.Object.Data), pluginBinding)
return id, err
}
func adoptPluginBinding(
ctx context.Context,
sdk sdkkonnectgo.PluginsSDK,
cl client.Client,
pluginBinding *configurationv1alpha1.KongPluginBinding,
) error {
cpID := pluginBinding.GetControlPlaneID()
adoptOptions := pluginBinding.Spec.Adopt
if cpID == "" {
return KonnectEntityAdoptionMissingControlPlaneIDError{}
}
if adoptOptions == nil || adoptOptions.Konnect == nil {
return errors.New("Konnect adopt options must be provided")
}
konnectID := adoptOptions.Konnect.ID
resp, err := sdk.GetPlugin(ctx, sdkkonnectops.GetPluginRequest{
PluginID: konnectID,
ControlPlaneID: cpID,
})
if err != nil {
return KonnectEntityAdoptionFetchError{
KonnectID: konnectID,
Err: err,
}
}
if resp == nil || resp.Plugin == nil {
return fmt.Errorf("failed getting %s: %w", pluginBinding.GetTypeName(), ErrNilResponse)
}
if uidTag, hasUIDTag := findUIDTag(resp.Plugin.Tags); hasUIDTag && extractUIDFromTag(uidTag) != string(pluginBinding.UID) {
return KonnectEntityAdoptionUIDTagConflictError{
KonnectID: konnectID,
ActualUIDTag: extractUIDFromTag(uidTag),
}
}
adoptMode := adoptOptions.Mode
if adoptMode == "" {
adoptMode = commonv1alpha1.AdoptModeOverride
}
switch adoptMode {
case commonv1alpha1.AdoptModeOverride:
// Update the remote plugin to match the spec.
pluginBindingCopy := pluginBinding.DeepCopy()
pluginBindingCopy.SetKonnectID(konnectID)
if err := updatePlugin(ctx, sdk, cl, pluginBindingCopy); err != nil {
return err
}
case commonv1alpha1.AdoptModeMatch:
matches, err := pluginBindingMatches(ctx, cl, pluginBinding, resp.Plugin)
if err != nil {
return err
}
if !matches {
return KonnectEntityAdoptionNotMatchError{
KonnectID: konnectID,
}
}
default:
return fmt.Errorf("failed to adopt: adopt mode %q not supported", adoptMode)
}
pluginBinding.SetKonnectID(konnectID)
return nil
}
// -----------------------------------------------------------------------------
// Konnect KongPlugin - ops helpers
// -----------------------------------------------------------------------------
// kongPluginBindingToSDKPluginInput returns the SDK PluginInput for the KongPluginBinding.
// It uses the client.Client to fetch the KongPlugin and the targets referenced by the KongPluginBinding that are needed
// to create the SDK PluginInput.
func kongPluginBindingToSDKPluginInput(
ctx context.Context,
cl client.Client,
pluginBinding *configurationv1alpha1.KongPluginBinding,
) (*sdkkonnectcomp.Plugin, error) {
plugin, err := getReferencedPlugin(ctx, cl, pluginBinding)
if err != nil {
return nil, err
}
targets, err := getPluginBindingTargets(ctx, cl, pluginBinding)
if err != nil {
return nil, err
}
tags := GenerateTagsForObject(pluginBinding, metadata.ExtractTags(plugin)...)
return kongPluginWithTargetsToKongPluginInput(pluginBinding, plugin, targets, tags)
}
// getPluginBindingTargets returns the list of client objects referenced
// by the kongPluginBInding.spec.targets field.
func getPluginBindingTargets(
ctx context.Context,
cl client.Client,
pluginBinding *configurationv1alpha1.KongPluginBinding,
) ([]pluginTarget, error) {
targets := pluginBinding.Spec.Targets
if targets == nil {
return nil, nil
}
targetObjects := []pluginTarget{}
if ref := targets.ServiceReference; ref != nil {
ref := targets.ServiceReference
if ref.Kind != "KongService" {
return nil, fmt.Errorf("unsupported service target kind %q", ref.Kind)
}
kongService := configurationv1alpha1.KongService{}
kongService.SetName(ref.Name)
kongService.SetNamespace(pluginBinding.GetNamespace())
if err := cl.Get(ctx, client.ObjectKeyFromObject(&kongService), &kongService); err != nil {
return nil, err
}
targetObjects = append(targetObjects, &kongService)
}
if ref := targets.RouteReference; ref != nil {
if ref.Kind != "KongRoute" {
return nil, fmt.Errorf("unsupported route target kind %q", ref.Kind)
}
kongRoute := configurationv1alpha1.KongRoute{}
kongRoute.SetName(ref.Name)
kongRoute.SetNamespace(pluginBinding.GetNamespace())
if err := cl.Get(ctx, client.ObjectKeyFromObject(&kongRoute), &kongRoute); err != nil {
return nil, err
}
targetObjects = append(targetObjects, &kongRoute)
}
if ref := targets.ConsumerReference; ref != nil {
kongConsumer := configurationv1.KongConsumer{}
kongConsumer.SetName(ref.Name)
kongConsumer.SetNamespace(pluginBinding.GetNamespace())
if err := cl.Get(ctx, client.ObjectKeyFromObject(&kongConsumer), &kongConsumer); err != nil {
return nil, err
}
targetObjects = append(targetObjects, &kongConsumer)
}
if ref := targets.ConsumerGroupReference; ref != nil {
kongConsumerGroup := configurationv1beta1.KongConsumerGroup{}
kongConsumerGroup.SetName(ref.Name)
kongConsumerGroup.SetNamespace(pluginBinding.GetNamespace())
if err := cl.Get(ctx, client.ObjectKeyFromObject(&kongConsumerGroup), &kongConsumerGroup); err != nil {
return nil, err
}
targetObjects = append(targetObjects, &kongConsumerGroup)
}
return targetObjects, nil
}
// getReferencedPlugin returns the KongPlugin referenced by the KongPluginBinding.spec.pluginRef field.
func getReferencedPlugin(
ctx context.Context,
cl client.Client,
pluginBinding *configurationv1alpha1.KongPluginBinding,
) (*configurationv1.KongPlugin, error) {
// TODO(mlavacca): add support for KongClusterPlugin
var (
plugin configurationv1.KongPlugin
pluginGVK = metav1.GroupVersionKind{
Group: configurationv1.SchemeGroupVersion.Group,
Kind: "KongPlugin",
}
pluginRef = pluginBinding.Spec.PluginReference
)
plugin.SetName(pluginRef.Name)
if ns := pluginRef.Namespace; ns != "" && ns != pluginBinding.GetNamespace() {
err := crossnamespace.CheckKongReferenceGrantForResource(
ctx,
cl,
pluginBinding.Namespace,
ns,
pluginRef.Name,
metav1.GroupVersionKind(pluginBinding.GetObjectKind().GroupVersionKind()),
pluginGVK,
)
if err != nil {
msg := err.Error()
if crossnamespace.IsReferenceNotGranted(err) {
msg = fmt.Sprintf("KongReferenceGrants do not allow access to KongPlugin %s/%s", ns, pluginRef.Name)
}
if _, errStatus := patch.StatusWithCondition(
ctx, cl, pluginBinding,
consts.ConditionType(configurationv1alpha1.KongReferenceGrantConditionTypeResolvedRefs),
metav1.ConditionFalse,
configurationv1alpha1.KongReferenceGrantReasonRefNotPermitted,
msg,
); errStatus != nil {
return nil, errStatus
}
return nil, err
}
// Grant allows access.
if _, errStatus := patch.StatusWithCondition(
ctx, cl, pluginBinding,
consts.ConditionType(configurationv1alpha1.KongReferenceGrantConditionTypeResolvedRefs),
metav1.ConditionTrue,
configurationv1alpha1.KongReferenceGrantReasonResolvedRefs,
fmt.Sprintf("KongReferenceGrants allow access to KongPlugin %s/%s", ns, pluginRef.Name),
); errStatus != nil {
return nil, errStatus
}
plugin.SetNamespace(pluginRef.Namespace)
} else {
plugin.SetNamespace(pluginBinding.GetNamespace())
}
if err := cl.Get(ctx, client.ObjectKeyFromObject(&plugin), &plugin); err != nil {
return nil, err
}
return &plugin, nil
}
type pluginTarget interface {
client.Object
GetKonnectID() string
GetTypeName() string
}
// kongPluginWithTargetsToKongPluginInput converts a KongPlugin configuration along with KongPluginBinding's targets and
// tags to an SKD PluginInput.
func kongPluginWithTargetsToKongPluginInput(binding *configurationv1alpha1.KongPluginBinding, plugin *configurationv1.KongPlugin, targets []pluginTarget, tags []string) (*sdkkonnectcomp.Plugin, error) {
if binding.Spec.Scope == configurationv1alpha1.KongPluginBindingScopeOnlyTargets && len(targets) == 0 {
return nil, fmt.Errorf("no targets found for KongPluginBinding %s", client.ObjectKeyFromObject(plugin))
}
pluginConfig := map[string]any{}
if rawConfig := plugin.Config.Raw; rawConfig != nil {
// If the config is empty (a valid case), there's no need to unmarshal (as it would fail).
if err := json.Unmarshal(rawConfig, &pluginConfig); err != nil {
return nil, fmt.Errorf("failed to unmarshal KongPlugin %s config: %w", client.ObjectKeyFromObject(plugin), err)
}
}
pluginInput := &sdkkonnectcomp.Plugin{
Name: plugin.PluginName,
Config: pluginConfig,
Enabled: new(!plugin.Disabled),
Tags: tags,
}
if plugin.InstanceName != "" {
pluginInput.InstanceName = new(plugin.InstanceName)
}
if len(plugin.Protocols) > 0 {
pluginInput.Protocols = lo.Map(
plugin.Protocols,
func(p configurationv1.KongProtocol, _ int) sdkkonnectcomp.Protocols {
return sdkkonnectcomp.Protocols(p)
},
)
}
// TODO: add support for ordering https://github.com/kong/kong-operator/issues/1682
// TODO(mlavacca): check all the entities reference the same KonnectGatewayControlPlane
for _, t := range targets {
id := t.GetKonnectID()
if id == "" {
return nil, fmt.Errorf("%s %s is not configured in Konnect yet", constraints.EntityTypeNameForObj(t), client.ObjectKeyFromObject(t))
}
switch t := t.(type) {
case *configurationv1alpha1.KongService:
pluginInput.Service = &sdkkonnectcomp.PluginService{
ID: new(id),
}
case *configurationv1alpha1.KongRoute:
pluginInput.Route = &sdkkonnectcomp.PluginRoute{
ID: new(id),
}
case *configurationv1.KongConsumer:
pluginInput.Consumer = &sdkkonnectcomp.PluginConsumer{
ID: new(id),
}
case *configurationv1beta1.KongConsumerGroup:
pluginInput.ConsumerGroup = &sdkkonnectcomp.PluginConsumerGroup{
ID: new(id),
}
default:
return nil, fmt.Errorf("unsupported target type %T", t)
}
}
return pluginInput, nil
}
func pluginBindingMatches(
ctx context.Context,
cl client.Client,
binding *configurationv1alpha1.KongPluginBinding,
konnectPlugin *sdkkonnectcomp.Plugin,
) (bool, error) {
desired, err := kongPluginBindingToSDKPluginInput(ctx, cl, binding)
if err != nil {
return false, err
}
if desired == nil {
return false, fmt.Errorf("failed to render desired plugin input for %s", client.ObjectKeyFromObject(binding))
}
if desired.Name != konnectPlugin.Name {
return false, nil
}
if boolValueOrDefault(desired.Enabled, true) != boolValueOrDefault(konnectPlugin.Enabled, true) {
return false, nil
}
if stringValueOrEmpty(desired.InstanceName) != stringValueOrEmpty(konnectPlugin.InstanceName) {
return false, nil
}
if !protocolsEqual(desired.Protocols, konnectPlugin.Protocols) {
return false, nil
}
if !configsEqual(desired.Config, konnectPlugin.Config) {
return false, nil
}
if pluginServiceID(desired.Service) != pluginServiceID(konnectPlugin.Service) {
return false, nil
}
if pluginRouteID(desired.Route) != pluginRouteID(konnectPlugin.Route) {
return false, nil
}
if pluginConsumerID(desired.Consumer) != pluginConsumerID(konnectPlugin.Consumer) {
return false, nil
}
if pluginConsumerGroupID(desired.ConsumerGroup) != pluginConsumerGroupID(konnectPlugin.ConsumerGroup) {
return false, nil
}
return true, nil
}
func boolValueOrDefault(v *bool, def bool) bool {
if v == nil {
return def
}
return *v
}
func stringValueOrEmpty(v *string) string {
if v == nil {
return ""
}
return *v
}
func protocolsEqual(expected, actual []sdkkonnectcomp.Protocols) bool {
if len(expected) == 0 && len(actual) == 0 {
return true
}
exp := make([]string, len(expected))
for i, p := range expected {
exp[i] = string(p)
}
act := make([]string, len(actual))
for i, p := range actual {
act[i] = string(p)
}
slices.Sort(exp)
slices.Sort(act)
return reflect.DeepEqual(exp, act)
}
func configsEqual(expected, actual map[string]any) bool {
if len(expected) == 0 && len(actual) == 0 {
return true
}
return reflect.DeepEqual(expected, actual)
}
func pluginServiceID(service *sdkkonnectcomp.PluginService) string {
if service == nil || service.ID == nil {
return ""
}
return *service.ID
}
func pluginRouteID(route *sdkkonnectcomp.PluginRoute) string {
if route == nil || route.ID == nil {
return ""
}
return *route.ID
}
func pluginConsumerID(consumer *sdkkonnectcomp.PluginConsumer) string {
if consumer == nil || consumer.ID == nil {
return ""
}
return *consumer.ID
}
func pluginConsumerGroupID(group *sdkkonnectcomp.PluginConsumerGroup) string {
if group == nil || group.ID == nil {
return ""
}
return *group.ID
}