-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathops.go
More file actions
910 lines (841 loc) · 33.2 KB
/
ops.go
File metadata and controls
910 lines (841 loc) · 33.2 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
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
package ops
import (
"context"
"errors"
"fmt"
"strings"
"time"
sdkkonnecterrs "github.com/Kong/sdk-konnect-go/models/sdkerrors"
"github.com/go-logr/logr"
"github.com/samber/lo"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
ctrllog "sigs.k8s.io/controller-runtime/pkg/log"
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"
kcfgkonnect "github.com/kong/kong-operator/v2/api/konnect"
konnectv1alpha1 "github.com/kong/kong-operator/v2/api/konnect/v1alpha1"
konnectv1alpha2 "github.com/kong/kong-operator/v2/api/konnect/v1alpha2"
"github.com/kong/kong-operator/v2/controller/konnect/constraints"
sdkops "github.com/kong/kong-operator/v2/controller/konnect/ops/sdk"
"github.com/kong/kong-operator/v2/controller/pkg/log"
"github.com/kong/kong-operator/v2/internal/metrics"
"github.com/kong/kong-operator/v2/internal/utils/crossnamespace"
k8sutils "github.com/kong/kong-operator/v2/pkg/utils/kubernetes"
)
// Op is the type for the operation type of a Konnect entity.
type Op string
const (
// CreateOp is the operation type for creating a Konnect entity.
CreateOp Op = "create"
// GetOp is the operation type for getting a Konnect entity.
GetOp Op = "get"
// UpdateOp is the operation type for updating a Konnect entity.
UpdateOp Op = "update"
// DeleteOp is the operation type for deleting a Konnect entity.
DeleteOp Op = "delete"
// AdoptOp is the operation type for adopting an existing Konnect entity.
AdoptOp Op = "adopt"
)
// Create creates a Konnect entity.
func Create[
T constraints.SupportedKonnectEntityType,
TEnt constraints.EntityType[T],
](
ctx context.Context,
sdk sdkops.SDKWrapper,
cl client.Client,
metricRecorder metrics.Recorder,
e TEnt,
) (*T, error) {
var (
err error
start = time.Now()
entityType = e.GetTypeName()
statusCode int
)
switch ent := any(e).(type) {
case *konnectv1alpha2.KonnectGatewayControlPlane:
err = ensureControlPlane(ctx, sdk.GetControlPlaneSDK(), sdk.GetControlPlaneGroupSDK(), cl, ent)
case *konnectv1alpha1.KonnectCloudGatewayNetwork:
err = createKonnectNetwork(ctx, sdk.GetCloudGatewaysSDK(), ent)
case *konnectv1alpha1.KonnectCloudGatewayDataPlaneGroupConfiguration:
err = createKonnectDataPlaneGroupConfiguration(ctx, sdk.GetCloudGatewaysSDK(), cl, ent, sdk.GetServer().Region())
case *konnectv1alpha1.KonnectCloudGatewayTransitGateway:
err = createKonnectTransitGateway(ctx, sdk.GetCloudGatewaysSDK(), ent)
case *configurationv1alpha1.KongService:
err = createService(ctx, sdk.GetServicesSDK(), ent)
case *configurationv1alpha1.KongRoute:
err = createRoute(ctx, sdk.GetRoutesSDK(), ent)
case *configurationv1.KongConsumer:
err = createConsumer(ctx, sdk.GetConsumersSDK(), sdk.GetConsumerGroupsSDK(), cl, ent)
case *configurationv1beta1.KongConsumerGroup:
err = createConsumerGroup(ctx, sdk.GetConsumerGroupsSDK(), ent)
case *configurationv1alpha1.KongPluginBinding:
err = createPlugin(ctx, cl, sdk.GetPluginSDK(), ent)
case *configurationv1alpha1.KongUpstream:
err = createUpstream(ctx, sdk.GetUpstreamsSDK(), ent)
case *configurationv1alpha1.KongCredentialBasicAuth:
err = createKongCredentialBasicAuth(ctx, sdk.GetBasicAuthCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialAPIKey:
err = createKongCredentialAPIKey(ctx, sdk.GetAPIKeyCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialACL:
err = createKongCredentialACL(ctx, sdk.GetACLCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialJWT:
err = createKongCredentialJWT(ctx, sdk.GetJWTCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialHMAC:
err = createKongCredentialHMAC(ctx, sdk.GetHMACCredentialsSDK(), ent)
case *configurationv1alpha1.KongCACertificate:
err = createCACertificate(ctx, cl, sdk.GetCACertificatesSDK(), ent)
case *configurationv1alpha1.KongCertificate:
err = createCertificate(ctx, cl, sdk.GetCertificatesSDK(), ent)
case *configurationv1alpha1.KongTarget:
err = createTarget(ctx, sdk.GetTargetsSDK(), ent)
case *configurationv1alpha1.KongVault:
err = createVault(ctx, sdk.GetVaultSDK(), ent)
case *configurationv1alpha1.KongKey:
err = createKey(ctx, sdk.GetKeysSDK(), ent)
case *configurationv1alpha1.KongKeySet:
err = createKeySet(ctx, sdk.GetKeySetsSDK(), ent)
case *configurationv1alpha1.KongSNI:
err = createSNI(ctx, sdk.GetSNIsSDK(), ent)
case *configurationv1alpha1.KongDataPlaneClientCertificate:
err = CreateKongDataPlaneClientCertificate(ctx, sdk.GetDataPlaneCertificatesSDK(), ent)
// ---------------------------------------------------------------------
// TODO: add other Konnect types
default:
return nil, fmt.Errorf("unsupported entity type %T", ent)
}
var errGet error
switch {
case ErrorIsCreateConflict(err):
// If there was a conflict on the create request, we can assume the entity already exists.
// We'll get its Konnect ID by listing all entities of its type filtered by the Kubernetes object UID.
var id string
switch ent := any(e).(type) {
case *konnectv1alpha2.KonnectGatewayControlPlane:
id, errGet = getControlPlaneForUID(ctx, sdk.GetControlPlaneSDK(), sdk.GetControlPlaneGroupSDK(), cl, ent)
case *konnectv1alpha1.KonnectCloudGatewayNetwork:
// NOTE: since Cloud Gateways resource do not support labels/tags,
// we can't reliably get the Konnect ID for a Cloud Gateway Network
// given a K8s object UID.
// For now this code uses a list, using a name filter, to get the Konnect ID.
id, err = getKonnectNetworkMatchingSpecName(ctx, sdk.GetCloudGatewaysSDK(), ent)
case *konnectv1alpha1.KonnectCloudGatewayDataPlaneGroupConfiguration:
// TODO: can't get the ID for a DataPlaneGroupConfiguration
// as this resource type does not support labels/tags.
case *konnectv1alpha1.KonnectCloudGatewayTransitGateway:
id, err = getKonnectTransitGatewayMatchingSpecName(ctx, sdk.GetCloudGatewaysSDK(), ent)
case *configurationv1alpha1.KongService:
id, errGet = getKongServiceForUID(ctx, sdk.GetServicesSDK(), ent)
case *configurationv1alpha1.KongRoute:
id, errGet = getKongRouteForUID(ctx, sdk.GetRoutesSDK(), ent)
case *configurationv1alpha1.KongSNI:
id, errGet = getKongSNIForUID(ctx, sdk.GetSNIsSDK(), ent)
case *configurationv1.KongConsumer:
id, errGet = getKongConsumerForUID(ctx, sdk.GetConsumersSDK(), ent)
case *configurationv1beta1.KongConsumerGroup:
id, errGet = getKongConsumerGroupForUID(ctx, sdk.GetConsumerGroupsSDK(), ent)
case *configurationv1alpha1.KongKeySet:
id, errGet = getKongKeySetForUID(ctx, sdk.GetKeySetsSDK(), ent)
case *configurationv1alpha1.KongKey:
id, errGet = getKongKeyForUID(ctx, sdk.GetKeysSDK(), ent)
case *configurationv1alpha1.KongUpstream:
id, errGet = getKongUpstreamForUID(ctx, sdk.GetUpstreamsSDK(), ent)
case *configurationv1alpha1.KongTarget:
id, errGet = getKongTargetForUID(ctx, sdk.GetTargetsSDK(), ent)
case *configurationv1alpha1.KongPluginBinding:
id, errGet = getPluginForUID(ctx, sdk.GetPluginSDK(), ent)
case *configurationv1alpha1.KongVault:
id, errGet = getKongVaultForUID(ctx, sdk.GetVaultSDK(), ent)
case *configurationv1alpha1.KongCredentialHMAC:
id, errGet = getKongCredentialHMACForUID(ctx, sdk.GetHMACCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialJWT:
id, errGet = getKongCredentialJWTForUID(ctx, sdk.GetJWTCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialBasicAuth:
id, errGet = getKongCredentialBasicAuthForUID(ctx, sdk.GetBasicAuthCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialAPIKey:
id, errGet = getKongCredentialAPIKeyForUID(ctx, sdk.GetAPIKeyCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialACL:
id, errGet = getKongCredentialACLForUID(ctx, sdk.GetACLCredentialsSDK(), ent)
case *configurationv1alpha1.KongCertificate:
id, errGet = getKongCertificateForUID(ctx, sdk.GetCertificatesSDK(), ent)
case *configurationv1alpha1.KongCACertificate:
id, errGet = getKongCACertificateForUID(ctx, sdk.GetCACertificatesSDK(), ent)
// ---------------------------------------------------------------------
// TODO: add other Konnect types
default:
return e, fmt.Errorf("conflict on create request for %T %s, but no conflict handling implemented: %w",
e, client.ObjectKeyFromObject(e), err,
)
}
if errGet == nil && id != "" {
e.SetKonnectID(id)
SetKonnectEntityProgrammedConditionTrue(e)
} else {
if errGet != nil {
err = fmt.Errorf("trying to find a matching Konnect entity matching the ID failed: %w, %w", errGet, err)
}
SetKonnectEntityProgrammedConditionFalse(e, kcfgkonnect.KonnectEntitiesFailedToCreateReason, err)
}
case err != nil:
if errSDK, ok := errors.AsType[*sdkkonnecterrs.SDKError](err); ok {
statusCode = errSDK.StatusCode
SetKonnectEntityProgrammedConditionFalse(
e, kcfgkonnect.KonnectEntitiesFailedToCreateReason, errSDK)
} else if errRelationsFailed, ok := errors.AsType[KonnectEntityCreatedButRelationsFailedError](err); ok {
e.SetKonnectID(errRelationsFailed.KonnectID)
SetKonnectEntityProgrammedConditionFalse(e, errRelationsFailed.Reason, errRelationsFailed.Err)
} else {
SetKonnectEntityProgrammedConditionFalse(e, kcfgkonnect.KonnectEntitiesFailedToCreateReason, err)
}
default:
SetKonnectEntityProgrammedConditionTrue(e)
}
// For mirrorable entities, we need to check if the source type is mirror
// and set the mirrored condition accordingly.
if isMirrorableEntity(e) {
if isMirrorEntity(e) {
if err == nil {
SetKonnectEntityMirroredConditionTrue(e)
} else {
SetKonnectEntityMirroredConditionFalse(e, err)
}
}
}
logOpComplete(ctx, start, CreateOp, e, err)
if err != nil {
metricRecorder.RecordKonnectEntityOperationFailure(
sdk.GetServerURL(),
metrics.KonnectEntityOperationCreate,
entityType,
time.Since(start),
statusCode,
)
} else {
metricRecorder.RecordKonnectEntityOperationSuccess(
sdk.GetServerURL(),
metrics.KonnectEntityOperationCreate,
entityType,
time.Since(start),
)
}
logger := loggerForEntity(ctx, e, CreateOp)
err = IgnoreUnrecoverableAPIErr(err, logger)
err = IgnoreAlreadyHandledErr(err, logger)
return e, err
}
// Delete deletes a Konnect entity.
// It returns an error if the entity does not have a Konnect ID or if the operation fails.
func Delete[
T constraints.SupportedKonnectEntityType,
TEnt constraints.EntityType[T],
](ctx context.Context, sdk sdkops.SDKWrapper, cl client.Client, metricRecorder metrics.Recorder, ent TEnt) error {
if ent.GetKonnectStatus().GetKonnectID() == "" {
cond, ok := k8sutils.GetCondition(konnectv1alpha1.KonnectEntityProgrammedConditionType, ent)
if ok && cond.Status == metav1.ConditionTrue {
return fmt.Errorf(
"can't delete %T %s when it does not have the Konnect ID",
ent, client.ObjectKeyFromObject(ent),
)
}
return nil
}
var (
err error
start = time.Now()
entityType = ent.GetTypeName()
statusCode int
)
switch ent := any(ent).(type) {
case *konnectv1alpha2.KonnectGatewayControlPlane:
err = deleteControlPlane(ctx, sdk.GetControlPlaneSDK(), ent)
case *konnectv1alpha1.KonnectCloudGatewayNetwork:
err = deleteKonnectNetwork(ctx, sdk.GetCloudGatewaysSDK(), ent)
case *konnectv1alpha1.KonnectCloudGatewayDataPlaneGroupConfiguration:
err = deleteKonnectDataPlaneGroupConfiguration(ctx, sdk.GetCloudGatewaysSDK(), ent, sdk.GetServer().Region())
case *konnectv1alpha1.KonnectCloudGatewayTransitGateway:
err = deleteKonnectTransitGateway(ctx, sdk.GetCloudGatewaysSDK(), ent)
case *configurationv1alpha1.KongService:
err = deleteService(ctx, sdk.GetServicesSDK(), ent)
case *configurationv1alpha1.KongRoute:
err = deleteRoute(ctx, sdk.GetRoutesSDK(), ent)
case *configurationv1.KongConsumer:
err = deleteConsumer(ctx, sdk.GetConsumersSDK(), ent)
case *configurationv1beta1.KongConsumerGroup:
err = deleteConsumerGroup(ctx, sdk.GetConsumerGroupsSDK(), ent)
case *configurationv1alpha1.KongPluginBinding:
err = deletePlugin(ctx, sdk.GetPluginSDK(), ent)
case *configurationv1alpha1.KongUpstream:
err = deleteUpstream(ctx, sdk.GetUpstreamsSDK(), ent)
case *configurationv1alpha1.KongCredentialBasicAuth:
err = deleteKongCredentialBasicAuth(ctx, sdk.GetBasicAuthCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialAPIKey:
err = deleteKongCredentialAPIKey(ctx, sdk.GetAPIKeyCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialACL:
err = deleteKongCredentialACL(ctx, sdk.GetACLCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialJWT:
err = deleteKongCredentialJWT(ctx, sdk.GetJWTCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialHMAC:
err = deleteKongCredentialHMAC(ctx, sdk.GetHMACCredentialsSDK(), ent)
case *configurationv1alpha1.KongCACertificate:
err = deleteCACertificate(ctx, sdk.GetCACertificatesSDK(), ent)
case *configurationv1alpha1.KongCertificate:
err = deleteCertificate(ctx, sdk.GetCertificatesSDK(), ent)
case *configurationv1alpha1.KongTarget:
err = deleteTarget(ctx, sdk.GetTargetsSDK(), ent)
case *configurationv1alpha1.KongVault:
err = deleteVault(ctx, sdk.GetVaultSDK(), ent)
case *configurationv1alpha1.KongKey:
err = deleteKey(ctx, sdk.GetKeysSDK(), ent)
case *configurationv1alpha1.KongKeySet:
err = deleteKeySet(ctx, sdk.GetKeySetsSDK(), ent)
case *configurationv1alpha1.KongSNI:
err = deleteSNI(ctx, sdk.GetSNIsSDK(), ent)
case *configurationv1alpha1.KongDataPlaneClientCertificate:
err = DeleteKongDataPlaneClientCertificate(ctx, sdk.GetDataPlaneCertificatesSDK(), ent)
// ---------------------------------------------------------------------
// TODO: add other Konnect types
default:
return fmt.Errorf("unsupported entity type %T", ent)
}
if err != nil {
if errSDK, ok := errors.AsType[*sdkkonnecterrs.SDKError](err); ok {
statusCode = errSDK.StatusCode
}
metricRecorder.RecordKonnectEntityOperationFailure(
sdk.GetServerURL(),
metrics.KonnectEntityOperationDelete,
entityType,
time.Since(start),
statusCode,
)
} else {
metricRecorder.RecordKonnectEntityOperationSuccess(
sdk.GetServerURL(),
metrics.KonnectEntityOperationDelete,
entityType,
time.Since(start),
)
}
logOpComplete(ctx, start, DeleteOp, ent, err)
// Clear the instance field from the error to avoid requeueing the resource
// because of the trace ID in the instance field is different for each request.
err = ClearInstanceFromError(err)
return err
}
func shouldUpdate[
T constraints.SupportedKonnectEntityType,
TEnt constraints.EntityType[T],
](
ctx context.Context,
ent TEnt,
syncPeriod time.Duration,
now time.Time,
) (bool, ctrl.Result) {
var (
condProgrammed, ok = k8sutils.GetCondition(konnectv1alpha1.KonnectEntityProgrammedConditionType, ent)
timeFromLastUpdate = time.Since(condProgrammed.LastTransitionTime.Time)
)
// If the entity is already programmed and the last update was less than
// the configured sync period, requeue after the remaining time.
if ok &&
condProgrammed.Status == metav1.ConditionTrue &&
condProgrammed.Reason == konnectv1alpha1.KonnectEntityProgrammedReasonProgrammed &&
condProgrammed.ObservedGeneration == ent.GetObjectMeta().GetGeneration() &&
timeFromLastUpdate <= syncPeriod {
requeueAfter := syncPeriod - timeFromLastUpdate
log.Debug(ctrllog.FromContext(ctx),
"no need for update, requeueing after configured sync period",
"last_update", condProgrammed.LastTransitionTime.String(),
"time_from_last_update", timeFromLastUpdate.String(),
"requeue_after", requeueAfter.String(),
"requeue_at", now.Add(requeueAfter).String(),
)
return false, ctrl.Result{
RequeueAfter: requeueAfter,
}
}
return true, ctrl.Result{}
}
// Update updates a Konnect entity.
// It returns an error if the entity does not have a Konnect ID or if the operation fails.
func Update[
T constraints.SupportedKonnectEntityType,
TEnt constraints.EntityType[T],
](
ctx context.Context,
sdk sdkops.SDKWrapper,
syncPeriod time.Duration,
cl client.Client,
metricRecorder metrics.Recorder,
e TEnt,
) (ctrl.Result, error) {
now := time.Now()
if ok, res := shouldUpdate(ctx, e, syncPeriod, now); !ok {
return res, nil
}
if e.GetKonnectStatus().GetKonnectID() == "" {
return ctrl.Result{}, fmt.Errorf(
"can't update %T %s when it does not have the Konnect ID",
e, client.ObjectKeyFromObject(e),
)
}
var (
err error
entityType = e.GetTypeName()
statusCode int
start = time.Now()
)
switch ent := any(e).(type) {
case *konnectv1alpha2.KonnectGatewayControlPlane:
// if the ControlPlane is of type origin, enforce the spec on Konnect.
if *ent.Spec.Source == commonv1alpha1.EntitySourceOrigin {
err = updateControlPlane(ctx, sdk.GetControlPlaneSDK(), sdk.GetControlPlaneGroupSDK(), cl, ent)
}
case *konnectv1alpha1.KonnectCloudGatewayNetwork:
err = updateKonnectNetwork(ctx, sdk.GetCloudGatewaysSDK(), ent)
case *konnectv1alpha1.KonnectCloudGatewayDataPlaneGroupConfiguration:
err = updateKonnectDataPlaneGroupConfiguration(ctx, sdk.GetCloudGatewaysSDK(), cl, ent, sdk.GetServer())
case *konnectv1alpha1.KonnectCloudGatewayTransitGateway:
err = updateKonnectTransitGateway(ctx, sdk.GetCloudGatewaysSDK(), ent)
case *configurationv1alpha1.KongService:
err = updateService(ctx, sdk.GetServicesSDK(), ent)
case *configurationv1alpha1.KongRoute:
err = updateRoute(ctx, sdk.GetRoutesSDK(), ent)
case *configurationv1.KongConsumer:
err = updateConsumer(ctx, sdk.GetConsumersSDK(), sdk.GetConsumerGroupsSDK(), cl, ent)
case *configurationv1beta1.KongConsumerGroup:
err = updateConsumerGroup(ctx, sdk.GetConsumerGroupsSDK(), ent)
case *configurationv1alpha1.KongPluginBinding:
err = updatePlugin(ctx, sdk.GetPluginSDK(), cl, ent)
case *configurationv1alpha1.KongUpstream:
err = updateUpstream(ctx, sdk.GetUpstreamsSDK(), ent)
case *configurationv1alpha1.KongCredentialBasicAuth:
err = updateKongCredentialBasicAuth(ctx, sdk.GetBasicAuthCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialAPIKey:
err = updateKongCredentialAPIKey(ctx, sdk.GetAPIKeyCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialACL:
err = updateKongCredentialACL(ctx, sdk.GetACLCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialJWT:
err = updateKongCredentialJWT(ctx, sdk.GetJWTCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialHMAC:
err = updateKongCredentialHMAC(ctx, sdk.GetHMACCredentialsSDK(), ent)
case *configurationv1alpha1.KongCACertificate:
err = updateCACertificate(ctx, cl, sdk.GetCACertificatesSDK(), ent)
case *configurationv1alpha1.KongCertificate:
err = updateCertificate(ctx, cl, sdk.GetCertificatesSDK(), ent)
case *configurationv1alpha1.KongTarget:
err = updateTarget(ctx, sdk.GetTargetsSDK(), ent)
case *configurationv1alpha1.KongVault:
err = updateVault(ctx, sdk.GetVaultSDK(), ent)
case *configurationv1alpha1.KongKey:
err = updateKey(ctx, sdk.GetKeysSDK(), ent)
case *configurationv1alpha1.KongKeySet:
err = updateKeySet(ctx, sdk.GetKeySetsSDK(), ent)
case *configurationv1alpha1.KongSNI:
err = updateSNI(ctx, sdk.GetSNIsSDK(), ent)
case *configurationv1alpha1.KongDataPlaneClientCertificate:
err = nil // DataPlaneCertificates are immutable.
// ---------------------------------------------------------------------
// TODO: add other Konnect types
default:
return ctrl.Result{}, fmt.Errorf("unsupported entity type %T", ent)
}
errSDK, isSDKErr := errors.AsType[*sdkkonnecterrs.SDKError](err)
errRelationsFailed, isRelationsFailed := errors.AsType[KonnectEntityCreatedButRelationsFailedError](err)
switch {
case isSDKErr:
statusCode = errSDK.StatusCode
SetKonnectEntityProgrammedConditionFalse(e, kcfgkonnect.KonnectEntitiesFailedToUpdateReason, errSDK)
case isRelationsFailed:
e.SetKonnectID(errRelationsFailed.KonnectID)
SetKonnectEntityProgrammedConditionFalse(e, errRelationsFailed.Reason, err)
case err != nil:
SetKonnectEntityProgrammedConditionFalse(e, kcfgkonnect.KonnectEntitiesFailedToUpdateReason, err)
default:
SetKonnectEntityProgrammedConditionTrue(e)
}
// For mirrorable entities, we need to check if the source type is mirror
// and set the mirrored condition accordingly.
if isMirrorableEntity(e) {
if isMirrorEntity(e) {
if err == nil {
SetKonnectEntityMirroredConditionTrue(e)
} else {
SetKonnectEntityMirroredConditionFalse(e, err)
}
}
}
logOpComplete(ctx, start, UpdateOp, e, err)
if err != nil {
metricRecorder.RecordKonnectEntityOperationFailure(
sdk.GetServerURL(),
metrics.KonnectEntityOperationUpdate,
entityType,
time.Since(start),
statusCode,
)
} else {
metricRecorder.RecordKonnectEntityOperationSuccess(
sdk.GetServerURL(),
metrics.KonnectEntityOperationUpdate,
entityType,
time.Since(start),
)
}
logger := loggerForEntity(ctx, e, UpdateOp)
err = IgnoreUnrecoverableAPIErr(err, logger)
err = IgnoreAlreadyHandledErr(err, logger)
return ctrl.Result{}, err
}
// Adopt adopts an exiting entity in Konnect and take over the management of the entity.
func Adopt[
T constraints.SupportedKonnectEntityType,
TEnt constraints.EntityType[T],
](
ctx context.Context,
sdk sdkops.SDKWrapper,
syncPeriod time.Duration,
cl client.Client,
metricRecorder metrics.Recorder,
e TEnt,
adoptOptions commonv1alpha1.AdoptOptions,
) (ctrl.Result, error) {
var (
err error
entityType = e.GetTypeName()
statusCode int
start = time.Now()
)
switch ent := any(e).(type) {
case *configurationv1alpha1.KongService:
err = adoptService(ctx, sdk.GetServicesSDK(), ent)
case *configurationv1.KongConsumer:
err = adoptConsumer(ctx, sdk.GetConsumersSDK(), sdk.GetConsumerGroupsSDK(), cl, ent, adoptOptions)
case *configurationv1beta1.KongConsumerGroup:
err = adoptConsumerGroup(ctx, sdk.GetConsumerGroupsSDK(), ent, adoptOptions)
case *konnectv1alpha1.KonnectCloudGatewayNetwork:
err = adoptKonnectCloudGatewayNetwork(ctx, sdk.GetCloudGatewaysSDK(), ent, adoptOptions)
case *konnectv1alpha1.KonnectCloudGatewayDataPlaneGroupConfiguration:
err = adoptKonnectDataPlaneGroupConfiguration(ctx, sdk.GetCloudGatewaysSDK(), cl, ent, adoptOptions)
case *konnectv1alpha1.KonnectCloudGatewayTransitGateway:
err = adoptKonnectTransitGateway(ctx, sdk.GetCloudGatewaysSDK(), ent, adoptOptions)
case *configurationv1alpha1.KongRoute:
err = adoptRoute(ctx, sdk.GetRoutesSDK(), ent)
case *configurationv1alpha1.KongUpstream:
err = adoptUpstream(ctx, sdk.GetUpstreamsSDK(), ent)
case *configurationv1alpha1.KongTarget:
err = adoptTarget(ctx, sdk.GetTargetsSDK(), ent)
case *configurationv1alpha1.KongCertificate:
err = adoptCertificate(ctx, cl, sdk.GetCertificatesSDK(), ent)
case *configurationv1alpha1.KongCACertificate:
err = adoptCACertificate(ctx, cl, sdk.GetCACertificatesSDK(), ent)
case *configurationv1alpha1.KongSNI:
err = adoptSNI(ctx, sdk.GetSNIsSDK(), ent)
case *configurationv1alpha1.KongVault:
err = adoptVault(ctx, sdk.GetVaultSDK(), ent)
case *configurationv1alpha1.KongKey:
err = adoptKey(ctx, sdk.GetKeysSDK(), ent)
case *configurationv1alpha1.KongKeySet:
err = adoptKeySet(ctx, sdk.GetKeySetsSDK(), ent)
case *configurationv1alpha1.KongPluginBinding:
err = adoptPluginBinding(ctx, sdk.GetPluginSDK(), cl, ent)
case *configurationv1alpha1.KongCredentialAPIKey:
err = adoptKongCredentialAPIKey(ctx, sdk.GetAPIKeyCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialBasicAuth:
err = adoptKongCredentialBasicAuth(ctx, sdk.GetBasicAuthCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialACL:
err = adoptKongCredentialACL(ctx, sdk.GetACLCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialJWT:
err = adoptKongCredentialJWT(ctx, sdk.GetJWTCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialHMAC:
err = adoptKongCredentialHMAC(ctx, sdk.GetHMACCredentialsSDK(), ent)
case *configurationv1alpha1.KongDataPlaneClientCertificate:
err = adoptKongDataPlaneCertificate(ctx, sdk.GetDataPlaneCertificatesSDK(), ent)
// TODO: implement adoption for other types.
default:
return ctrl.Result{}, fmt.Errorf("unsupported entity type %T", ent)
}
// Set "Adopted" and "Programmed" conditions of the object based on errors returned in the adopt operation.
errFetch, isFetchErr := errors.AsType[KonnectEntityAdoptionFetchError](err)
errUIDConflict, isUIDConflict := errors.AsType[KonnectEntityAdoptionUIDTagConflictError](err)
errNotMatch, isNotMatch := errors.AsType[KonnectEntityAdoptionNotMatchError](err)
errSDK, isSDKErr := errors.AsType[*sdkkonnecterrs.SDKError](err)
switch {
// If the adoption process failed to fetch the entity, we use the "FetchFailed" reason in the "adopted" condition.
case isFetchErr:
if errSDKInner, ok := errors.AsType[*sdkkonnecterrs.SDKError](errFetch.Err); ok {
statusCode = errSDKInner.StatusCode
}
SetKonnectEntityAdoptedConditionFalse(e, konnectv1alpha1.KonnectEntityAdoptedReasonFetchFailed, err)
SetKonnectEntityProgrammedConditionFalse(e, kcfgkonnect.KonnectEntitiesFailedToAdoptReason, err)
case isUIDConflict:
SetKonnectEntityAdoptedConditionFalse(e, konnectv1alpha1.KonnectEntityAdoptedReasonUIDConflict, errUIDConflict)
SetKonnectEntityProgrammedConditionFalse(e, kcfgkonnect.KonnectEntitiesFailedToAdoptReason, errUIDConflict)
case isNotMatch:
SetKonnectEntityAdoptedConditionFalse(e, konnectv1alpha1.KonnectEntityAdoptedReasonNotMatch, errNotMatch)
SetKonnectEntityProgrammedConditionFalse(e, kcfgkonnect.KonnectEntitiesFailedToAdoptReason, errNotMatch)
case isSDKErr:
statusCode = errSDK.StatusCode
SetKonnectEntityAdoptedConditionFalse(e, kcfgkonnect.KonnectEntitiesFailedToAdoptReason, errSDK)
SetKonnectEntityProgrammedConditionFalse(e, kcfgkonnect.KonnectEntitiesFailedToAdoptReason, errSDK)
case err != nil:
SetKonnectEntityAdoptedConditionFalse(e, kcfgkonnect.KonnectEntitiesFailedToAdoptReason, err)
SetKonnectEntityProgrammedConditionFalse(e, kcfgkonnect.KonnectEntitiesFailedToAdoptReason, err)
default:
SetKonnectEntityAdoptedConditionTrue(e)
SetKonnectEntityProgrammedConditionTrue(e)
}
if err != nil {
metricRecorder.RecordKonnectEntityOperationFailure(
sdk.GetServerURL(),
metrics.KonnectEntityOperationAdopt,
entityType,
time.Since(start),
statusCode,
)
} else {
metricRecorder.RecordKonnectEntityOperationSuccess(
sdk.GetServerURL(),
metrics.KonnectEntityOperationAdopt,
entityType,
time.Since(start),
)
}
logOpComplete(ctx, start, AdoptOp, e, err)
return ctrl.Result{}, IgnoreUnrecoverableAPIErr(err, loggerForEntity(ctx, e, AdoptOp))
}
func loggerForEntity[
T constraints.SupportedKonnectEntityType,
TEnt constraints.EntityType[T],
](ctx context.Context, e TEnt, op Op) logr.Logger {
keysAndValues := []any{
"op", op,
}
// Only add the Konnect ID if it exists and it's a create operation.
// Otherwise the Konnect ID is already set in the logger.
if id := e.GetKonnectStatus().GetKonnectID(); id != "" && op == CreateOp {
keysAndValues = append(keysAndValues, "konnect_id", id)
}
return ctrllog.FromContext(ctx).WithValues(keysAndValues...)
}
func logOpComplete[
T constraints.SupportedKonnectEntityType,
TEnt constraints.EntityType[T],
](ctx context.Context, start time.Time, op Op, e TEnt, err error) {
// if the entity is a Mirror, don't log the konnect operation,
// as no operation occurred.
if isMirrorableEntity(e) {
if isMirrorEntity(e) {
return
}
}
if crossnamespace.IsReferenceNotGranted(err) {
// Don't log errors due to missing KongReferenceGrant,
// as they are expected until the user creates the required resource.
return
}
logger := loggerForEntity(ctx, e, op).
WithValues("duration", time.Since(start).String())
if err != nil {
// NOTE: We don't want to print stack trace information here so skip 99 frames
// just in case.
logger.WithCallDepth(99).Error(err, "operation in Konnect API failed")
return
}
logger.Info("operation in Konnect API complete")
}
// wrapErrIfKonnectOpFailed checks the response from the Konnect API and returns a uniform
// error for all Konnect entities if the operation failed.
func wrapErrIfKonnectOpFailed[
T constraints.SupportedKonnectEntityType,
TEnt constraints.EntityType[T],
](err error, op Op, e TEnt) error {
if err != nil {
if errBadRequest, ok := errors.AsType[*sdkkonnecterrs.BadRequestError](err); ok {
errBadRequest.Instance = ""
err = errBadRequest
}
entityTypeName := constraints.EntityTypeName[T]()
if e == nil {
return fmt.Errorf("failed to %s %s: %w",
op, entityTypeName, err,
)
}
return KonnectOperationFailedError{
Op: op,
EntityType: entityTypeName,
EntityKey: client.ObjectKeyFromObject(e).String(),
Err: err,
}
}
return nil
}
func logEntityNotFoundRecreating[
T constraints.SupportedKonnectEntityType,
](ctx context.Context, _ *T, id string) {
ctrllog.FromContext(ctx).
Info(
"entity not found in Konnect, trying to recreate",
"type", constraints.EntityTypeName[T](),
"id", id,
)
}
// sliceToEntityWithIDPtrSlice converts a slice of entities to a slice of entityWithIDPtr.
func sliceToEntityWithIDPtrSlice[
T any,
TPtr interface {
*T
GetID() *string
},
](
slice []T,
) []TPtr {
result := make([]TPtr, 0, len(slice))
for _, item := range slice {
result = append(result, TPtr(&item))
}
return result
}
// sliceToEntityWithIDSlice converts a slice of entities to a slice of entityWithID.
func sliceToEntityWithIDSlice[
T any,
TPtr interface {
*T
GetID() string
},
](
slice []T,
) []TPtr {
result := make([]TPtr, 0, len(slice))
for _, item := range slice {
result = append(result, TPtr(&item))
}
return result
}
// extractedEntityID represents the ID of an entity.
// The type is defined to satisfy the interface in the parameter of getMatchingEntryFromListResponseData.
// Some types of responses do not provide a GetID in sdk-konnect-go
// so we need to extract the ID and return this type for getMatchingEntryFromListResponseData.
type extractedEntityID string
// GetID returns the extracted ID. Implements the interface in the parameter of getMatchingEntryFromListResponseData.
func (e extractedEntityID) GetID() string {
return string(e)
}
// getMatchingEntryFromListResponseData returns the ID of the first entry in the list response data.
// It returns an error if no entry with a non-empty ID was found.
// It is used in conjunction with the list operation to get the ID of the entity that matches the UID
// hence no filtering is done here because it is assumed that the provided list response data is already filtered.
func getMatchingEntryFromListResponseData[
T interface {
GetID() IDType
},
IDType string | *string,
](
data []T,
entity entity,
) (T, string, error) {
var (
id string
ret T
)
for _, entry := range data {
entryID := entry.GetID()
switch entryID := any(entryID).(type) {
case string:
if entryID != "" {
id = entryID
ret = entry
break
}
case *string:
if entryID != nil && *entryID != "" {
id = *entryID
break
}
}
}
if id == "" {
return ret, "", EntityWithMatchingUIDNotFoundError{
Entity: entity,
}
}
return ret, id, nil
}
// ClearInstanceFromError clears the instance field from the error.
// This is needed because the instance field contains the trace ID which changes
// with each request and makes the reconciliation loop requeue the resource
// instead of performing the backoff.
func ClearInstanceFromError(err error) error {
if errBadRequest, ok := errors.AsType[*sdkkonnecterrs.BadRequestError](err); ok {
errBadRequest.Instance = ""
return errBadRequest
}
if errConflict, ok := errors.AsType[*sdkkonnecterrs.ConflictError](err); ok {
errConflict.Instance = ""
return errConflict
}
if errNotFound, ok := errors.AsType[*sdkkonnecterrs.NotFoundError](err); ok {
errNotFound.Instance = ""
return errNotFound
}
return err
}
// isMirrorableEntity checks if the entity is mirrorable.
// This is used to determine if the entity can be mirrored to Konnect.
func isMirrorableEntity[
T constraints.SupportedKonnectEntityType,
TEnt constraints.EntityType[T],
](ent TEnt) bool {
switch any(ent).(type) {
case *konnectv1alpha2.KonnectGatewayControlPlane:
return true
default:
return false
}
}
// isMirrorEntity checks if the entity is a mirror entity.
// This is used to determine if the entity is a mirror of a Konnect entity.
func isMirrorEntity[
T constraints.SupportedKonnectEntityType,
TEnt constraints.EntityType[T],
](ent TEnt) bool {
switch cp := any(ent).(type) {
case *konnectv1alpha2.KonnectGatewayControlPlane:
return cp.Spec.Source != nil && *cp.Spec.Source == commonv1alpha1.EntitySourceMirror
default:
return false
}
}
// findUIDTag finds tags annotating the k8s UID.
func findUIDTag(tags []string) (string, bool) {
return lo.Find(tags, func(s string) bool {
return strings.HasPrefix(s, "k8s-uid:")
})
}
// extractUIDFromTag extracts the k8s UID from the tag.
func extractUIDFromTag(tag string) string {
return strings.TrimPrefix(tag, "k8s-uid:")
}
// equalWithDefault compares two values from the pointers and falls back to
// the given default value if the pointer is nil or the value is the zero value for the given type.
func equalWithDefault[T comparable](
a *T, b *T, defaultValue T,
) bool {
var aVal, bVal T
if a == nil || lo.IsEmpty(*a) {
aVal = defaultValue
} else {
aVal = *a
}
if b == nil || lo.IsEmpty(*b) {
bVal = defaultValue
} else {
bVal = *b
}
return aVal == bVal
}