Skip to content

Commit 82dfaeb

Browse files
(ci) - fix cleanup to allow tests broken for 1.33 work
1 parent 5d3e33b commit 82dfaeb

File tree

1 file changed

+143
-81
lines changed

1 file changed

+143
-81
lines changed

test/e2e/v4/plugin_cluster_test.go

Lines changed: 143 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ var _ = Describe("kubebuilder", func() {
6363
By("clean up API objects created during the test")
6464
_ = kbc.Make("undeploy")
6565

66+
By("clean up API objects created during the test")
67+
_ = kbc.Make("uninstall")
68+
6669
By("removing controller image and working dir")
6770
kbc.Destroy()
6871
})
@@ -88,25 +91,19 @@ var _ = Describe("kubebuilder", func() {
8891
GenerateV4WithoutMetrics(kbc)
8992
Run(kbc, true, false, false, false, false)
9093
})
91-
// FIXME: This test is currently disabled because it requires to be fixed:
92-
// https://github.com/kubernetes-sigs/kubebuilder/issues/4853
93-
// It is not working for k8s 1.33
94-
// It("should generate a runnable project with metrics protected by network policies", func() {
95-
// GenerateV4WithNetworkPoliciesWithoutWebhooks(kbc)
96-
// Run(kbc, false, false, false, true, true)
97-
// })
94+
It("should generate a runnable project with metrics protected by network policies", func() {
95+
GenerateV4WithNetworkPoliciesWithoutWebhooks(kbc)
96+
Run(kbc, false, false, false, true, true)
97+
})
9898
It("should generate a runnable project with webhooks and metrics protected by network policies", func() {
9999
GenerateV4WithNetworkPolicies(kbc)
100100
Run(kbc, true, false, false, true, true)
101101
})
102-
// FIXME: This test is currently disabled because it requires to be fixed:
103-
// https://github.com/kubernetes-sigs/kubebuilder/issues/4853
104-
// It is not working for k8s 1.33
105-
// It("should generate a runnable project with the manager running "+
106-
// "as restricted and without webhooks", func() {
107-
// GenerateV4WithoutWebhooks(kbc)
108-
// Run(kbc, false, false, false, true, false)
109-
// })
102+
It("should generate a runnable project with the manager running "+
103+
"as restricted and without webhooks", func() {
104+
GenerateV4WithoutWebhooks(kbc)
105+
Run(kbc, false, false, false, true, false)
106+
})
110107
})
111108
})
112109

