-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathutils.go
More file actions
1886 lines (1624 loc) · 65.5 KB
/
utils.go
File metadata and controls
1886 lines (1624 loc) · 65.5 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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package utils
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
aws_sdk "github.com/aws/aws-sdk-go/aws"
aws_config "github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/route53"
"github.com/go-logr/logr"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
certmanv1alpha1 "github.com/openshift/certman-operator/api/v1alpha1"
awsclient "github.com/openshift/certman-operator/pkg/clients/aws"
hivev1 "github.com/openshift/hive/apis/hive/v1"
corev1 "k8s.io/api/core/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
syaml "k8s.io/apimachinery/pkg/runtime/serializer/yaml"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"sigs.k8s.io/controller-runtime/pkg/client"
logs "sigs.k8s.io/controller-runtime/pkg/log"
)
type CertConfig struct {
ClusterName string
BaseDomain string
TestNamespace string
OCMClusterID string
}
// ExtractClusterInfoFromInfrastructure extracts cluster name and base domain from the infrastructure cluster resource
// This replicates: oc get infrastructure cluster -o jsonpath='{.status.apiServerURL}' | sed 's|https://api\.\(.*\):6443|\1|'
// Returns clusterName and baseDomain parsed from the apiServerURL
// Example: if apiServerURL is "https://api.sai-test.fvj1.s1.devshift.org:6443"
// - fullDomain = "sai-test.fvj1.s1.devshift.org"
// - clusterName = "sai-test"
// - baseDomain = "fvj1.s1.devshift.org"
func ExtractClusterInfoFromInfrastructure(ctx context.Context, dynamicClient dynamic.Interface) (clusterName, baseDomain string, err error) {
// Infrastructure is a cluster-scoped resource in config.openshift.io/v1
infrastructureGVR := schema.GroupVersionResource{
Group: "config.openshift.io",
Version: "v1",
Resource: "infrastructures",
}
// Get the infrastructure cluster resource
infra, err := dynamicClient.Resource(infrastructureGVR).Get(ctx, "cluster", metav1.GetOptions{})
if err != nil {
return "", "", fmt.Errorf("failed to get infrastructure cluster: %w", err)
}
// Extract apiServerURL from status
apiServerURL, found, err := unstructured.NestedString(infra.Object, "status", "apiServerURL")
if !found || err != nil {
return "", "", fmt.Errorf("failed to get apiServerURL from infrastructure status: %w", err)
}
// Parse apiServerURL: "https://api.sai-test.fvj1.s1.devshift.org:6443"
// Extract: "sai-test.fvj1.s1.devshift.org"
// Pattern: https://api.{clusterName}.{baseDomain}:6443
// We need to extract the part between "https://api." and ":6443"
if !strings.HasPrefix(apiServerURL, "https://api.") {
return "", "", fmt.Errorf("unexpected apiServerURL format: %s", apiServerURL)
}
// Remove "https://api." prefix
fullDomain := strings.TrimPrefix(apiServerURL, "https://api.")
// Remove ":6443" suffix if present
fullDomain = strings.TrimSuffix(fullDomain, ":6443")
// Split by first dot to get clusterName and baseDomain
// fullDomain = "sai-test.fvj1.s1.devshift.org"
// parts[0] = "sai-test" (clusterName)
// parts[1:] = ["fvj1", "s1", "devshift", "org"] -> join with "." = "fvj1.s1.devshift.org" (baseDomain)
parts := strings.SplitN(fullDomain, ".", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("unexpected domain format: %s (expected clusterName.baseDomain)", fullDomain)
}
clusterName = parts[0]
baseDomain = parts[1]
return clusterName, baseDomain, nil
}
func LoadTestConfig() *CertConfig {
clusterName := GetEnvOrDefault("CLUSTER_NAME", "test-cluster")
baseDomain := GetEnvOrDefault("BASE_DOMAIN", "example.com")
ocmClusterID := GetEnvOrDefault("OCM_CLUSTER_ID", "test-cluster-id")
return NewCertConfig(clusterName, ocmClusterID, baseDomain)
}
// LoadTestConfigFromInfrastructure loads cluster configuration by extracting it from the infrastructure cluster resource
// This is the preferred method as it uses the actual cluster information
func LoadTestConfigFromInfrastructure(ctx context.Context, dynamicClient dynamic.Interface) (*CertConfig, error) {
clusterName, baseDomain, err := ExtractClusterInfoFromInfrastructure(ctx, dynamicClient)
if err != nil {
return nil, fmt.Errorf("failed to extract cluster info from infrastructure: %w", err)
}
ocmClusterID := GetEnvOrDefault("OCM_CLUSTER_ID", "test-cluster-id")
return NewCertConfig(clusterName, ocmClusterID, baseDomain), nil
}
func NewCertConfig(clusterName string, ocmClusterID string, baseDomain string) *CertConfig {
return &CertConfig{
ClusterName: clusterName,
BaseDomain: baseDomain,
TestNamespace: "certman-operator",
OCMClusterID: ocmClusterID,
}
}
func CreateAdminKubeconfigSecret(ctx context.Context, clientset *kubernetes.Clientset, config *CertConfig, secretName string) error {
dummyKubeconfig := fmt.Sprintf(`apiVersion: v1
kind: Config
clusters:
- cluster:
certificate-authority-data: <REDACTED-TEST-CA-CERT>
server: https://api.%s.%s:6443
name: %s
contexts:
- context:
cluster: %s
user: system:admin
name: %s-admin
current-context: %s-admin
users:
- name: system:admin
user:
client-certificate-data: <REDACTED-TEST-CLIENT-CERT>
client-key-data: <REDACTED-TEST-CLIENT-KEY>`,
config.ClusterName, config.BaseDomain, config.ClusterName,
config.ClusterName, config.ClusterName, config.ClusterName)
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
Namespace: config.TestNamespace,
Labels: map[string]string{
"test-resource": "true",
"cluster-name": config.ClusterName,
},
},
Type: corev1.SecretTypeOpaque,
Data: map[string][]byte{
"kubeconfig": []byte(dummyKubeconfig),
},
}
_, err := clientset.CoreV1().Secrets(config.TestNamespace).Create(ctx, secret, metav1.CreateOptions{})
if err != nil && !strings.Contains(err.Error(), "already exists") {
return fmt.Errorf("failed to create admin kubeconfig secret: %w", err)
}
ginkgo.GinkgoLogr.Info("Created admin kubeconfig secret", "secretName", secretName)
return nil
}
func BuildCompleteClusterDeployment(config *CertConfig, clusterDeploymentName, adminKubeconfigSecretName, ocmClusterID string) *unstructured.Unstructured {
randomBytes := make([]byte, 3)
if _, err := rand.Read(randomBytes); err != nil {
// Fallback to a deterministic value if random generation fails (should never happen)
randomBytes = []byte{0x12, 0x34, 0x56}
}
infraID := fmt.Sprintf("%s-%x", config.ClusterName, randomBytes)[:len(config.ClusterName)+6] // Take clusterName + "-" + 5 hex chars
domainName := config.ClusterName
return &unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": "hive.openshift.io/v1",
"kind": "ClusterDeployment",
"metadata": map[string]interface{}{
"name": clusterDeploymentName,
"namespace": config.TestNamespace,
"labels": map[string]interface{}{
"api.openshift.com/managed": "true",
"api.openshift.com/id": ocmClusterID,
"api.openshift.com/name": config.ClusterName,
},
"annotations": map[string]interface{}{
"hive.openshift.io/protected-delete": "true",
"hive.openshift.io/syncset-pause": "true",
},
},
"spec": map[string]interface{}{
"installed": true,
"baseDomain": config.BaseDomain,
"clusterName": config.ClusterName,
"clusterMetadata": map[string]interface{}{
"clusterID": ocmClusterID,
"infraID": infraID,
"adminKubeconfigSecretRef": map[string]interface{}{
"name": adminKubeconfigSecretName,
},
},
"certificateBundles": []interface{}{
map[string]interface{}{
"generate": true,
"name": "primary-cert-bundle",
"certificateSecretRef": map[string]interface{}{
"name": "primary-cert-bundle-secret",
},
},
},
"controlPlaneConfig": map[string]interface{}{
"apiURLOverride": fmt.Sprintf("api.%s.%s:6443", domainName, config.BaseDomain),
"servingCertificates": map[string]interface{}{
"default": "primary-cert-bundle",
"additional": []interface{}{
map[string]interface{}{
"domain": fmt.Sprintf("api.%s.%s", domainName, config.BaseDomain),
"name": "primary-cert-bundle",
},
},
},
},
"ingress": []interface{}{
map[string]interface{}{
"domain": fmt.Sprintf("apps.%s.%s", domainName, config.BaseDomain),
"name": "default",
"servingCertificate": "primary-cert-bundle",
},
},
"platform": map[string]interface{}{
"aws": map[string]interface{}{
"region": "us-east-1",
"credentialsSecretRef": map[string]interface{}{
"name": "aws",
},
},
},
},
"status": map[string]interface{}{
"apiURL": fmt.Sprintf("https://api.%s.%s:6443", domainName, config.BaseDomain),
"webConsoleURL": fmt.Sprintf("https://console-openshift-console.apps.%s.%s", domainName, config.BaseDomain),
},
},
}
}
// Helper functions to extract values from ClusterDeployment for logging/verification
func GetClusterNameFromCD(cd *unstructured.Unstructured) string {
clusterName, _, _ := unstructured.NestedString(cd.Object, "spec", "clusterName")
return clusterName
}
func GetBaseDomainFromCD(cd *unstructured.Unstructured) string {
baseDomain, _, _ := unstructured.NestedString(cd.Object, "spec", "baseDomain")
return baseDomain
}
func GetAPIURLOverrideFromCD(cd *unstructured.Unstructured) string {
apiURLOverride, _, _ := unstructured.NestedString(cd.Object, "spec", "controlPlaneConfig", "apiURLOverride")
return apiURLOverride
}
func GetStatusAPIURLFromCD(cd *unstructured.Unstructured) string {
apiURL, _, _ := unstructured.NestedString(cd.Object, "status", "apiURL")
return apiURL
}
func GetInfraIDFromCD(cd *unstructured.Unstructured) string {
infraID, _, _ := unstructured.NestedString(cd.Object, "spec", "clusterMetadata", "infraID")
return infraID
}
// VerifyClusterDeploymentCriteria checks all reconciliation criteria from requirements
func VerifyClusterDeploymentCriteria(ctx context.Context, dynamicClient dynamic.Interface, gvr schema.GroupVersionResource, namespace, name, ocmClusterID string) bool {
cd, err := dynamicClient.Resource(gvr).Namespace(namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
ginkgo.GinkgoLogr.Error(err, "Failed to get ClusterDeployment")
return false
}
// Check required label: "api.openshift.com/managed"
labels := cd.GetLabels()
gomega.Expect(labels).ToNot(gomega.BeNil(), "Labels should not be nil")
gomega.Expect(labels["api.openshift.com/managed"]).To(gomega.Equal("true"), "Missing required managed label")
// Check ClusterDeployment.Spec.Installed = True
installed, found, _ := unstructured.NestedBool(cd.Object, "spec", "installed")
gomega.Expect(found).To(gomega.BeTrue(), "Installed field not found")
gomega.Expect(installed).To(gomega.BeTrue(), "Installed field not true")
// Check NOT has annotation "hive.openshift.io/relocate" = "outgoing"
annotations := cd.GetAnnotations()
if annotations != nil {
gomega.Expect(annotations["hive.openshift.io/relocate"]).ToNot(gomega.Equal("outgoing"),
"Has relocate annotation set to outgoing - this prevents reconciliation")
}
// Verify OCM cluster ID matches
gomega.Expect(labels["api.openshift.com/id"]).To(gomega.Equal(ocmClusterID),
"OCM cluster ID mismatch", "expected", ocmClusterID, "actual", labels["api.openshift.com/id"])
// Verify certificateBundles section exists
certificateBundles, found, _ := unstructured.NestedSlice(cd.Object, "spec", "certificateBundles")
gomega.Expect(found).To(gomega.BeTrue(), "certificateBundles section not found")
gomega.Expect(certificateBundles).ToNot(gomega.BeEmpty(), "certificateBundles section is empty")
ginkgo.GinkgoLogr.Info("All ClusterDeployment reconciliation criteria met")
return true
}
// EnsureTestNamespace ensures the test namespace exists
func EnsureTestNamespace(ctx context.Context, clientset *kubernetes.Clientset, namespace string) error {
_, err := clientset.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
// Create namespace
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
Labels: map[string]string{
"test-namespace": "true",
},
},
}
_, err = clientset.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{})
if err != nil {
return fmt.Errorf("failed to create namespace %s: %w", namespace, err)
}
ginkgo.GinkgoLogr.Info("Created test namespace", "namespace", namespace)
} else {
return fmt.Errorf("failed to get namespace %s: %w", namespace, err)
}
}
return nil
}
// CleanupClusterDeployment removes ClusterDeployment if it exists
func CleanupClusterDeployment(ctx context.Context, dynamicClient dynamic.Interface, gvr schema.GroupVersionResource, namespace, name string) {
// First, try to get the ClusterDeployment to check if it exists
cd, err := dynamicClient.Resource(gvr).Namespace(namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
ginkgo.GinkgoLogr.Info("ClusterDeployment does not exist, nothing to cleanup", "name", name)
return
}
ginkgo.GinkgoLogr.Error(err, "Failed to get ClusterDeployment", "name", name)
return
}
// Check if it's already marked for deletion
deletionTimestamp, found, _ := unstructured.NestedString(cd.Object, "metadata", "deletionTimestamp")
if found && deletionTimestamp != "" {
ginkgo.GinkgoLogr.Info("ClusterDeployment is already marked for deletion, checking finalizers", "name", name)
// If already marked for deletion, check finalizers immediately
finalizers := cd.GetFinalizers()
if len(finalizers) > 0 {
ginkgo.GinkgoLogr.Info("Removing finalizers from ClusterDeployment that is already marked for deletion",
"name", name, "finalizers", finalizers)
cd.SetFinalizers([]string{})
_, err := dynamicClient.Resource(gvr).Namespace(namespace).Update(ctx, cd, metav1.UpdateOptions{})
if err != nil {
ginkgo.GinkgoLogr.Error(err, "Failed to remove finalizers from ClusterDeployment", "name", name)
} else {
ginkgo.GinkgoLogr.Info("Successfully removed finalizers from ClusterDeployment", "name", name)
}
}
} else {
// Delete the ClusterDeployment
err = dynamicClient.Resource(gvr).Namespace(namespace).Delete(ctx, name, metav1.DeleteOptions{})
if err != nil && !apierrors.IsNotFound(err) {
ginkgo.GinkgoLogr.Error(err, "Failed to delete ClusterDeployment", "name", name)
return
}
ginkgo.GinkgoLogr.Info("Initiated ClusterDeployment deletion", "name", name)
// Give a short time for deletion timestamp to be set, then check finalizers
time.Sleep(5 * time.Second)
// Re-fetch to check deletion status and finalizers
cd, err = dynamicClient.Resource(gvr).Namespace(namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
ginkgo.GinkgoLogr.Info("ClusterDeployment deleted successfully", "name", name)
return
}
ginkgo.GinkgoLogr.Error(err, "Failed to get ClusterDeployment after deletion", "name", name)
return
}
// Check for finalizers and remove them proactively
finalizers := cd.GetFinalizers()
if len(finalizers) > 0 {
ginkgo.GinkgoLogr.Info("Removing finalizers from ClusterDeployment to allow deletion",
"name", name, "finalizers", finalizers)
cd.SetFinalizers([]string{})
_, err := dynamicClient.Resource(gvr).Namespace(namespace).Update(ctx, cd, metav1.UpdateOptions{})
if err != nil {
ginkgo.GinkgoLogr.Error(err, "Failed to remove finalizers from ClusterDeployment", "name", name)
} else {
ginkgo.GinkgoLogr.Info("Successfully removed finalizers from ClusterDeployment", "name", name)
}
}
}
// Wait for ClusterDeployment to be fully deleted (with a reasonable timeout)
// Use a loop instead of gomega.Eventually to avoid test failure on timeout
maxWait := 60 * time.Second
checkInterval := 2 * time.Second
startTime := time.Now()
for time.Since(startTime) < maxWait {
_, err := dynamicClient.Resource(gvr).Namespace(namespace).Get(ctx, name, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
ginkgo.GinkgoLogr.Info("ClusterDeployment deleted successfully", "name", name)
return
}
time.Sleep(checkInterval)
}
// If still not deleted, try one more time to remove finalizers and force delete
ginkgo.GinkgoLogr.Info("ClusterDeployment still exists after timeout, attempting final cleanup", "name", name)
cd, err = dynamicClient.Resource(gvr).Namespace(namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
ginkgo.GinkgoLogr.Info("ClusterDeployment was deleted during final cleanup check", "name", name)
return
}
ginkgo.GinkgoLogr.Error(err, "Failed to get ClusterDeployment for final cleanup", "name", name)
return
}
finalizers := cd.GetFinalizers()
if len(finalizers) > 0 {
ginkgo.GinkgoLogr.Info("Force removing finalizers from ClusterDeployment",
"name", name, "finalizers", finalizers)
cd.SetFinalizers([]string{})
_, err := dynamicClient.Resource(gvr).Namespace(namespace).Update(ctx, cd, metav1.UpdateOptions{})
if err != nil {
ginkgo.GinkgoLogr.Error(err, "Failed to force remove finalizers from ClusterDeployment", "name", name)
} else {
ginkgo.GinkgoLogr.Info("Successfully force removed finalizers from ClusterDeployment", "name", name)
// Give it a moment to delete
time.Sleep(5 * time.Second)
_, err := dynamicClient.Resource(gvr).Namespace(namespace).Get(ctx, name, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
ginkgo.GinkgoLogr.Info("ClusterDeployment deleted after force removing finalizers", "name", name)
return
}
}
}
ginkgo.GinkgoLogr.Info("ClusterDeployment cleanup completed (may still exist if operator is processing)", "name", name)
}
// FindCertificateRequestForClusterDeployment finds the CertificateRequest owned by a ClusterDeployment
func FindCertificateRequestForClusterDeployment(ctx context.Context, dynamicClient dynamic.Interface, crGVR schema.GroupVersionResource, namespace, clusterDeploymentName string) (*unstructured.Unstructured, error) {
crList, err := dynamicClient.Resource(crGVR).Namespace(namespace).List(ctx, metav1.ListOptions{})
if err != nil {
return nil, fmt.Errorf("failed to list CertificateRequests: %w", err)
}
for i := range crList.Items {
cr := &crList.Items[i]
ownerRefs, found, _ := unstructured.NestedSlice(cr.Object, "metadata", "ownerReferences")
if found && len(ownerRefs) > 0 {
for _, ownerRef := range ownerRefs {
ownerRefMap, ok := ownerRef.(map[string]interface{})
if ok {
ownerKind, _ := ownerRefMap["kind"].(string)
ownerName, _ := ownerRefMap["name"].(string)
if ownerKind == "ClusterDeployment" && ownerName == clusterDeploymentName {
return cr, nil
}
}
}
}
}
return nil, fmt.Errorf("no CertificateRequest found for ClusterDeployment %s", clusterDeploymentName)
}
// GetCertificateSecretNameFromCR extracts the certificate secret name from a CertificateRequest
func GetCertificateSecretNameFromCR(cr *unstructured.Unstructured) (string, error) {
secretRef, found, _ := unstructured.NestedMap(cr.Object, "spec", "certificateSecret")
if !found {
return "", fmt.Errorf("certificateSecret not found in CertificateRequest spec")
}
name, ok := secretRef["name"].(string)
if !ok || name == "" {
return "", fmt.Errorf("certificateSecret name is empty or invalid")
}
return name, nil
}
// ForceDeleteCertificateRequests deletes all CertificateRequests in a namespace,
// removing finalizers if necessary to ensure deletion completes
func ForceDeleteCertificateRequests(ctx context.Context, dynamicClient dynamic.Interface, namespace string) {
certificateRequestGVR := schema.GroupVersionResource{
Group: "certman.managed.openshift.io", Version: "v1alpha1", Resource: "certificaterequests",
}
crList, err := dynamicClient.Resource(certificateRequestGVR).Namespace(namespace).List(ctx, metav1.ListOptions{})
if err != nil {
ginkgo.GinkgoLogr.Error(err, "Failed to list CertificateRequests for cleanup")
return
}
for _, cr := range crList.Items {
crName := cr.GetName()
// Check if CR has finalizers that might block deletion
finalizers := cr.GetFinalizers()
if len(finalizers) > 0 {
ginkgo.GinkgoLogr.Info("Removing finalizers from CertificateRequest to force deletion",
"name", crName, "finalizers", finalizers)
// Remove all finalizers
cr.SetFinalizers([]string{})
_, err := dynamicClient.Resource(certificateRequestGVR).Namespace(namespace).Update(ctx, &cr, metav1.UpdateOptions{})
if err != nil {
ginkgo.GinkgoLogr.Error(err, "Failed to remove finalizers from CertificateRequest", "name", crName)
// Continue trying to delete anyway
} else {
ginkgo.GinkgoLogr.Info("Successfully removed finalizers from CertificateRequest", "name", crName)
}
}
// Delete the CertificateRequest
err := dynamicClient.Resource(certificateRequestGVR).Namespace(namespace).Delete(ctx, crName, metav1.DeleteOptions{})
if err != nil && !apierrors.IsNotFound(err) {
ginkgo.GinkgoLogr.Error(err, "Failed to delete CertificateRequest", "name", crName)
} else if err == nil {
ginkgo.GinkgoLogr.Info("Deleted CertificateRequest", "name", crName)
}
}
// Verify all CRs are deleted
time.Sleep(2 * time.Second)
remaining, err := dynamicClient.Resource(certificateRequestGVR).Namespace(namespace).List(ctx, metav1.ListOptions{})
if err == nil && len(remaining.Items) > 0 {
ginkgo.GinkgoLogr.Info("Warning: Some CertificateRequests still exist after cleanup", "count", len(remaining.Items))
} else if err == nil {
ginkgo.GinkgoLogr.Info("All CertificateRequests successfully deleted")
}
}
func VerifyMetrics(ctx context.Context, clientset *kubernetes.Clientset, namespace string) (certRequestsCount, issuedCertCount int, success bool) {
// Find the certman-operator pod
pods, err := clientset.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{
LabelSelector: "name=certman-operator",
})
if err != nil {
ginkgo.GinkgoLogr.Error(err, "Failed to list certman-operator pods")
return 0, 0, false
}
if len(pods.Items) == 0 {
ginkgo.GinkgoLogr.Info("No certman-operator pods found")
return 0, 0, false
}
// Use the first running pod
var targetPod *corev1.Pod
for i := range pods.Items {
if pods.Items[i].Status.Phase == corev1.PodRunning {
targetPod = &pods.Items[i]
break
}
}
if targetPod == nil {
ginkgo.GinkgoLogr.Info("No running certman-operator pod found")
return 0, 0, false
}
// Find the metrics port (default is 8080)
metricsPort := int32(8080)
for _, container := range targetPod.Spec.Containers {
for _, port := range container.Ports {
if port.Name == "metrics" || port.ContainerPort == 8080 {
metricsPort = port.ContainerPort
break
}
}
if metricsPort != 8080 {
break
}
}
ginkgo.GinkgoLogr.Info("Querying metrics via Kubernetes API proxy",
"pod", targetPod.Name,
"port", metricsPort,
"namespace", namespace)
// Query metrics endpoint via API proxy using REST client
restClient := clientset.CoreV1().RESTClient()
// Use Raw() to get the raw response body as bytes
result := restClient.Get().
Namespace(namespace).
Resource("pods").
Name(fmt.Sprintf("%s:%d", targetPod.Name, metricsPort)).
SubResource("proxy").
Suffix("metrics").
Do(ctx)
if result.Error() != nil {
ginkgo.GinkgoLogr.Error(result.Error(), "Failed to query metrics endpoint via API proxy")
return 0, 0, false
}
metricsData, err := result.Raw()
if err != nil {
ginkgo.GinkgoLogr.Error(err, "Failed to read metrics response")
return 0, 0, false
}
metricsText := string(metricsData)
ginkgo.GinkgoLogr.Info("Metrics response received", "size", len(metricsText))
// Parse metrics to find certificate_requests_count
// Note: certRequestsCount and issuedCertCount are already declared in function signature
lines := strings.Split(metricsText, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
// Skip comments and empty lines
if strings.HasPrefix(line, "#") || line == "" {
continue
}
if strings.HasPrefix(line, "certman_operator_certificate_requests_count") {
lastSpace := strings.LastIndex(line, " ")
if lastSpace > 0 {
valueStr := strings.TrimSpace(line[lastSpace:])
if count, err := fmt.Sscanf(valueStr, "%d", &certRequestsCount); err == nil && count == 1 {
ginkgo.GinkgoLogr.Info("Found certificate_requests_count", "value", certRequestsCount, "line", line)
}
}
}
// Look for certman_operator_issued_certificates_count
if strings.Contains(line, "certman_operator_issued_certificates_count") && !strings.HasPrefix(line, "#") {
lastSpace := strings.LastIndex(line, " ")
if lastSpace > 0 {
valueStr := strings.TrimSpace(line[lastSpace:])
if count, err := fmt.Sscanf(valueStr, "%d", &issuedCertCount); err == nil && count == 1 {
ginkgo.GinkgoLogr.Info("Found issued_certificates_count", "value", issuedCertCount, "line", line)
}
}
}
}
ginkgo.GinkgoLogr.Info("Metrics verification results",
"certificate_requests_count", certRequestsCount,
"issued_certificates_count", issuedCertCount)
// Verify that we have at least 1 certificate request
if certRequestsCount > 0 {
ginkgo.GinkgoLogr.Info("Metrics validation successful",
"certificate_requests_count", certRequestsCount,
"issued_certificates_count", issuedCertCount)
return certRequestsCount, issuedCertCount, true
}
ginkgo.GinkgoLogr.Info("Metrics validation: certificate_requests_count is 0 or not found",
"certificate_requests_count", certRequestsCount,
"issued_certificates_count", issuedCertCount)
return certRequestsCount, issuedCertCount, false
}
// CleanupAllTestResources cleans up all resources created during testing
func CleanupAllTestResources(ctx context.Context, clientset *kubernetes.Clientset, dynamicClient dynamic.Interface, config *CertConfig, clusterDeploymentName, adminKubeconfigSecretName, ocmClusterID string) {
ginkgo.GinkgoLogr.Info("Cleaning up CertificateRequests before ClusterDeployment")
ForceDeleteCertificateRequests(ctx, dynamicClient, config.TestNamespace)
// Give a moment for CertificateRequests to be deleted
time.Sleep(5 * time.Second)
// Cleanup ClusterDeployment (after CertificateRequests are cleaned up)
clusterDeploymentGVR := schema.GroupVersionResource{
Group: "hive.openshift.io", Version: "v1", Resource: "clusterdeployments",
}
CleanupClusterDeployment(ctx, dynamicClient, clusterDeploymentGVR, config.TestNamespace, clusterDeploymentName)
// Cleanup secrets
secrets := []string{
adminKubeconfigSecretName,
}
for _, secretName := range secrets {
err := clientset.CoreV1().Secrets(config.TestNamespace).Delete(ctx, secretName, metav1.DeleteOptions{})
if err != nil && !apierrors.IsNotFound(err) {
ginkgo.GinkgoLogr.Error(err, "Failed to cleanup secret", "secretName", secretName)
} else if err == nil {
ginkgo.GinkgoLogr.Info("Cleaned up secret", "secretName", secretName)
}
}
ginkgo.GinkgoLogr.Info("Test resource cleanup completed",
"clusterName", config.ClusterName,
"namespace", config.TestNamespace,
"ocmClusterID", ocmClusterID)
}
var logger = logs.Log
func DownloadAndApplyCRD(ctx context.Context, apiExtClient apiextensionsclient.Interface, crdURL, crdName string) error {
log.Printf("CRD '%s' not found. Downloading and applying from: %s", crdName, crdURL)
// Validate URL
parsedURL, err := url.ParseRequestURI(crdURL)
if err != nil {
return fmt.Errorf("invalid CRD URL: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsedURL.String(), nil)
if err != nil {
return fmt.Errorf("failed to create HTTP request: %w", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to download CRD from %s: %w", crdURL, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download CRD. HTTP status %d", resp.StatusCode)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read CRD body: %w", err)
}
decoder := syaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme)
crd := &apiextensionsv1.CustomResourceDefinition{}
_, _, err = decoder.Decode(data, nil, crd)
if err != nil {
return fmt.Errorf("failed to decode CRD YAML: %w", err)
}
if _, err := apiExtClient.ApiextensionsV1().CustomResourceDefinitions().Create(ctx, crd, metav1.CreateOptions{}); err != nil {
return fmt.Errorf("failed to create CRD '%s': %w", crdName, err)
}
log.Printf("CRD '%s' applied.", crdName)
return nil
}
func ApplyManifestsFromURLs(ctx context.Context, cfg *rest.Config, manifestURLs []string) error {
// Create discovery client and dynamic client from REST config
dc, err := discovery.NewDiscoveryClientForConfig(cfg)
if err != nil {
return fmt.Errorf("failed to create discovery client: %w", err)
}
gr, err := restmapper.GetAPIGroupResources(dc)
if err != nil {
return fmt.Errorf("failed to get API group resources: %w", err)
}
mapper := restmapper.NewDiscoveryRESTMapper(gr)
dynamicClient, err := dynamic.NewForConfig(cfg)
if err != nil {
return fmt.Errorf("failed to create dynamic client: %w", err)
}
for _, manifestURL := range manifestURLs {
log.Printf("Downloading manifest from: %s", manifestURL)
parsedURL, err := url.ParseRequestURI(manifestURL)
if err != nil {
return fmt.Errorf("invalid manifest URL: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsedURL.String(), nil)
if err != nil {
return fmt.Errorf("failed to create HTTP request: %w", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to download manifest from %s: %w", manifestURL, err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read manifest from %s: %w", manifestURL, err)
}
decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096)
for {
var rawObj map[string]interface{}
if err := decoder.Decode(&rawObj); err != nil {
if err == io.EOF {
break
}
return fmt.Errorf("failed to decode YAML from %s: %w", manifestURL, err)
}
if len(rawObj) == 0 {
continue
}
obj := &unstructured.Unstructured{Object: rawObj}
gvk := obj.GroupVersionKind()
mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
return fmt.Errorf("failed to get REST mapping for GVK %v: %w", gvk, err)
}
var dri dynamic.ResourceInterface
if mapping.Scope.Name() == meta.RESTScopeNameNamespace {
ns := obj.GetNamespace()
if ns == "" {
ns = "certman-operator"
obj.SetNamespace(ns)
}
dri = dynamicClient.Resource(mapping.Resource).Namespace(ns)
} else {
dri = dynamicClient.Resource(mapping.Resource)
}
_, err = dri.Create(ctx, obj, metav1.CreateOptions{})
if apierrors.IsAlreadyExists(err) {
log.Printf("Resource %s/%s already exists, skipping.", obj.GetNamespace(), obj.GetName())
continue
}
if err != nil {
return fmt.Errorf("failed to create resource %s/%s: %w", obj.GetNamespace(), obj.GetName(), err)
}
log.Printf("Successfully applied resource: %s/%s", obj.GetNamespace(), obj.GetName())
}
}
return nil
}
func SetupHiveCRDs(ctx context.Context, apiExtClient apiextensionsclient.Interface) error {
const crdURL = "https://raw.githubusercontent.com/openshift/hive/master/config/crds/hive.openshift.io_clusterdeployments.yaml"
const crdName = "clusterdeployments.hive.openshift.io"
_, err := apiExtClient.ApiextensionsV1().CustomResourceDefinitions().Get(ctx, crdName, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
return DownloadAndApplyCRD(ctx, apiExtClient, crdURL, crdName)
} else if err != nil {
return fmt.Errorf("error getting CRD '%s': %w", crdName, err)
}
log.Printf("CRD '%s' already exists.", crdName)
return nil
}
// SetupCertman ensures namespace, CRD, ConfigMap and applies operator manifests
func SetupCertman(ctx context.Context, kubeClient kubernetes.Interface, apiExtClient apiextensionsclient.Interface, cfg *rest.Config) error {
const (
namespace = "certman-operator"
configMapName = "certman-operator"
crdURL = "https://raw.githubusercontent.com/openshift/certman-operator/master/deploy/crds/certman.managed.openshift.io_certificaterequests.yaml"
crdName = "certificaterequests.certman.managed.openshift.io"
)
// Check namespace status and fix if terminating
ns, err := kubeClient.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{})
if err == nil && ns.Status.Phase == corev1.NamespaceTerminating {
log.Printf("Namespace '%s' is stuck in terminating state. Removing finalizers to force deletion...", namespace)
// Remove finalizers from the namespace to allow deletion
if len(ns.Spec.Finalizers) > 0 {
log.Printf("Removing %d finalizers from namespace '%s'", len(ns.Spec.Finalizers), namespace)
ns.Spec.Finalizers = []corev1.FinalizerName{}
_, updateErr := kubeClient.CoreV1().Namespaces().Finalize(ctx, ns, metav1.UpdateOptions{})
if updateErr != nil {
log.Printf("Warning: failed to remove namespace finalizers: %v", updateErr)
} else {
log.Printf("Successfully removed finalizers from namespace '%s'", namespace)
}
}
// Wait for namespace to be fully deleted (up to 2 minutes)
log.Printf("Waiting for namespace '%s' to be fully deleted...", namespace)
for i := 0; i < 24; i++ {
time.Sleep(5 * time.Second)
_, err := kubeClient.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
log.Printf("Namespace '%s' has been fully deleted.", namespace)
break
}
if i == 23 {
return fmt.Errorf("timeout waiting for namespace '%s' to finish terminating after removing finalizers", namespace)
}
log.Printf("Still waiting for namespace '%s' to terminate... (%d/24)", namespace, i+1)
}
// Reset err to NotFound so we create the namespace below
err = apierrors.NewNotFound(corev1.Resource("namespaces"), namespace)
}
if apierrors.IsNotFound(err) {
log.Printf("Namespace '%s' not found. Creating namespace", namespace)
newNs := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
},
}
if _, err := kubeClient.CoreV1().Namespaces().Create(ctx, newNs, metav1.CreateOptions{}); err != nil {
return fmt.Errorf("failed to create namespace '%s': %w", namespace, err)
}
log.Printf("Namespace '%s' created.", namespace)
} else if err != nil {
return fmt.Errorf("error getting namespace '%s': %w", namespace, err)
} else {
log.Printf("Namespace '%s' already exists.", namespace)
}
// Checking CRD exists or create it
_, err = apiExtClient.ApiextensionsV1().CustomResourceDefinitions().Get(ctx, crdName, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
if err := DownloadAndApplyCRD(ctx, apiExtClient, crdURL, crdName); err != nil {
return err
}
} else if err != nil {
return fmt.Errorf("error getting CRD '%s': %w", crdName, err)
} else {
log.Printf("CRD '%s' already exists.", crdName)
}
// Ensuring ConfigMap exists or create it
_, err = kubeClient.CoreV1().ConfigMaps(namespace).Get(ctx, configMapName, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
log.Printf("ConfigMap '%s' not found in namespace '%s'. Creating ConfigMap", configMapName, namespace)
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: configMapName,
Namespace: namespace,
},
Data: map[string]string{
"default_notification_email_address": "teste2e@redhat.com",
},
}
if _, err := kubeClient.CoreV1().ConfigMaps(namespace).Create(ctx, cm, metav1.CreateOptions{}); err != nil {
return fmt.Errorf("failed to create ConfigMap '%s': %w", configMapName, err)
}
log.Printf("ConfigMap '%s' created in namespace '%s'.", configMapName, namespace)
} else if err != nil {
return fmt.Errorf("error getting ConfigMap '%s': %w", configMapName, err)
} else {
log.Printf("ConfigMap '%s' already exists in namespace '%s'.", configMapName, namespace)
}
manifestURLs := []string{
"https://raw.githubusercontent.com/openshift/certman-operator/master/deploy/service_account.yaml",
"https://raw.githubusercontent.com/openshift/certman-operator/master/deploy/role.yaml",
"https://raw.githubusercontent.com/openshift/certman-operator/master/deploy/role_binding.yaml",
"https://raw.githubusercontent.com/openshift/certman-operator/master/deploy/operator.yaml",
}
if err := ApplyManifestsFromURLs(ctx, cfg, manifestURLs); err != nil {
return fmt.Errorf("failed to apply certman operator manifests: %w", err)
}
log.Println("Certman setup completed successfully.")
return nil
}
func SetupAWSCreds(ctx context.Context, kubeClient kubernetes.Interface) error {
const (
namespace = "certman-operator"