@@ -189,7 +186,7 @@ func Run(kbc *utils.TestContext, hasWebhook, isToUseInstaller, isToUseHelmChart,
189186
By("Checking if all flags are applied to the manager pod")
190187
podOutput, err := kbc.Kubectl.Get(
191188
true,
192-
"pod", controllerPodName,
189+
"pods", controllerPodName,
193190
"-o", "jsonpath={.spec.containers[0].args}",
194191
)
195192
Expect(err).NotTo(HaveOccurred())
@@ -453,7 +450,6 @@ func getControllerName(kbc *utils.TestContext) string {
453450
controllerPodName = podNames[0]
454451
g.Expect(controllerPodName).Should(ContainSubstring("controller-manager"))
455452

456-
// Validate pod status
457453
status, err := kbc.Kubectl.Get(
458454
true,
459455
"pods", controllerPodName, "-o", "jsonpath={.status.phase}")
@@ -464,9 +460,14 @@ func getControllerName(kbc *utils.TestContext) string {
464460
return nil
465461
}
466462
defer func() {
467-
out, err := kbc.Kubectl.CommandInNamespace("describe", "all")
468-
Expect(err).NotTo(HaveOccurred())
469-
_, _ = fmt.Fprintln(GinkgoWriter, out)
463+
status, err := kbc.Kubectl.Get(
464+
true,
465+
"pods", controllerPodName, "-o", "jsonpath={.status.phase}")
466+
if status != "Running" || err != nil {
467+
out, err := kbc.Kubectl.CommandInNamespace("describe", "all")
468+
Expect(err).NotTo(HaveOccurred())
469+
_, _ = fmt.Fprintln(GinkgoWriter, out)
470+
}
470471
}()
471472
Eventually(verifyControllerUp, 5*time.Minute, time.Second).Should(Succeed())
472473
return controllerPodName
@@ -501,6 +502,17 @@ func getMetricsOutput(kbc *utils.TestContext) string {
501502
)
502503
Expect(err).NotTo(HaveOccurred(), "Controller-manager service should exist")
503504

505+
By("checking controller-manager logs to verify metrics server is up")
506+
controllerPodName := getControllerName(kbc)
507+
checkLogs := func(g Gomega) {
508+
logs, curlLogsError := kbc.Kubectl.Logs(controllerPodName)
509+
g.Expect(curlLogsError).NotTo(HaveOccurred(), "failed to get controller-manager logs")
510+
g.Expect(logs).To(ContainSubstring("Serving metrics server"),
511+
"controller logs should show that metrics server is up")
512+
}
513+
Eventually(checkLogs, 2*time.Minute, 5*time.Second).Should(Succeed(),
514+
"controller logs should show metrics server startup within 2 minutes")
515+
504516
By("ensuring the service endpoint is ready")
505517
checkServiceEndpoint := func(g Gomega) {
506518
var output string
@@ -515,30 +527,62 @@ func getMetricsOutput(kbc *utils.TestContext) string {
515527
Eventually(checkServiceEndpoint, 2*time.Minute, time.Second).Should(Succeed(),
516528
"Service endpoint should be ready")
517529

518-
By("creating a curl pod to access the metrics endpoint")
519-
cmdOpts := cmdOptsToCreateCurlPod(kbc, token)
520-
_, err = kbc.Kubectl.CommandInNamespace(cmdOpts...)
521-
Expect(err).NotTo(HaveOccurred())
530+
By("checking if curl pod to access the metrics endpoint exist")
531+
podName := fmt.Sprintf("%s-curl", kbc.TestSuffix)
532+
if _, err = kbc.Kubectl.Get(true, "pods", podName); err != nil && strings.Contains(err.Error(), "NotFound") {
533+
By("creating a curl pod to access the metrics endpoint")
534+
cmdOpts := cmdOptsToCreateCurlPod(kbc, podName, token)
535+
_, err = kbc.Kubectl.CommandInNamespace(cmdOpts...)
536+
Expect(err).NotTo(HaveOccurred())
537+
}
522538

523-
By("validating that the curl pod is running as expected")
539+
By(fmt.Sprintf("validating that the pod %s is running as expected", podName))
524540
verifyCurlUp := func(g Gomega) {
525541
var status string
526542
status, err = kbc.Kubectl.Get(
527543
true,
528-
"pods", "curl", "-o", "jsonpath={.status.phase}")
544+
"pods", podName, "-o", "jsonpath={.status.phase}")
529545
g.Expect(err).NotTo(HaveOccurred())
530-
g.Expect(status).To(Equal("Succeeded"), fmt.Sprintf("curl pod in %s status", status))
546+
g.Expect(status).To(Equal("Succeeded"), fmt.Sprintf("%s pod in %s status", podName, status))
531547
}
548+
defer func() {
549+
status, errCurl := kbc.Kubectl.Get(
550+
true,
551+
"pods", podName, "-o", "jsonpath={.status.phase}")
552+
if status != "Succeeded" || errCurl != nil {
553+
out, errDescribe := kbc.Kubectl.CommandInNamespace("describe", "all")
554+
Expect(errDescribe).NotTo(HaveOccurred())
555+
_, _ = fmt.Fprintln(GinkgoWriter, out)
556+
557+
out, err = kbc.Kubectl.Get(true,
558+
"pods", podName, "-o", "jsonpath={.status.phase}", "--namespace", kbc.Kubectl.Namespace)
559+
Expect(err).NotTo(HaveOccurred())
560+
_, _ = fmt.Fprintln(GinkgoWriter, out)
561+
}
562+
}()
532563
Eventually(verifyCurlUp, 240*time.Second, time.Second).Should(Succeed())
533564

565+
By("validating that the correct ServiceAccount is being used")
566+
saName := kbc.Kubectl.ServiceAccount
567+
currentSAOutput, err := kbc.Kubectl.Get(
568+
true,
569+
"serviceaccount", saName,
570+
"-o", "jsonpath={.metadata.name}",
571+
)
572+
Expect(err).NotTo(HaveOccurred(), "Failed to fetch the service account")
573+
Expect(currentSAOutput).To(Equal(saName), "The ServiceAccount in use does not match the expected one")
574+
534575
By("validating that the metrics endpoint is serving as expected")
535576
getCurlLogs := func(g Gomega) {
536-
metricsOutput, err = kbc.Kubectl.Logs("curl")
577+
metricsOutput, err = kbc.Kubectl.Logs("pod/" + podName)
537578
g.Expect(err).NotTo(HaveOccurred())
538579
g.Expect(metricsOutput).Should(ContainSubstring("< HTTP/1.1 200 OK"))
539580
}
540581
Eventually(getCurlLogs, 10*time.Second, time.Second).Should(Succeed())
582+
583+
By("By removing pod create for the metrics")
541584
removeCurlPod(kbc)
585+
542586
return metricsOutput
543587
}
544588

@@ -553,81 +597,99 @@ func metricsShouldBeUnavailable(kbc *utils.TestContext) {
553597
Expect(err).NotTo(HaveOccurred())
554598
Expect(token).NotTo(BeEmpty())
555599

556-
By("creating a curl pod to access the metrics endpoint")
557-
cmdOpts := cmdOptsToCreateCurlPod(kbc, token)
558-
_, err = kbc.Kubectl.CommandInNamespace(cmdOpts...)
559-
Expect(err).NotTo(HaveOccurred())
600+
By("checking if curl pod to access the metrics endpoint exist")
601+
podName := fmt.Sprintf("%s-curl", kbc.TestSuffix)
602+
if _, errCurl := kbc.Kubectl.Get(true, "pods", podName); errCurl != nil &&
603+
strings.Contains(errCurl.Error(), "NotFound") {
604+
By("creating a curl pod to access the metrics endpoint")
605+
cmdOpts := cmdOptsToCreateCurlPod(kbc, podName, token)
606+
_, err = kbc.Kubectl.CommandInNamespace(cmdOpts...)
607+
Expect(err).NotTo(HaveOccurred())
608+
}
560609

561610
By("validating that the curl pod fail as expected")
562611
verifyCurlUp := func(g Gomega) {
563612
status, errCurl := kbc.Kubectl.Get(
564613
true,
565-
"pods", "curl", "-o", "jsonpath={.status.phase}")
614+
"pods", podName, "-o", "jsonpath={.status.phase}")
566615
g.Expect(errCurl).NotTo(HaveOccurred())
567616
g.Expect(status).NotTo(Equal("Failed"),
568617
fmt.Sprintf("curl pod in %s status when should fail with an error", status))
569618
}
570619
Eventually(verifyCurlUp, 240*time.Second, time.Second).Should(Succeed())
571620

572-
By("validating that the correct ServiceAccount is being used")
573-
saName := kbc.Kubectl.ServiceAccount
574-
currentSAOutput, err := kbc.Kubectl.Get(
575-
true,
576-
"serviceaccount", saName,
577-
"-o", "jsonpath={.metadata.name}",
578-
)
579-
Expect(err).NotTo(HaveOccurred(), "Failed to fetch the service account")
580-
Expect(currentSAOutput).To(Equal(saName), "The ServiceAccount in use does not match the expected one")
581-
582621
By("validating that the metrics endpoint is not working as expected")
583622
getCurlLogs := func(g Gomega) {
584-
metricsOutput, err := kbc.Kubectl.Logs("curl")
623+
metricsOutput, err := kbc.Kubectl.Logs("pod/" + podName)
585624
g.Expect(err).NotTo(HaveOccurred())
586625
g.Expect(metricsOutput).Should(ContainSubstring("Could not resolve host"))
587626
}
588627
Eventually(getCurlLogs, 10*time.Second, time.Second).Should(Succeed())
628+
629+
By("By removing pod create for the metrics")
589630
removeCurlPod(kbc)
590631
}
591-
592-
func cmdOptsToCreateCurlPod(kbc *utils.TestContext, token string) []string {
593-
//nolint:lll
594-
cmdOpts := []string{
595-
"run", "curl",
596-
"--restart=Never",
597-
"--namespace", kbc.Kubectl.Namespace,
598-
"--image=curlimages/curl:latest",
599-
"--overrides",
600-
fmt.Sprintf(`{
601-
"spec": {
602-
"containers": [{
603-
"name": "curl",
604-
"image": "curlimages/curl:latest",
605-
"command": ["/bin/sh", "-c"],
606-
"args": ["curl -v -k -H 'Authorization: Bearer %s' https://e2e-%s-controller-manager-metrics-service.%s.svc.cluster.local:8443/metrics"],
607-
"securityContext": {
608-
"readOnlyRootFilesystem": true,
609-
"allowPrivilegeEscalation": false,
610-
"capabilities": {
611-
"drop": ["ALL"]
612-
},
613-
"runAsNonRoot": true,
614-
"runAsUser": 1000,
615-
"seccompProfile": {
616-
"type": "RuntimeDefault"
617-
}
618-
}
619-
}],
620-
"serviceAccountName": "%s"
621-
}
622-
}`, token, kbc.TestSuffix, kbc.Kubectl.Namespace, kbc.Kubectl.ServiceAccount),
623-
}
624-
return cmdOpts
632+
func cmdOptsToCreateCurlPod(kbc *utils.TestContext, podName, token string) []string {
633+
jobYAML := fmt.Sprintf(`{
634+
"apiVersion": "batch/v1",
635+
"kind": "Job",
636+
"metadata": {
637+
"name": "%s",
638+
"namespace": "%s"
639+
},
640+
"spec": {
641+
"template": {
642+
"spec": {
643+
"restartPolicy": "OnFailure",
644+
"containers": [{
645+
"name": "curl",
646+
"image": "curlimages/curl:latest",
647+
"command": ["/bin/sh", "-c"],
648+
"args": ["curl -v -k -H 'Authorization: Bearer %s' https://e2e-%s-controller-manager-metrics-service.%s.svc.cluster.local:8443/metrics"],
649+
"securityContext": {
650+
"readOnlyRootFilesystem": true,
651+
"allowPrivilegeEscalation": false,
652+
"capabilities": {
653+
"drop": ["ALL"]
654+
},
655+
"runAsNonRoot": true,
656+
"runAsUser": 1000,
657+
"seccompProfile": {
658+
"type": "RuntimeDefault"
659+
}
660+
}
661+
}],
662+
"serviceAccountName": "%s"
663+
}
664+
}
665+
}
666+
}`, podName, kbc.Kubectl.Namespace, token, kbc.TestSuffix, kbc.Kubectl.Namespace, kbc.Kubectl.ServiceAccount)
667+
668+
// Save the manifest into the Stdin of the Kubectl context
669+
kbc.Kubectl.Stdin = strings.NewReader(jobYAML)
670+
671+
// Return the kubectl command options for `kubectl apply -f -`
672+
return []string{"apply", "-f", "-"}
625673
}
626674

627675
func removeCurlPod(kbc *utils.TestContext) {
628-
By("cleaning up the curl pod")
629-
_, err := kbc.Kubectl.Delete(true, "pods/curl")
630-
Expect(err).NotTo(HaveOccurred())
676+
podName := fmt.Sprintf("%s-curl", kbc.TestSuffix)
677+
678+
By(fmt.Sprintf("checking if pod %q exists before attempting cleanup", podName))
679+
if _, err := kbc.Kubectl.Get(true, "pods", podName); err != nil {
680+
By(fmt.Sprintf("pod %q does not exist, skipping cleanup", podName))
681+
return
682+
}
683+
684+
By("waiting for the pod to be deleted")
685+
if _, err := kbc.Kubectl.Wait(true, "pod/"+podName, "--for=delete", "--timeout=40s"); err != nil {
686+
By("force deleting the curl pod with 0s grace period")
687+
_, err := kbc.Kubectl.Delete(true, "pods", podName, "--grace-period=0", "--force")
688+
Expect(err).NotTo(HaveOccurred())
689+
690+
_, err = kbc.Kubectl.Wait(true, "pod/"+podName, "--for=delete", "--timeout=30s")
691+
Expect(err).NotTo(HaveOccurred())
692+
}
631693
}
632694

633695
// serviceAccountToken provides a helper function that can provide you with a service account

0 commit comments

Comments
 (0)