[OSD-24748] SDN migration suite #2668
GROQ_API_KEY / GROQ_API_KEY_backup in .env
Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all
/assign
/ok-to-test
@@ -0,0 +1,639 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "log"
+ "strconv"
+ "strings"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "os"
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+ "time"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+/*
+- before all create clients
+- test cluster creation
+- test cluster upgrade
+- test cluster migration<
+ - test apply manifests
+*/
@@ -0,0 +1,63 @@
+# Rosa SDN to OVN Migration Test Suite
+
+
+This folder contains the test suite to validate rosa cluster upgrades and network
+migration from SDN to OVN for 14.14.x cluster.
+
+
+The test suite can be easily run by invoking `ginkgo run` directly,
+from a `compiled binary`
+## Test Suite Model
This folder contains the test suite to validate rosa cluster upgrades and network
migration from SDN to OVN for 14.14.x cluster.
The test suite can be easily run by invoking `ginkgo run` directly,
from a `compiled binary`
## Test Suite Model
@@ -0,0 +1,63 @@
+# Rosa SDN to OVN Migration Test Suite
+
+
+This folder contains the test suite to validate rosa cluster upgrades and network
+migration from SDN to OVN for 14.14.x cluster.
+
+
+The test suite can be easily run by invoking `ginkgo run` directly,
+from a `compiled binary`
+## Test Suite Model
just white space cleanup
@@ -0,0 +1,639 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "log"
+ "strconv"
+ "strings"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "os"
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+ "time"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+/*
+- before all create clients
+- test cluster creation
+- test cluster upgrade
+- test cluster migration<
+ - test apply manifests
+*/
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ rosaProvider, err := rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ err = rosaProvider.DeleteCluster(ctx, &rosaprovider.DeleteClusterOptions{
+ ClusterName: testRosaCluster.name,
+ WorkingDir: testRosaCluster.reportDir,
+ STS: true,
+ DeleteOidcConfigID: true,
+ })
+ Expect(err).Should(BeNil(), "failed to delete rosa cluster")
+ }
+ })
+
+ It("rosa cluster is upgraded to 4.15.8 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_15, image4_15, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.15.8 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.15.8-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster is upgraded to 4.16.0-rc.0 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_16, image4_16, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.16.0-rc.0 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.16.0-rc.0-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster migrated from sdn to ovn successfully", sdnToOvn, func(ctx context.Context) {
+ err := addIntenalTestingAnnotation(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = patchNetworkConfig(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = checkMigrationStatus(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+
+ })
+ It("rosa cluster has no critical alerts firing post sdn to ovn migration", postMigrationCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+})
+
+// queryPrometheusAlerts queries prometheus for alerts and provides a count for critical and warning alerts
+func queryPrometheusAlerts(ctx context.Context, client *openshiftclient.Client, logFilename string) (int, int, error) {
+ criticalAlertCount, warningAlertCount := 0, 0
+ alerts := ""
+
+ type metric struct {
+ AlertName string `json:"alertname"`
+ AlertState string `json:"alertstate"`
+ Condition string `json:"condition"`
+ Endpoint string `json:"endpoint"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Severity string `json:"severity"`
+ }
+
+ prometheusClient, _ := prometheusclient.New(ctx, client)
+ vector, err := prometheusClient.InstantQuery(ctx, "ALERTS{alertstate!=\"pending\",alertname!=\"Watchdog\"}")
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to query prometheus: %v", err)
+ }
+
+ for _, model := range vector {
+ metric := metric{}
+
+ metricEncoded, err := json.Marshal(model.Metric)
+ if err != nil {
+ continue
+ }
+
+ err = json.Unmarshal(metricEncoded, &metric)
+ if err != nil {
+ continue
+ }
+
+ alerts += fmt.Sprintf("Since: %s : %+v\n", time.Unix(model.Timestamp.Unix(), 0), metric)
+
+ switch model.Metric["severity"] {
+ case "critical":
+ criticalAlertCount += 1
+ case "warning":
+ warningAlertCount += 1
+ }
+ }
+
+ if alerts != "" {
+ if err = os.WriteFile(logFilename, []byte(alerts), os.FileMode(0o644)); err != nil {
+ return criticalAlertCount, warningAlertCount, fmt.Errorf("failed to write prometheus alerts to file: %v", err)
+ }
+ }
+
+ return criticalAlertCount, warningAlertCount, nil
+}
+
+// getEnvVar returns the env variable value and if unset returns default provided
+func getEnvVar(key, value string) string {
+ result, exist := os.LookupEnv(key)
+ if exist {
+ return result
+ }
+ return value
+}
+
+// osdClusterReadyHealthCheck verifies the osd-cluster-ready health check job is passing
+func osdClusterReadyHealthCheck(ctx context.Context, clusterClient *openshiftclient.Client, action, reportDir string) error {
+ var (
+ err error
+ job batchv1.Job
+ )
+
+ if err = clusterClient.Get(ctx, osdClusterReadyJobName, "openshift-monitoring", &job); err != nil {
+ return fmt.Errorf("failed to get existing %s job %v", osdClusterReadyJobName, err)
+ }
+
+ newJob := &batchv1.Job{
+ ObjectMeta: metav1.ObjectMeta{
+ GenerateName: osdClusterReadyJobName,
+ Annotations: job.Annotations,
+ Namespace: job.Namespace,
+ },
+ Spec: job.Spec,
+ }
+
+ newJob.Spec.Selector.MatchLabels = map[string]string{}
+ newJob.Spec.Template.ObjectMeta.Name = newJob.GetGenerateName()
+ newJob.Spec.Template.ObjectMeta.Labels = map[string]string{}
+ newJob.Spec.Template.Spec.Containers[0].Name = newJob.GetGenerateName()
+
+ if err = clusterClient.Create(ctx, newJob); err != nil {
+ return fmt.Errorf("failed to create %s job: %v", newJob.GetName(), err)
+ }
+
+ defer func() {
+ _ = clusterClient.Delete(ctx, newJob)
+ }()
+
+ return clusterClient.OSDClusterHealthy(ctx, newJob.GetName(), reportDir, osdClusterReadyJobTimeout)
+}
+
+// getKubernetesDynamicClient returns the kubernetes dynamic client
+func getKubernetesDynamicClient(client *openshiftclient.Client) (*dynamic.DynamicClient, error) {
+ dynamicClient, err := dynamic.NewForConfig(client.GetConfig())
+ if err != nil {
+ return nil, fmt.Errorf("failed to create kubernetes dynamic client: %w", err)
+ }
+ return dynamicClient, nil
+}
+
+type upgradeError struct {
+ err error
+}
+
+// Error returns the formatted error message when upgradeError is invoked
+func (e *upgradeError) Error() string {
+ return fmt.Sprintf("osd upgrade failed: %v", e.err)
+}
+
+func getOpenshiftConfig(ctx context.Context, dynamicClient *dynamic.DynamicClient, resource string, name string) (*unstructured.Unstructured, error) {
+ gvr := schema.GroupVersionResource{
+ Group: "config.openshift.io",
+ Version: "v1",
+ Resource: resource,
+ }
+ return dynamicClient.Resource(gvr).Get(ctx, name, metav1.GetOptions{})
+}
+
+// checkMigrationStatus probes the status of the SDN-to-OVN migration
+func checkMigrationStatus(ctx context.Context, client *openshiftclient.Client) error {
+ var (
+ dynamicClient *dynamic.DynamicClient
+ err error
+ )
+
+ if dynamicClient, err = getKubernetesDynamicClient(client); err != nil {
+ return &upgradeError{err: err}
+ }
+ for i := 1; i <= upgradeMaxAttempts; i++ {
+ // Get the current network configuration
+ networkConfig, err := getOpenshiftConfig(ctx, dynamicClient, "networks", "cluster")
You should be able to do a this instead of the dynamic client
var network configv1.Network
_ = oc.Get(context.Background(), "", "cluster", &network)
@@ -0,0 +1,639 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "log"
+ "strconv"
+ "strings"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "os"
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+ "time"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+/*
+- before all create clients
+- test cluster creation
+- test cluster upgrade
+- test cluster migration<
+ - test apply manifests
+*/
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ rosaProvider, err := rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ err = rosaProvider.DeleteCluster(ctx, &rosaprovider.DeleteClusterOptions{
+ ClusterName: testRosaCluster.name,
+ WorkingDir: testRosaCluster.reportDir,
+ STS: true,
+ DeleteOidcConfigID: true,
+ })
+ Expect(err).Should(BeNil(), "failed to delete rosa cluster")
+ }
+ })
+
+ It("rosa cluster is upgraded to 4.15.8 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_15, image4_15, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.15.8 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.15.8-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster is upgraded to 4.16.0-rc.0 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_16, image4_16, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.16.0-rc.0 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.16.0-rc.0-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster migrated from sdn to ovn successfully", sdnToOvn, func(ctx context.Context) {
+ err := addIntenalTestingAnnotation(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = patchNetworkConfig(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = checkMigrationStatus(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+
+ })
+ It("rosa cluster has no critical alerts firing post sdn to ovn migration", postMigrationCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+})
+
+// queryPrometheusAlerts queries prometheus for alerts and provides a count for critical and warning alerts
+func queryPrometheusAlerts(ctx context.Context, client *openshiftclient.Client, logFilename string) (int, int, error) {
+ criticalAlertCount, warningAlertCount := 0, 0
+ alerts := ""
+
+ type metric struct {
+ AlertName string `json:"alertname"`
+ AlertState string `json:"alertstate"`
+ Condition string `json:"condition"`
+ Endpoint string `json:"endpoint"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Severity string `json:"severity"`
+ }
+
+ prometheusClient, _ := prometheusclient.New(ctx, client)
+ vector, err := prometheusClient.InstantQuery(ctx, "ALERTS{alertstate!=\"pending\",alertname!=\"Watchdog\"}")
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to query prometheus: %v", err)
+ }
+
+ for _, model := range vector {
+ metric := metric{}
+
+ metricEncoded, err := json.Marshal(model.Metric)
+ if err != nil {
+ continue
+ }
+
+ err = json.Unmarshal(metricEncoded, &metric)
+ if err != nil {
+ continue
+ }
+
+ alerts += fmt.Sprintf("Since: %s : %+v\n", time.Unix(model.Timestamp.Unix(), 0), metric)
+
+ switch model.Metric["severity"] {
+ case "critical":
+ criticalAlertCount += 1
+ case "warning":
+ warningAlertCount += 1
+ }
+ }
+
+ if alerts != "" {
+ if err = os.WriteFile(logFilename, []byte(alerts), os.FileMode(0o644)); err != nil {
+ return criticalAlertCount, warningAlertCount, fmt.Errorf("failed to write prometheus alerts to file: %v", err)
+ }
+ }
+
+ return criticalAlertCount, warningAlertCount, nil
+}
+
+// getEnvVar returns the env variable value and if unset returns default provided
+func getEnvVar(key, value string) string {
+ result, exist := os.LookupEnv(key)
+ if exist {
+ return result
+ }
+ return value
+}
+
+// osdClusterReadyHealthCheck verifies the osd-cluster-ready health check job is passing
+func osdClusterReadyHealthCheck(ctx context.Context, clusterClient *openshiftclient.Client, action, reportDir string) error {
+ var (
+ err error
+ job batchv1.Job
+ )
+
+ if err = clusterClient.Get(ctx, osdClusterReadyJobName, "openshift-monitoring", &job); err != nil {
+ return fmt.Errorf("failed to get existing %s job %v", osdClusterReadyJobName, err)
+ }
+
+ newJob := &batchv1.Job{
+ ObjectMeta: metav1.ObjectMeta{
+ GenerateName: osdClusterReadyJobName,
+ Annotations: job.Annotations,
+ Namespace: job.Namespace,
+ },
+ Spec: job.Spec,
+ }
+
+ newJob.Spec.Selector.MatchLabels = map[string]string{}
+ newJob.Spec.Template.ObjectMeta.Name = newJob.GetGenerateName()
+ newJob.Spec.Template.ObjectMeta.Labels = map[string]string{}
+ newJob.Spec.Template.Spec.Containers[0].Name = newJob.GetGenerateName()
+
+ if err = clusterClient.Create(ctx, newJob); err != nil {
+ return fmt.Errorf("failed to create %s job: %v", newJob.GetName(), err)
+ }
+
+ defer func() {
+ _ = clusterClient.Delete(ctx, newJob)
+ }()
+
+ return clusterClient.OSDClusterHealthy(ctx, newJob.GetName(), reportDir, osdClusterReadyJobTimeout)
+}
+
+// getKubernetesDynamicClient returns the kubernetes dynamic client
+func getKubernetesDynamicClient(client *openshiftclient.Client) (*dynamic.DynamicClient, error) {
+ dynamicClient, err := dynamic.NewForConfig(client.GetConfig())
+ if err != nil {
+ return nil, fmt.Errorf("failed to create kubernetes dynamic client: %w", err)
+ }
+ return dynamicClient, nil
+}
+
+type upgradeError struct {
+ err error
+}
+
+// Error returns the formatted error message when upgradeError is invoked
+func (e *upgradeError) Error() string {
+ return fmt.Sprintf("osd upgrade failed: %v", e.err)
+}
+
+func getOpenshiftConfig(ctx context.Context, dynamicClient *dynamic.DynamicClient, resource string, name string) (*unstructured.Unstructured, error) {
+ gvr := schema.GroupVersionResource{
+ Group: "config.openshift.io",
+ Version: "v1",
+ Resource: resource,
+ }
+ return dynamicClient.Resource(gvr).Get(ctx, name, metav1.GetOptions{})
+}
+
+// checkMigrationStatus probes the status of the SDN-to-OVN migration
+func checkMigrationStatus(ctx context.Context, client *openshiftclient.Client) error {
+ var (
+ dynamicClient *dynamic.DynamicClient
+ err error
+ )
+
+ if dynamicClient, err = getKubernetesDynamicClient(client); err != nil {
+ return &upgradeError{err: err}
+ }
+ for i := 1; i <= upgradeMaxAttempts; i++ {
+ // Get the current network configuration
+ networkConfig, err := getOpenshiftConfig(ctx, dynamicClient, "networks", "cluster")
+ if err != nil {
+ return fmt.Errorf("failed to get network configuration: %v", err)
+ }
+
+ // Extract the status conditions
+ status, found, err := unstructured.NestedMap(networkConfig.Object, "status")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find status in network configuration: %v", err)
+ }
+
+ conditions, found, err := unstructured.NestedSlice(status, "conditions")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find conditions in status: %v", err)
+ }
+
+ // Check for the migration condition
+ migrationInProgress := false
+ for _, cond := range conditions {
+ conditionMap, ok := cond.(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("invalid type for condition entry")
+ }
+
+ conditionType, found, err := unstructured.NestedString(conditionMap, "type")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition type: %v", err)
+ }
+
+ if conditionType == "NetworkTypeMigrationInProgress" {
+ status, found, err := unstructured.NestedString(conditionMap, "status")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition status: %v", err)
+ }
+
+ reason, found, err := unstructured.NestedString(conditionMap, "reason")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition reason: %v", err)
+ }
+
+ // Check if the migration is in progress
+ if status == "True" && reason == "NetworkTypeMigrationStarted" {
+ migrationInProgress = true
+ break
+ }
+
+ // Check if the migration is complete
+ if status == "False" && reason == "NetworkTypeMigrationCompleted" {
+ fmt.Println("Network migration completed successfully!")
+ return nil
+ }
+ }
+ }
+
+ if migrationInProgress {
+ fmt.Println("Network migration is still in progress...")
+ } else {
+ fmt.Println("Migration status is unknown or not in progress.")
+ }
+
+ time.Sleep(upgradeDelay * time.Second)
+ }
+
+ return fmt.Errorf("network migration is still in progress after %d attempts", upgradeMaxAttempts)
+
+}
+
+// checkUpgradeStatus probes the status of the cluster upgrade
+func checkUpgradeStatus(ctx context.Context, client *openshiftclient.Client, upgradeVersion string) error {
+ var (
+ conditionMessage string
+ dynamicClient *dynamic.DynamicClient
+ upgradeState string
+ err error
+ )
+
+ for i := 1; i <= upgradeMaxAttempts; i++ {
+ if dynamicClient, err = getKubernetesDynamicClient(client); err != nil {
+ log.Printf("here")
+ time.Sleep(upgradeDelay * time.Second)
+ continue
+ }
+ // Get the current cluster version configuration
+ upgradeConfig, err := getOpenshiftConfig(ctx, dynamicClient, "clusterversions", "version")
Same with this
var cv configv1.ClusterVersion
_ = oc.Get(context.Background(), "", "version", &cv)
should cut down on the unstructured stuff
@@ -0,0 +1,639 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "log"
+ "strconv"
+ "strings"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "os"
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+ "time"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+/*
+- before all create clients
+- test cluster creation
+- test cluster upgrade
+- test cluster migration<
+ - test apply manifests
+*/
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ rosaProvider, err := rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ err = rosaProvider.DeleteCluster(ctx, &rosaprovider.DeleteClusterOptions{
+ ClusterName: testRosaCluster.name,
+ WorkingDir: testRosaCluster.reportDir,
+ STS: true,
+ DeleteOidcConfigID: true,
+ })
+ Expect(err).Should(BeNil(), "failed to delete rosa cluster")
+ }
+ })
+
+ It("rosa cluster is upgraded to 4.15.8 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_15, image4_15, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.15.8 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.15.8-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster is upgraded to 4.16.0-rc.0 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_16, image4_16, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.16.0-rc.0 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.16.0-rc.0-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster migrated from sdn to ovn successfully", sdnToOvn, func(ctx context.Context) {
+ err := addIntenalTestingAnnotation(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = patchNetworkConfig(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = checkMigrationStatus(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+
+ })
+ It("rosa cluster has no critical alerts firing post sdn to ovn migration", postMigrationCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+})
+
+// queryPrometheusAlerts queries prometheus for alerts and provides a count for critical and warning alerts
+func queryPrometheusAlerts(ctx context.Context, client *openshiftclient.Client, logFilename string) (int, int, error) {
+ criticalAlertCount, warningAlertCount := 0, 0
+ alerts := ""
+
+ type metric struct {
+ AlertName string `json:"alertname"`
+ AlertState string `json:"alertstate"`
+ Condition string `json:"condition"`
+ Endpoint string `json:"endpoint"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Severity string `json:"severity"`
+ }
+
+ prometheusClient, _ := prometheusclient.New(ctx, client)
+ vector, err := prometheusClient.InstantQuery(ctx, "ALERTS{alertstate!=\"pending\",alertname!=\"Watchdog\"}")
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to query prometheus: %v", err)
+ }
+
+ for _, model := range vector {
+ metric := metric{}
+
+ metricEncoded, err := json.Marshal(model.Metric)
+ if err != nil {
+ continue
+ }
+
+ err = json.Unmarshal(metricEncoded, &metric)
+ if err != nil {
+ continue
+ }
+
+ alerts += fmt.Sprintf("Since: %s : %+v\n", time.Unix(model.Timestamp.Unix(), 0), metric)
+
+ switch model.Metric["severity"] {
+ case "critical":
+ criticalAlertCount += 1
+ case "warning":
+ warningAlertCount += 1
+ }
+ }
+
+ if alerts != "" {
+ if err = os.WriteFile(logFilename, []byte(alerts), os.FileMode(0o644)); err != nil {
+ return criticalAlertCount, warningAlertCount, fmt.Errorf("failed to write prometheus alerts to file: %v", err)
+ }
+ }
+
+ return criticalAlertCount, warningAlertCount, nil
+}
+
+// getEnvVar returns the env variable value and if unset returns default provided
+func getEnvVar(key, value string) string {
+ result, exist := os.LookupEnv(key)
+ if exist {
+ return result
+ }
+ return value
+}
+
+// osdClusterReadyHealthCheck verifies the osd-cluster-ready health check job is passing
+func osdClusterReadyHealthCheck(ctx context.Context, clusterClient *openshiftclient.Client, action, reportDir string) error {
+ var (
+ err error
+ job batchv1.Job
+ )
+
+ if err = clusterClient.Get(ctx, osdClusterReadyJobName, "openshift-monitoring", &job); err != nil {
+ return fmt.Errorf("failed to get existing %s job %v", osdClusterReadyJobName, err)
+ }
+
+ newJob := &batchv1.Job{
+ ObjectMeta: metav1.ObjectMeta{
+ GenerateName: osdClusterReadyJobName,
+ Annotations: job.Annotations,
+ Namespace: job.Namespace,
+ },
+ Spec: job.Spec,
+ }
+
+ newJob.Spec.Selector.MatchLabels = map[string]string{}
+ newJob.Spec.Template.ObjectMeta.Name = newJob.GetGenerateName()
+ newJob.Spec.Template.ObjectMeta.Labels = map[string]string{}
+ newJob.Spec.Template.Spec.Containers[0].Name = newJob.GetGenerateName()
+
+ if err = clusterClient.Create(ctx, newJob); err != nil {
+ return fmt.Errorf("failed to create %s job: %v", newJob.GetName(), err)
+ }
+
+ defer func() {
+ _ = clusterClient.Delete(ctx, newJob)
+ }()
+
+ return clusterClient.OSDClusterHealthy(ctx, newJob.GetName(), reportDir, osdClusterReadyJobTimeout)
+}
+
+// getKubernetesDynamicClient returns the kubernetes dynamic client
+func getKubernetesDynamicClient(client *openshiftclient.Client) (*dynamic.DynamicClient, error) {
+ dynamicClient, err := dynamic.NewForConfig(client.GetConfig())
+ if err != nil {
+ return nil, fmt.Errorf("failed to create kubernetes dynamic client: %w", err)
+ }
+ return dynamicClient, nil
+}
+
+type upgradeError struct {
+ err error
+}
+
+// Error returns the formatted error message when upgradeError is invoked
+func (e *upgradeError) Error() string {
+ return fmt.Sprintf("osd upgrade failed: %v", e.err)
+}
+
+func getOpenshiftConfig(ctx context.Context, dynamicClient *dynamic.DynamicClient, resource string, name string) (*unstructured.Unstructured, error) {
+ gvr := schema.GroupVersionResource{
+ Group: "config.openshift.io",
+ Version: "v1",
+ Resource: resource,
+ }
+ return dynamicClient.Resource(gvr).Get(ctx, name, metav1.GetOptions{})
+}
+
+// checkMigrationStatus probes the status of the SDN-to-OVN migration
+func checkMigrationStatus(ctx context.Context, client *openshiftclient.Client) error {
+ var (
+ dynamicClient *dynamic.DynamicClient
+ err error
+ )
+
+ if dynamicClient, err = getKubernetesDynamicClient(client); err != nil {
+ return &upgradeError{err: err}
+ }
+ for i := 1; i <= upgradeMaxAttempts; i++ {
+ // Get the current network configuration
+ networkConfig, err := getOpenshiftConfig(ctx, dynamicClient, "networks", "cluster")
+ if err != nil {
+ return fmt.Errorf("failed to get network configuration: %v", err)
+ }
+
+ // Extract the status conditions
+ status, found, err := unstructured.NestedMap(networkConfig.Object, "status")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find status in network configuration: %v", err)
+ }
+
+ conditions, found, err := unstructured.NestedSlice(status, "conditions")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find conditions in status: %v", err)
+ }
+
+ // Check for the migration condition
+ migrationInProgress := false
+ for _, cond := range conditions {
+ conditionMap, ok := cond.(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("invalid type for condition entry")
+ }
+
+ conditionType, found, err := unstructured.NestedString(conditionMap, "type")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition type: %v", err)
+ }
+
+ if conditionType == "NetworkTypeMigrationInProgress" {
+ status, found, err := unstructured.NestedString(conditionMap, "status")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition status: %v", err)
+ }
+
+ reason, found, err := unstructured.NestedString(conditionMap, "reason")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition reason: %v", err)
+ }
+
+ // Check if the migration is in progress
+ if status == "True" && reason == "NetworkTypeMigrationStarted" {
+ migrationInProgress = true
+ break
+ }
+
+ // Check if the migration is complete
+ if status == "False" && reason == "NetworkTypeMigrationCompleted" {
+ fmt.Println("Network migration completed successfully!")
+ return nil
+ }
+ }
+ }
+
+ if migrationInProgress {
+ fmt.Println("Network migration is still in progress...")
+ } else {
+ fmt.Println("Migration status is unknown or not in progress.")
+ }
+
+ time.Sleep(upgradeDelay * time.Second)
+ }
+
+ return fmt.Errorf("network migration is still in progress after %d attempts", upgradeMaxAttempts)
+
+}
+
+// checkUpgradeStatus probes the status of the cluster upgrade
+func checkUpgradeStatus(ctx context.Context, client *openshiftclient.Client, upgradeVersion string) error {
+ var (
+ conditionMessage string
+ dynamicClient *dynamic.DynamicClient
+ upgradeState string
+ err error
+ )
+
+ for i := 1; i <= upgradeMaxAttempts; i++ {
+ if dynamicClient, err = getKubernetesDynamicClient(client); err != nil {
+ log.Printf("here")
+ time.Sleep(upgradeDelay * time.Second)
+ continue
+ }
+ // Get the current cluster version configuration
+ upgradeConfig, err := getOpenshiftConfig(ctx, dynamicClient, "clusterversions", "version")
+ if err != nil {
+ log.Printf("Failed to get cluster version config: %v", err)
+ time.Sleep(upgradeDelay * time.Second)
+ continue
+ }
+
+ // Extract the status map from the configuration
+ status, found, err := unstructured.NestedMap(upgradeConfig.Object, "status")
+ if err != nil || !found {
+ log.Printf("Failed to find status in cluster version config: %v", err)
+ time.Sleep(upgradeDelay * time.Second)
+ continue
+ }
+
+ // Extract the history slice from the status
+ histories, found, err := unstructured.NestedSlice(status, "history")
+ if err != nil || !found {
+ log.Printf("Failed to find history in status")
+ time.Sleep(upgradeDelay * time.Second)
+ continue
+ }
+
+ for _, h := range histories {
+ historyMap, ok := h.(map[string]interface{})
+ if !ok {
+ err = fmt.Errorf("invalid type for history entry")
+ log.Printf(err.Error(), "Invalid history entry type")
+ continue
+ }
+
+ // Extract the version for each history entry
+ version, found, err := unstructured.NestedString(historyMap, "version")
+ if err != nil || !found {
+ log.Printf("Failed to find version in history entry")
+ continue
+ }
+
+ // Check if the version matches the desired upgrade version
+ if version == upgradeVersion {
+ // Extract the state for the matching version
+ state, found, err := unstructured.NestedString(historyMap, "state")
+ if err != nil || !found {
+ log.Printf("Failed to find state in history entry")
+ continue
+ }
+
+ upgradeState = state
+ break
+ }
+ }
+
+ // Extract the conditions from the status
+ conditions, found, err := unstructured.NestedSlice(status, "conditions")
+ if err != nil || !found {
+ log.Printf("Failed to find conditions in status")
+ } else {
+ // Filter for the condition message that starts with "Working towards"
+ for _, cond := range conditions {
+ conditionMap, ok := cond.(map[string]interface{})
+ if !ok {
+ err = fmt.Errorf("invalid type for condition entry")
+ log.Printf(err.Error(), "Invalid condition entry type")
+ continue
+ }
+
+ // Extract the condition message
+ message, found, err := unstructured.NestedString(conditionMap, "message")
+ if err != nil || !found {
+ continue
+ }
+
+ // Check if the message starts with "Working towards"
+ if strings.HasPrefix(message, "Working towards") {
+ conditionMessage = message
+ break
+ }
+ }
+ }
+
+ // Determine the appropriate action based on the upgrade state
+ switch upgradeState {
+ case "":
+ log.Printf("Upgrade has not started yet...")
+ case "Partial":
+ log.Printf("Upgrade is in progress. Conditions: %v", conditionMessage)
+ case "Completed":
+ log.Printf("Upgrade complete!")
+ return nil
+ case "Failed":
+ log.Printf("Upgrade failed! Conditions: %v", conditionMessage)
+ return &upgradeError{err: fmt.Errorf("upgrade failed")}
+ default:
+ log.Printf("Unknown upgrade state: %s", upgradeState)
+ }
+
+ // Wait before the next poll attempt
+ time.Sleep(upgradeDelay * time.Second)
+ }
+
+ return fmt.Errorf("upgrade is still in progress, failed to finish within max wait attempts")
+}
+
+// patchVersionConfig updates the version config to the desired version to initiate an upgrade
+func patchVersionConfig(ctx context.Context, client *openshiftclient.Client, channel string, image string, version string) error {
+ clusterVersionConfing := configv1.ClusterVersion{
+ TypeMeta: v1.TypeMeta{},
not needed to define
Can you also try formatting the files with gofumpt? https://github.com/mvdan/gofumpt it will clean up some of the more nit picky things
/hold
@@ -0,0 +1,639 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "log"
+ "strconv"
+ "strings"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "os"
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+ "time"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+/*
+- before all create clients
+- test cluster creation
+- test cluster upgrade
+- test cluster migration<
+ - test apply manifests
+*/
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ rosaProvider, err := rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ err = rosaProvider.DeleteCluster(ctx, &rosaprovider.DeleteClusterOptions{
+ ClusterName: testRosaCluster.name,
+ WorkingDir: testRosaCluster.reportDir,
+ STS: true,
+ DeleteOidcConfigID: true,
+ })
+ Expect(err).Should(BeNil(), "failed to delete rosa cluster")
+ }
+ })
+
+ It("rosa cluster is upgraded to 4.15.8 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_15, image4_15, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.15.8 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.15.8-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster is upgraded to 4.16.0-rc.0 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_16, image4_16, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.16.0-rc.0 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.16.0-rc.0-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster migrated from sdn to ovn successfully", sdnToOvn, func(ctx context.Context) {
+ err := addIntenalTestingAnnotation(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = patchNetworkConfig(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = checkMigrationStatus(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+
+ })
+ It("rosa cluster has no critical alerts firing post sdn to ovn migration", postMigrationCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+})
+
+// queryPrometheusAlerts queries prometheus for alerts and provides a count for critical and warning alerts
+func queryPrometheusAlerts(ctx context.Context, client *openshiftclient.Client, logFilename string) (int, int, error) {
+ criticalAlertCount, warningAlertCount := 0, 0
+ alerts := ""
+
+ type metric struct {
+ AlertName string `json:"alertname"`
+ AlertState string `json:"alertstate"`
+ Condition string `json:"condition"`
+ Endpoint string `json:"endpoint"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Severity string `json:"severity"`
+ }
+
+ prometheusClient, _ := prometheusclient.New(ctx, client)
+ vector, err := prometheusClient.InstantQuery(ctx, "ALERTS{alertstate!=\"pending\",alertname!=\"Watchdog\"}")
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to query prometheus: %v", err)
+ }
+
+ for _, model := range vector {
+ metric := metric{}
+
+ metricEncoded, err := json.Marshal(model.Metric)
+ if err != nil {
+ continue
+ }
+
+ err = json.Unmarshal(metricEncoded, &metric)
+ if err != nil {
+ continue
+ }
+
+ alerts += fmt.Sprintf("Since: %s : %+v\n", time.Unix(model.Timestamp.Unix(), 0), metric)
+
+ switch model.Metric["severity"] {
+ case "critical":
+ criticalAlertCount += 1
+ case "warning":
+ warningAlertCount += 1
+ }
+ }
+
+ if alerts != "" {
+ if err = os.WriteFile(logFilename, []byte(alerts), os.FileMode(0o644)); err != nil {
+ return criticalAlertCount, warningAlertCount, fmt.Errorf("failed to write prometheus alerts to file: %v", err)
+ }
+ }
+
+ return criticalAlertCount, warningAlertCount, nil
+}
+
+// getEnvVar returns the env variable value and if unset returns default provided
+func getEnvVar(key, value string) string {
+ result, exist := os.LookupEnv(key)
+ if exist {
+ return result
+ }
+ return value
+}
+
+// osdClusterReadyHealthCheck verifies the osd-cluster-ready health check job is passing
+func osdClusterReadyHealthCheck(ctx context.Context, clusterClient *openshiftclient.Client, action, reportDir string) error {
can this reuse this function from osde2e-common? https://github.com/openshift/osde2e-common/blob/b7010c1e369cc51ae0e27231271409b016b53b2d/pkg/clients/openshift/healthcheck.go#L23
@@ -0,0 +1,639 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "log"
+ "strconv"
+ "strings"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "os"
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+ "time"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+/*
+- before all create clients
+- test cluster creation
+- test cluster upgrade
+- test cluster migration<
+ - test apply manifests
+*/
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ rosaProvider, err := rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ err = rosaProvider.DeleteCluster(ctx, &rosaprovider.DeleteClusterOptions{
+ ClusterName: testRosaCluster.name,
+ WorkingDir: testRosaCluster.reportDir,
+ STS: true,
+ DeleteOidcConfigID: true,
+ })
+ Expect(err).Should(BeNil(), "failed to delete rosa cluster")
+ }
+ })
+
+ It("rosa cluster is upgraded to 4.15.8 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_15, image4_15, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.15.8 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.15.8-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster is upgraded to 4.16.0-rc.0 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_16, image4_16, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.16.0-rc.0 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.16.0-rc.0-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster migrated from sdn to ovn successfully", sdnToOvn, func(ctx context.Context) {
+ err := addIntenalTestingAnnotation(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = patchNetworkConfig(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = checkMigrationStatus(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+
+ })
+ It("rosa cluster has no critical alerts firing post sdn to ovn migration", postMigrationCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+})
+
+// queryPrometheusAlerts queries prometheus for alerts and provides a count for critical and warning alerts
+func queryPrometheusAlerts(ctx context.Context, client *openshiftclient.Client, logFilename string) (int, int, error) {
+ criticalAlertCount, warningAlertCount := 0, 0
+ alerts := ""
+
+ type metric struct {
+ AlertName string `json:"alertname"`
+ AlertState string `json:"alertstate"`
+ Condition string `json:"condition"`
+ Endpoint string `json:"endpoint"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Severity string `json:"severity"`
+ }
+
+ prometheusClient, _ := prometheusclient.New(ctx, client)
+ vector, err := prometheusClient.InstantQuery(ctx, "ALERTS{alertstate!=\"pending\",alertname!=\"Watchdog\"}")
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to query prometheus: %v", err)
+ }
+
+ for _, model := range vector {
+ metric := metric{}
+
+ metricEncoded, err := json.Marshal(model.Metric)
+ if err != nil {
+ continue
+ }
+
+ err = json.Unmarshal(metricEncoded, &metric)
+ if err != nil {
+ continue
+ }
+
+ alerts += fmt.Sprintf("Since: %s : %+v\n", time.Unix(model.Timestamp.Unix(), 0), metric)
+
+ switch model.Metric["severity"] {
+ case "critical":
+ criticalAlertCount += 1
+ case "warning":
+ warningAlertCount += 1
+ }
+ }
+
+ if alerts != "" {
+ if err = os.WriteFile(logFilename, []byte(alerts), os.FileMode(0o644)); err != nil {
+ return criticalAlertCount, warningAlertCount, fmt.Errorf("failed to write prometheus alerts to file: %v", err)
+ }
+ }
+
+ return criticalAlertCount, warningAlertCount, nil
+}
+
+// getEnvVar returns the env variable value and if unset returns default provided
+func getEnvVar(key, value string) string {
+ result, exist := os.LookupEnv(key)
+ if exist {
+ return result
+ }
+ return value
+}
+
+// osdClusterReadyHealthCheck verifies the osd-cluster-ready health check job is passing
+func osdClusterReadyHealthCheck(ctx context.Context, clusterClient *openshiftclient.Client, action, reportDir string) error {
It is being used below! https://github.com/openshift/osde2e/pull/2668/files#diff-17513b7abb891bbe82b939440dcf60b8b75379fa1bf5d06538f64dbcf4ea76e4R324 This is just a way to kick off a new job based on the already completed one
@@ -0,0 +1,639 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "log"
+ "strconv"
+ "strings"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "os"
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+ "time"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+/*
+- before all create clients
+- test cluster creation
+- test cluster upgrade
+- test cluster migration<
+ - test apply manifests
+*/
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ rosaProvider, err := rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ err = rosaProvider.DeleteCluster(ctx, &rosaprovider.DeleteClusterOptions{
+ ClusterName: testRosaCluster.name,
+ WorkingDir: testRosaCluster.reportDir,
+ STS: true,
+ DeleteOidcConfigID: true,
+ })
+ Expect(err).Should(BeNil(), "failed to delete rosa cluster")
+ }
+ })
+
+ It("rosa cluster is upgraded to 4.15.8 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_15, image4_15, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.15.8 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.15.8-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster is upgraded to 4.16.0-rc.0 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_16, image4_16, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.16.0-rc.0 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.16.0-rc.0-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster migrated from sdn to ovn successfully", sdnToOvn, func(ctx context.Context) {
+ err := addIntenalTestingAnnotation(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = patchNetworkConfig(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = checkMigrationStatus(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+
+ })
+ It("rosa cluster has no critical alerts firing post sdn to ovn migration", postMigrationCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+})
+
+// queryPrometheusAlerts queries prometheus for alerts and provides a count for critical and warning alerts
+func queryPrometheusAlerts(ctx context.Context, client *openshiftclient.Client, logFilename string) (int, int, error) {
+ criticalAlertCount, warningAlertCount := 0, 0
+ alerts := ""
+
+ type metric struct {
+ AlertName string `json:"alertname"`
+ AlertState string `json:"alertstate"`
+ Condition string `json:"condition"`
+ Endpoint string `json:"endpoint"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Severity string `json:"severity"`
+ }
+
+ prometheusClient, _ := prometheusclient.New(ctx, client)
+ vector, err := prometheusClient.InstantQuery(ctx, "ALERTS{alertstate!=\"pending\",alertname!=\"Watchdog\"}")
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to query prometheus: %v", err)
+ }
+
+ for _, model := range vector {
+ metric := metric{}
+
+ metricEncoded, err := json.Marshal(model.Metric)
+ if err != nil {
+ continue
+ }
+
+ err = json.Unmarshal(metricEncoded, &metric)
+ if err != nil {
+ continue
+ }
+
+ alerts += fmt.Sprintf("Since: %s : %+v\n", time.Unix(model.Timestamp.Unix(), 0), metric)
+
+ switch model.Metric["severity"] {
+ case "critical":
+ criticalAlertCount += 1
+ case "warning":
+ warningAlertCount += 1
+ }
+ }
+
+ if alerts != "" {
+ if err = os.WriteFile(logFilename, []byte(alerts), os.FileMode(0o644)); err != nil {
+ return criticalAlertCount, warningAlertCount, fmt.Errorf("failed to write prometheus alerts to file: %v", err)
+ }
+ }
+
+ return criticalAlertCount, warningAlertCount, nil
+}
+
+// getEnvVar returns the env variable value and if unset returns default provided
+func getEnvVar(key, value string) string {
+ result, exist := os.LookupEnv(key)
+ if exist {
+ return result
+ }
+ return value
+}
+
+// osdClusterReadyHealthCheck verifies the osd-cluster-ready health check job is passing
+func osdClusterReadyHealthCheck(ctx context.Context, clusterClient *openshiftclient.Client, action, reportDir string) error {
+ var (
+ err error
+ job batchv1.Job
+ )
+
+ if err = clusterClient.Get(ctx, osdClusterReadyJobName, "openshift-monitoring", &job); err != nil {
+ return fmt.Errorf("failed to get existing %s job %v", osdClusterReadyJobName, err)
+ }
+
+ newJob := &batchv1.Job{
+ ObjectMeta: metav1.ObjectMeta{
+ GenerateName: osdClusterReadyJobName,
+ Annotations: job.Annotations,
+ Namespace: job.Namespace,
+ },
+ Spec: job.Spec,
+ }
+
+ newJob.Spec.Selector.MatchLabels = map[string]string{}
+ newJob.Spec.Template.ObjectMeta.Name = newJob.GetGenerateName()
+ newJob.Spec.Template.ObjectMeta.Labels = map[string]string{}
+ newJob.Spec.Template.Spec.Containers[0].Name = newJob.GetGenerateName()
+
+ if err = clusterClient.Create(ctx, newJob); err != nil {
+ return fmt.Errorf("failed to create %s job: %v", newJob.GetName(), err)
+ }
+
+ defer func() {
+ _ = clusterClient.Delete(ctx, newJob)
+ }()
+
+ return clusterClient.OSDClusterHealthy(ctx, newJob.GetName(), reportDir, osdClusterReadyJobTimeout)
+}
+
+// getKubernetesDynamicClient returns the kubernetes dynamic client
+func getKubernetesDynamicClient(client *openshiftclient.Client) (*dynamic.DynamicClient, error) {
+ dynamicClient, err := dynamic.NewForConfig(client.GetConfig())
+ if err != nil {
+ return nil, fmt.Errorf("failed to create kubernetes dynamic client: %w", err)
+ }
+ return dynamicClient, nil
+}
+
+type upgradeError struct {
+ err error
+}
+
+// Error returns the formatted error message when upgradeError is invoked
+func (e *upgradeError) Error() string {
+ return fmt.Sprintf("osd upgrade failed: %v", e.err)
+}
+
+func getOpenshiftConfig(ctx context.Context, dynamicClient *dynamic.DynamicClient, resource string, name string) (*unstructured.Unstructured, error) {
+ gvr := schema.GroupVersionResource{
+ Group: "config.openshift.io",
+ Version: "v1",
+ Resource: resource,
+ }
+ return dynamicClient.Resource(gvr).Get(ctx, name, metav1.GetOptions{})
+}
+
+// checkMigrationStatus probes the status of the SDN-to-OVN migration
+func checkMigrationStatus(ctx context.Context, client *openshiftclient.Client) error {
+ var (
+ dynamicClient *dynamic.DynamicClient
+ err error
+ )
+
+ if dynamicClient, err = getKubernetesDynamicClient(client); err != nil {
+ return &upgradeError{err: err}
+ }
+ for i := 1; i <= upgradeMaxAttempts; i++ {
+ // Get the current network configuration
+ networkConfig, err := getOpenshiftConfig(ctx, dynamicClient, "networks", "cluster")
+ if err != nil {
+ return fmt.Errorf("failed to get network configuration: %v", err)
+ }
+
+ // Extract the status conditions
+ status, found, err := unstructured.NestedMap(networkConfig.Object, "status")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find status in network configuration: %v", err)
+ }
+
+ conditions, found, err := unstructured.NestedSlice(status, "conditions")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find conditions in status: %v", err)
+ }
+
+ // Check for the migration condition
+ migrationInProgress := false
+ for _, cond := range conditions {
+ conditionMap, ok := cond.(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("invalid type for condition entry")
+ }
+
+ conditionType, found, err := unstructured.NestedString(conditionMap, "type")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition type: %v", err)
+ }
+
+ if conditionType == "NetworkTypeMigrationInProgress" {
+ status, found, err := unstructured.NestedString(conditionMap, "status")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition status: %v", err)
+ }
+
+ reason, found, err := unstructured.NestedString(conditionMap, "reason")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition reason: %v", err)
+ }
+
+ // Check if the migration is in progress
+ if status == "True" && reason == "NetworkTypeMigrationStarted" {
+ migrationInProgress = true
+ break
+ }
+
+ // Check if the migration is complete
+ if status == "False" && reason == "NetworkTypeMigrationCompleted" {
+ fmt.Println("Network migration completed successfully!")
+ return nil
+ }
+ }
+ }
+
+ if migrationInProgress {
+ fmt.Println("Network migration is still in progress...")
+ } else {
+ fmt.Println("Migration status is unknown or not in progress.")
+ }
+
+ time.Sleep(upgradeDelay * time.Second)
+ }
+
+ return fmt.Errorf("network migration is still in progress after %d attempts", upgradeMaxAttempts)
+
+}
+
+// checkUpgradeStatus probes the status of the cluster upgrade
+func checkUpgradeStatus(ctx context.Context, client *openshiftclient.Client, upgradeVersion string) error {
similarly, could this block reuse the function here? https://github.com/openshift/osde2e-common/blob/b7010c1e369cc51ae0e27231271409b016b53b2d/pkg/openshift/osd/upgrade.go#L223
@@ -0,0 +1,639 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "log"
+ "strconv"
+ "strings"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "os"
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+ "time"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+/*
+- before all create clients
+- test cluster creation
+- test cluster upgrade
+- test cluster migration<
+ - test apply manifests
+*/
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ rosaProvider, err := rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ err = rosaProvider.DeleteCluster(ctx, &rosaprovider.DeleteClusterOptions{
+ ClusterName: testRosaCluster.name,
+ WorkingDir: testRosaCluster.reportDir,
+ STS: true,
+ DeleteOidcConfigID: true,
+ })
+ Expect(err).Should(BeNil(), "failed to delete rosa cluster")
+ }
+ })
+
+ It("rosa cluster is upgraded to 4.15.8 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_15, image4_15, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.15.8 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.15.8-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster is upgraded to 4.16.0-rc.0 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_16, image4_16, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.16.0-rc.0 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.16.0-rc.0-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster migrated from sdn to ovn successfully", sdnToOvn, func(ctx context.Context) {
+ err := addIntenalTestingAnnotation(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = patchNetworkConfig(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = checkMigrationStatus(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+
+ })
+ It("rosa cluster has no critical alerts firing post sdn to ovn migration", postMigrationCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+})
+
+// queryPrometheusAlerts queries prometheus for alerts and provides a count for critical and warning alerts
+func queryPrometheusAlerts(ctx context.Context, client *openshiftclient.Client, logFilename string) (int, int, error) {
+ criticalAlertCount, warningAlertCount := 0, 0
+ alerts := ""
+
+ type metric struct {
+ AlertName string `json:"alertname"`
+ AlertState string `json:"alertstate"`
+ Condition string `json:"condition"`
+ Endpoint string `json:"endpoint"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Severity string `json:"severity"`
+ }
+
+ prometheusClient, _ := prometheusclient.New(ctx, client)
+ vector, err := prometheusClient.InstantQuery(ctx, "ALERTS{alertstate!=\"pending\",alertname!=\"Watchdog\"}")
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to query prometheus: %v", err)
+ }
+
+ for _, model := range vector {
+ metric := metric{}
+
+ metricEncoded, err := json.Marshal(model.Metric)
+ if err != nil {
+ continue
+ }
+
+ err = json.Unmarshal(metricEncoded, &metric)
+ if err != nil {
+ continue
+ }
+
+ alerts += fmt.Sprintf("Since: %s : %+v\n", time.Unix(model.Timestamp.Unix(), 0), metric)
+
+ switch model.Metric["severity"] {
+ case "critical":
+ criticalAlertCount += 1
+ case "warning":
+ warningAlertCount += 1
+ }
+ }
+
+ if alerts != "" {
+ if err = os.WriteFile(logFilename, []byte(alerts), os.FileMode(0o644)); err != nil {
+ return criticalAlertCount, warningAlertCount, fmt.Errorf("failed to write prometheus alerts to file: %v", err)
+ }
+ }
+
+ return criticalAlertCount, warningAlertCount, nil
+}
+
+// getEnvVar returns the env variable value and if unset returns default provided
+func getEnvVar(key, value string) string {
+ result, exist := os.LookupEnv(key)
+ if exist {
+ return result
+ }
+ return value
+}
+
+// osdClusterReadyHealthCheck verifies the osd-cluster-ready health check job is passing
+func osdClusterReadyHealthCheck(ctx context.Context, clusterClient *openshiftclient.Client, action, reportDir string) error {
+ var (
+ err error
+ job batchv1.Job
+ )
+
+ if err = clusterClient.Get(ctx, osdClusterReadyJobName, "openshift-monitoring", &job); err != nil {
+ return fmt.Errorf("failed to get existing %s job %v", osdClusterReadyJobName, err)
+ }
+
+ newJob := &batchv1.Job{
+ ObjectMeta: metav1.ObjectMeta{
+ GenerateName: osdClusterReadyJobName,
+ Annotations: job.Annotations,
+ Namespace: job.Namespace,
+ },
+ Spec: job.Spec,
+ }
+
+ newJob.Spec.Selector.MatchLabels = map[string]string{}
+ newJob.Spec.Template.ObjectMeta.Name = newJob.GetGenerateName()
+ newJob.Spec.Template.ObjectMeta.Labels = map[string]string{}
+ newJob.Spec.Template.Spec.Containers[0].Name = newJob.GetGenerateName()
+
+ if err = clusterClient.Create(ctx, newJob); err != nil {
+ return fmt.Errorf("failed to create %s job: %v", newJob.GetName(), err)
+ }
+
+ defer func() {
+ _ = clusterClient.Delete(ctx, newJob)
+ }()
+
+ return clusterClient.OSDClusterHealthy(ctx, newJob.GetName(), reportDir, osdClusterReadyJobTimeout)
+}
+
+// getKubernetesDynamicClient returns the kubernetes dynamic client
+func getKubernetesDynamicClient(client *openshiftclient.Client) (*dynamic.DynamicClient, error) {
+ dynamicClient, err := dynamic.NewForConfig(client.GetConfig())
+ if err != nil {
+ return nil, fmt.Errorf("failed to create kubernetes dynamic client: %w", err)
+ }
+ return dynamicClient, nil
+}
+
+type upgradeError struct {
+ err error
+}
+
+// Error returns the formatted error message when upgradeError is invoked
+func (e *upgradeError) Error() string {
+ return fmt.Sprintf("osd upgrade failed: %v", e.err)
+}
+
+func getOpenshiftConfig(ctx context.Context, dynamicClient *dynamic.DynamicClient, resource string, name string) (*unstructured.Unstructured, error) {
+ gvr := schema.GroupVersionResource{
+ Group: "config.openshift.io",
+ Version: "v1",
+ Resource: resource,
+ }
+ return dynamicClient.Resource(gvr).Get(ctx, name, metav1.GetOptions{})
+}
+
+// checkMigrationStatus probes the status of the SDN-to-OVN migration
+func checkMigrationStatus(ctx context.Context, client *openshiftclient.Client) error {
+ var (
+ dynamicClient *dynamic.DynamicClient
+ err error
+ )
+
+ if dynamicClient, err = getKubernetesDynamicClient(client); err != nil {
+ return &upgradeError{err: err}
+ }
+ for i := 1; i <= upgradeMaxAttempts; i++ {
+ // Get the current network configuration
+ networkConfig, err := getOpenshiftConfig(ctx, dynamicClient, "networks", "cluster")
+ if err != nil {
+ return fmt.Errorf("failed to get network configuration: %v", err)
+ }
+
+ // Extract the status conditions
+ status, found, err := unstructured.NestedMap(networkConfig.Object, "status")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find status in network configuration: %v", err)
+ }
+
+ conditions, found, err := unstructured.NestedSlice(status, "conditions")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find conditions in status: %v", err)
+ }
+
+ // Check for the migration condition
+ migrationInProgress := false
+ for _, cond := range conditions {
+ conditionMap, ok := cond.(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("invalid type for condition entry")
+ }
+
+ conditionType, found, err := unstructured.NestedString(conditionMap, "type")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition type: %v", err)
+ }
+
+ if conditionType == "NetworkTypeMigrationInProgress" {
+ status, found, err := unstructured.NestedString(conditionMap, "status")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition status: %v", err)
+ }
+
+ reason, found, err := unstructured.NestedString(conditionMap, "reason")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition reason: %v", err)
+ }
+
+ // Check if the migration is in progress
+ if status == "True" && reason == "NetworkTypeMigrationStarted" {
+ migrationInProgress = true
+ break
+ }
+
+ // Check if the migration is complete
+ if status == "False" && reason == "NetworkTypeMigrationCompleted" {
+ fmt.Println("Network migration completed successfully!")
+ return nil
+ }
+ }
+ }
+
+ if migrationInProgress {
+ fmt.Println("Network migration is still in progress...")
+ } else {
+ fmt.Println("Migration status is unknown or not in progress.")
+ }
+
+ time.Sleep(upgradeDelay * time.Second)
+ }
+
+ return fmt.Errorf("network migration is still in progress after %d attempts", upgradeMaxAttempts)
+
+}
+
+// checkUpgradeStatus probes the status of the cluster upgrade
+func checkUpgradeStatus(ctx context.Context, client *openshiftclient.Client, upgradeVersion string) error {
+ var (
+ conditionMessage string
+ dynamicClient *dynamic.DynamicClient
+ upgradeState string
+ err error
+ )
+
+ for i := 1; i <= upgradeMaxAttempts; i++ {
+ if dynamicClient, err = getKubernetesDynamicClient(client); err != nil {
+ log.Printf("here")
+ time.Sleep(upgradeDelay * time.Second)
+ continue
+ }
+ // Get the current cluster version configuration
+ upgradeConfig, err := getOpenshiftConfig(ctx, dynamicClient, "clusterversions", "version")
+ if err != nil {
+ log.Printf("Failed to get cluster version config: %v", err)
+ time.Sleep(upgradeDelay * time.Second)
+ continue
+ }
+
+ // Extract the status map from the configuration
+ status, found, err := unstructured.NestedMap(upgradeConfig.Object, "status")
+ if err != nil || !found {
+ log.Printf("Failed to find status in cluster version config: %v", err)
+ time.Sleep(upgradeDelay * time.Second)
+ continue
+ }
+
+ // Extract the history slice from the status
+ histories, found, err := unstructured.NestedSlice(status, "history")
+ if err != nil || !found {
+ log.Printf("Failed to find history in status")
+ time.Sleep(upgradeDelay * time.Second)
+ continue
+ }
+
+ for _, h := range histories {
+ historyMap, ok := h.(map[string]interface{})
+ if !ok {
+ err = fmt.Errorf("invalid type for history entry")
+ log.Printf(err.Error(), "Invalid history entry type")
+ continue
+ }
+
+ // Extract the version for each history entry
+ version, found, err := unstructured.NestedString(historyMap, "version")
+ if err != nil || !found {
+ log.Printf("Failed to find version in history entry")
+ continue
+ }
+
+ // Check if the version matches the desired upgrade version
+ if version == upgradeVersion {
+ // Extract the state for the matching version
+ state, found, err := unstructured.NestedString(historyMap, "state")
+ if err != nil || !found {
+ log.Printf("Failed to find state in history entry")
+ continue
+ }
+
+ upgradeState = state
+ break
+ }
+ }
+
+ // Extract the conditions from the status
+ conditions, found, err := unstructured.NestedSlice(status, "conditions")
+ if err != nil || !found {
+ log.Printf("Failed to find conditions in status")
+ } else {
+ // Filter for the condition message that starts with "Working towards"
+ for _, cond := range conditions {
+ conditionMap, ok := cond.(map[string]interface{})
+ if !ok {
+ err = fmt.Errorf("invalid type for condition entry")
+ log.Printf(err.Error(), "Invalid condition entry type")
+ continue
+ }
+
+ // Extract the condition message
+ message, found, err := unstructured.NestedString(conditionMap, "message")
+ if err != nil || !found {
+ continue
+ }
+
+ // Check if the message starts with "Working towards"
+ if strings.HasPrefix(message, "Working towards") {
+ conditionMessage = message
+ break
+ }
+ }
+ }
+
+ // Determine the appropriate action based on the upgrade state
+ switch upgradeState {
+ case "":
+ log.Printf("Upgrade has not started yet...")
+ case "Partial":
+ log.Printf("Upgrade is in progress. Conditions: %v", conditionMessage)
+ case "Completed":
+ log.Printf("Upgrade complete!")
+ return nil
+ case "Failed":
+ log.Printf("Upgrade failed! Conditions: %v", conditionMessage)
+ return &upgradeError{err: fmt.Errorf("upgrade failed")}
+ default:
+ log.Printf("Unknown upgrade state: %s", upgradeState)
+ }
+
+ // Wait before the next poll attempt
+ time.Sleep(upgradeDelay * time.Second)
+ }
+
+ return fmt.Errorf("upgrade is still in progress, failed to finish within max wait attempts")
+}
+
+// patchVersionConfig updates the version config to the desired version to initiate an upgrade
+func patchVersionConfig(ctx context.Context, client *openshiftclient.Client, channel string, image string, version string) error {
+ clusterVersionConfing := configv1.ClusterVersion{
+ TypeMeta: v1.TypeMeta{},
+ ObjectMeta: v1.ObjectMeta{Name: "version"}}
+
+ mergePatch, err := json.Marshal(map[string]interface{}{
+ "spec": map[string]interface{}{
+ "channel": channel,
+ "desiredUpdate": map[string]interface{}{
+ "version": version,
+ "image": image,
+ "force": true,
+ },
+ },
+ })
+
+ if err != nil {
+ panic(err)
+ }
+
+ if err = client.Patch(
+ ctx,
+ &clusterVersionConfing,
+ k8s.Patch{PatchType: types.MergePatchType, Data: mergePatch},
+ ); err != nil {
+ panic(err)
+ }
+ return nil
+
+}
+
+// patchNetworkConfig updates network type to OVN
+func patchNetworkConfig(ctx context.Context, client *openshiftclient.Client) error {
+
+ networkConfig := configv1.Network{ObjectMeta: v1.ObjectMeta{Name: "cluster"}}
+
+ mergePatch, err := json.Marshal(map[string]interface{}{
+ "metadata": map[string]interface{}{
+ "annotations": map[string]interface{}{
+ "network.openshift.io/network-type-migration": "",
+ },
+ },
+ "spec": map[string]interface{}{
+ "networkType": "OVNKubernetes",
+ },
+ })
+
+ if err != nil {
+ panic(err)
+ }
+
+ if err = client.Patch(
+ ctx,
+ &networkConfig,
+ k8s.Patch{PatchType: types.MergePatchType, Data: mergePatch},
+ ); err != nil {
+ panic(err)
+ }
+ return nil
+}
+
+// addAnnotation adds the internal testing annotation to the network config
+func addIntenalTestingAnnotation(ctx context.Context, client *openshiftclient.Client) error {
+
+ networkConfig := configv1.Network{ObjectMeta: v1.ObjectMeta{Name: "cluster"}}
+
+ mergePatch, err := json.Marshal(map[string]interface{}{
+ "metadata": map[string]interface{}{
+ "annotations": map[string]interface{}{
+ "unsupported-red-hat-internal-testing": "true",
+ },
+ },
+ })
+
+ if err != nil {
+ panic(err)
+ }
+
+ if err = client.Patch(
+ ctx,
+ &networkConfig,
+ k8s.Patch{PatchType: types.MergePatchType, Data: mergePatch},
+ ); err != nil {
+ panic(err)
these panics should return err instead, there are a few uses of it in these helper functions
@@ -0,0 +1,639 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "log"
+ "strconv"
+ "strings"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "os"
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+ "time"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+/*
+- before all create clients
+- test cluster creation
+- test cluster upgrade
+- test cluster migration<
+ - test apply manifests
+*/
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ rosaProvider, err := rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ err = rosaProvider.DeleteCluster(ctx, &rosaprovider.DeleteClusterOptions{
+ ClusterName: testRosaCluster.name,
+ WorkingDir: testRosaCluster.reportDir,
+ STS: true,
+ DeleteOidcConfigID: true,
+ })
+ Expect(err).Should(BeNil(), "failed to delete rosa cluster")
+ }
+ })
+
+ It("rosa cluster is upgraded to 4.15.8 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_15, image4_15, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.15.8 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.15.8-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster is upgraded to 4.16.0-rc.0 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_16, image4_16, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.16.0-rc.0 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.16.0-rc.0-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster migrated from sdn to ovn successfully", sdnToOvn, func(ctx context.Context) {
+ err := addIntenalTestingAnnotation(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = patchNetworkConfig(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = checkMigrationStatus(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+
+ })
+ It("rosa cluster has no critical alerts firing post sdn to ovn migration", postMigrationCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+})
+
+// queryPrometheusAlerts queries prometheus for alerts and provides a count for critical and warning alerts
+func queryPrometheusAlerts(ctx context.Context, client *openshiftclient.Client, logFilename string) (int, int, error) {
+ criticalAlertCount, warningAlertCount := 0, 0
+ alerts := ""
+
+ type metric struct {
+ AlertName string `json:"alertname"`
+ AlertState string `json:"alertstate"`
+ Condition string `json:"condition"`
+ Endpoint string `json:"endpoint"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Severity string `json:"severity"`
+ }
+
+ prometheusClient, _ := prometheusclient.New(ctx, client)
+ vector, err := prometheusClient.InstantQuery(ctx, "ALERTS{alertstate!=\"pending\",alertname!=\"Watchdog\"}")
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to query prometheus: %v", err)
+ }
+
+ for _, model := range vector {
+ metric := metric{}
+
+ metricEncoded, err := json.Marshal(model.Metric)
+ if err != nil {
+ continue
+ }
+
+ err = json.Unmarshal(metricEncoded, &metric)
+ if err != nil {
+ continue
+ }
+
+ alerts += fmt.Sprintf("Since: %s : %+v\n", time.Unix(model.Timestamp.Unix(), 0), metric)
+
+ switch model.Metric["severity"] {
+ case "critical":
+ criticalAlertCount += 1
+ case "warning":
+ warningAlertCount += 1
+ }
+ }
+
+ if alerts != "" {
+ if err = os.WriteFile(logFilename, []byte(alerts), os.FileMode(0o644)); err != nil {
+ return criticalAlertCount, warningAlertCount, fmt.Errorf("failed to write prometheus alerts to file: %v", err)
+ }
+ }
+
+ return criticalAlertCount, warningAlertCount, nil
+}
+
+// getEnvVar returns the env variable value and if unset returns default provided
+func getEnvVar(key, value string) string {
+ result, exist := os.LookupEnv(key)
+ if exist {
+ return result
+ }
+ return value
+}
+
+// osdClusterReadyHealthCheck verifies the osd-cluster-ready health check job is passing
+func osdClusterReadyHealthCheck(ctx context.Context, clusterClient *openshiftclient.Client, action, reportDir string) error {
+ var (
+ err error
+ job batchv1.Job
+ )
+
+ if err = clusterClient.Get(ctx, osdClusterReadyJobName, "openshift-monitoring", &job); err != nil {
+ return fmt.Errorf("failed to get existing %s job %v", osdClusterReadyJobName, err)
+ }
+
+ newJob := &batchv1.Job{
+ ObjectMeta: metav1.ObjectMeta{
+ GenerateName: osdClusterReadyJobName,
+ Annotations: job.Annotations,
+ Namespace: job.Namespace,
+ },
+ Spec: job.Spec,
+ }
+
+ newJob.Spec.Selector.MatchLabels = map[string]string{}
+ newJob.Spec.Template.ObjectMeta.Name = newJob.GetGenerateName()
+ newJob.Spec.Template.ObjectMeta.Labels = map[string]string{}
+ newJob.Spec.Template.Spec.Containers[0].Name = newJob.GetGenerateName()
+
+ if err = clusterClient.Create(ctx, newJob); err != nil {
+ return fmt.Errorf("failed to create %s job: %v", newJob.GetName(), err)
+ }
+
+ defer func() {
+ _ = clusterClient.Delete(ctx, newJob)
+ }()
+
+ return clusterClient.OSDClusterHealthy(ctx, newJob.GetName(), reportDir, osdClusterReadyJobTimeout)
+}
+
+// getKubernetesDynamicClient returns the kubernetes dynamic client
+func getKubernetesDynamicClient(client *openshiftclient.Client) (*dynamic.DynamicClient, error) {
+ dynamicClient, err := dynamic.NewForConfig(client.GetConfig())
+ if err != nil {
+ return nil, fmt.Errorf("failed to create kubernetes dynamic client: %w", err)
+ }
+ return dynamicClient, nil
+}
+
+type upgradeError struct {
+ err error
+}
+
+// Error returns the formatted error message when upgradeError is invoked
+func (e *upgradeError) Error() string {
+ return fmt.Sprintf("osd upgrade failed: %v", e.err)
+}
+
+func getOpenshiftConfig(ctx context.Context, dynamicClient *dynamic.DynamicClient, resource string, name string) (*unstructured.Unstructured, error) {
+ gvr := schema.GroupVersionResource{
+ Group: "config.openshift.io",
+ Version: "v1",
+ Resource: resource,
+ }
+ return dynamicClient.Resource(gvr).Get(ctx, name, metav1.GetOptions{})
+}
+
+// checkMigrationStatus probes the status of the SDN-to-OVN migration
+func checkMigrationStatus(ctx context.Context, client *openshiftclient.Client) error {
+ var (
+ dynamicClient *dynamic.DynamicClient
+ err error
+ )
+
+ if dynamicClient, err = getKubernetesDynamicClient(client); err != nil {
+ return &upgradeError{err: err}
+ }
+ for i := 1; i <= upgradeMaxAttempts; i++ {
+ // Get the current network configuration
+ networkConfig, err := getOpenshiftConfig(ctx, dynamicClient, "networks", "cluster")
+ if err != nil {
+ return fmt.Errorf("failed to get network configuration: %v", err)
+ }
+
+ // Extract the status conditions
+ status, found, err := unstructured.NestedMap(networkConfig.Object, "status")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find status in network configuration: %v", err)
+ }
+
+ conditions, found, err := unstructured.NestedSlice(status, "conditions")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find conditions in status: %v", err)
+ }
+
+ // Check for the migration condition
+ migrationInProgress := false
+ for _, cond := range conditions {
+ conditionMap, ok := cond.(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("invalid type for condition entry")
+ }
+
+ conditionType, found, err := unstructured.NestedString(conditionMap, "type")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition type: %v", err)
+ }
+
+ if conditionType == "NetworkTypeMigrationInProgress" {
+ status, found, err := unstructured.NestedString(conditionMap, "status")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition status: %v", err)
+ }
+
+ reason, found, err := unstructured.NestedString(conditionMap, "reason")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition reason: %v", err)
+ }
+
+ // Check if the migration is in progress
+ if status == "True" && reason == "NetworkTypeMigrationStarted" {
+ migrationInProgress = true
+ break
+ }
+
+ // Check if the migration is complete
+ if status == "False" && reason == "NetworkTypeMigrationCompleted" {
+ fmt.Println("Network migration completed successfully!")
+ return nil
+ }
+ }
+ }
+
+ if migrationInProgress {
+ fmt.Println("Network migration is still in progress...")
+ } else {
+ fmt.Println("Migration status is unknown or not in progress.")
+ }
+
+ time.Sleep(upgradeDelay * time.Second)
+ }
+
+ return fmt.Errorf("network migration is still in progress after %d attempts", upgradeMaxAttempts)
+
+}
+
+// checkUpgradeStatus probes the status of the cluster upgrade
+func checkUpgradeStatus(ctx context.Context, client *openshiftclient.Client, upgradeVersion string) error {
If needed, we can extract some of that function out to deduplicate this
@@ -0,0 +1,639 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "log"
+ "strconv"
+ "strings"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "os"
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+ "time"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+/*
+- before all create clients
+- test cluster creation
+- test cluster upgrade
+- test cluster migration<
+ - test apply manifests
+*/
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ rosaProvider, err := rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ err = rosaProvider.DeleteCluster(ctx, &rosaprovider.DeleteClusterOptions{
+ ClusterName: testRosaCluster.name,
+ WorkingDir: testRosaCluster.reportDir,
+ STS: true,
+ DeleteOidcConfigID: true,
+ })
+ Expect(err).Should(BeNil(), "failed to delete rosa cluster")
+ }
+ })
+
+ It("rosa cluster is upgraded to 4.15.8 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_15, image4_15, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.15.8 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.15.8-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster is upgraded to 4.16.0-rc.0 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_16, image4_16, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.16.0-rc.0 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.16.0-rc.0-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster migrated from sdn to ovn successfully", sdnToOvn, func(ctx context.Context) {
+ err := addIntenalTestingAnnotation(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = patchNetworkConfig(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = checkMigrationStatus(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+
+ })
+ It("rosa cluster has no critical alerts firing post sdn to ovn migration", postMigrationCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+})
+
+// queryPrometheusAlerts queries prometheus for alerts and provides a count for critical and warning alerts
+func queryPrometheusAlerts(ctx context.Context, client *openshiftclient.Client, logFilename string) (int, int, error) {
+ criticalAlertCount, warningAlertCount := 0, 0
+ alerts := ""
+
+ type metric struct {
+ AlertName string `json:"alertname"`
+ AlertState string `json:"alertstate"`
+ Condition string `json:"condition"`
+ Endpoint string `json:"endpoint"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Severity string `json:"severity"`
+ }
+
+ prometheusClient, _ := prometheusclient.New(ctx, client)
+ vector, err := prometheusClient.InstantQuery(ctx, "ALERTS{alertstate!=\"pending\",alertname!=\"Watchdog\"}")
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to query prometheus: %v", err)
+ }
+
+ for _, model := range vector {
+ metric := metric{}
+
+ metricEncoded, err := json.Marshal(model.Metric)
+ if err != nil {
+ continue
+ }
+
+ err = json.Unmarshal(metricEncoded, &metric)
+ if err != nil {
+ continue
+ }
+
+ alerts += fmt.Sprintf("Since: %s : %+v\n", time.Unix(model.Timestamp.Unix(), 0), metric)
+
+ switch model.Metric["severity"] {
+ case "critical":
+ criticalAlertCount += 1
+ case "warning":
+ warningAlertCount += 1
+ }
+ }
+
+ if alerts != "" {
+ if err = os.WriteFile(logFilename, []byte(alerts), os.FileMode(0o644)); err != nil {
+ return criticalAlertCount, warningAlertCount, fmt.Errorf("failed to write prometheus alerts to file: %v", err)
+ }
+ }
+
+ return criticalAlertCount, warningAlertCount, nil
+}
+
+// getEnvVar returns the env variable value and if unset returns default provided
+func getEnvVar(key, value string) string {
+ result, exist := os.LookupEnv(key)
+ if exist {
+ return result
+ }
+ return value
+}
+
+// osdClusterReadyHealthCheck verifies the osd-cluster-ready health check job is passing
+func osdClusterReadyHealthCheck(ctx context.Context, clusterClient *openshiftclient.Client, action, reportDir string) error {
+ var (
+ err error
+ job batchv1.Job
+ )
+
+ if err = clusterClient.Get(ctx, osdClusterReadyJobName, "openshift-monitoring", &job); err != nil {
+ return fmt.Errorf("failed to get existing %s job %v", osdClusterReadyJobName, err)
+ }
+
+ newJob := &batchv1.Job{
+ ObjectMeta: metav1.ObjectMeta{
+ GenerateName: osdClusterReadyJobName,
+ Annotations: job.Annotations,
+ Namespace: job.Namespace,
+ },
+ Spec: job.Spec,
+ }
+
+ newJob.Spec.Selector.MatchLabels = map[string]string{}
+ newJob.Spec.Template.ObjectMeta.Name = newJob.GetGenerateName()
+ newJob.Spec.Template.ObjectMeta.Labels = map[string]string{}
+ newJob.Spec.Template.Spec.Containers[0].Name = newJob.GetGenerateName()
+
+ if err = clusterClient.Create(ctx, newJob); err != nil {
+ return fmt.Errorf("failed to create %s job: %v", newJob.GetName(), err)
+ }
+
+ defer func() {
+ _ = clusterClient.Delete(ctx, newJob)
+ }()
+
+ return clusterClient.OSDClusterHealthy(ctx, newJob.GetName(), reportDir, osdClusterReadyJobTimeout)
+}
+
+// getKubernetesDynamicClient returns the kubernetes dynamic client
+func getKubernetesDynamicClient(client *openshiftclient.Client) (*dynamic.DynamicClient, error) {
+ dynamicClient, err := dynamic.NewForConfig(client.GetConfig())
+ if err != nil {
+ return nil, fmt.Errorf("failed to create kubernetes dynamic client: %w", err)
+ }
+ return dynamicClient, nil
+}
+
+type upgradeError struct {
+ err error
+}
+
+// Error returns the formatted error message when upgradeError is invoked
+func (e *upgradeError) Error() string {
+ return fmt.Sprintf("osd upgrade failed: %v", e.err)
+}
+
+func getOpenshiftConfig(ctx context.Context, dynamicClient *dynamic.DynamicClient, resource string, name string) (*unstructured.Unstructured, error) {
+ gvr := schema.GroupVersionResource{
+ Group: "config.openshift.io",
+ Version: "v1",
+ Resource: resource,
+ }
+ return dynamicClient.Resource(gvr).Get(ctx, name, metav1.GetOptions{})
+}
+
+// checkMigrationStatus probes the status of the SDN-to-OVN migration
+func checkMigrationStatus(ctx context.Context, client *openshiftclient.Client) error {
+ var (
+ dynamicClient *dynamic.DynamicClient
+ err error
+ )
+
+ if dynamicClient, err = getKubernetesDynamicClient(client); err != nil {
+ return &upgradeError{err: err}
+ }
+ for i := 1; i <= upgradeMaxAttempts; i++ {
+ // Get the current network configuration
+ networkConfig, err := getOpenshiftConfig(ctx, dynamicClient, "networks", "cluster")
+ if err != nil {
+ return fmt.Errorf("failed to get network configuration: %v", err)
+ }
+
+ // Extract the status conditions
+ status, found, err := unstructured.NestedMap(networkConfig.Object, "status")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find status in network configuration: %v", err)
+ }
+
+ conditions, found, err := unstructured.NestedSlice(status, "conditions")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find conditions in status: %v", err)
+ }
+
+ // Check for the migration condition
+ migrationInProgress := false
+ for _, cond := range conditions {
+ conditionMap, ok := cond.(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("invalid type for condition entry")
+ }
+
+ conditionType, found, err := unstructured.NestedString(conditionMap, "type")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition type: %v", err)
+ }
+
+ if conditionType == "NetworkTypeMigrationInProgress" {
+ status, found, err := unstructured.NestedString(conditionMap, "status")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition status: %v", err)
+ }
+
+ reason, found, err := unstructured.NestedString(conditionMap, "reason")
+ if err != nil || !found {
+ return fmt.Errorf("failed to find condition reason: %v", err)
+ }
+
+ // Check if the migration is in progress
+ if status == "True" && reason == "NetworkTypeMigrationStarted" {
+ migrationInProgress = true
+ break
+ }
+
+ // Check if the migration is complete
+ if status == "False" && reason == "NetworkTypeMigrationCompleted" {
+ fmt.Println("Network migration completed successfully!")
+ return nil
+ }
+ }
+ }
+
+ if migrationInProgress {
+ fmt.Println("Network migration is still in progress...")
+ } else {
+ fmt.Println("Migration status is unknown or not in progress.")
+ }
+
+ time.Sleep(upgradeDelay * time.Second)
+ }
+
+ return fmt.Errorf("network migration is still in progress after %d attempts", upgradeMaxAttempts)
+
+}
+
+// checkUpgradeStatus probes the status of the cluster upgrade
+func checkUpgradeStatus(ctx context.Context, client *openshiftclient.Client, upgradeVersion string) error {
The reason for not using https://github.com/openshift/osde2e-common/blob/b7010c1e369cc51ae0e27231271409b016b53b2d/pkg/openshift/osd/upgrade.go#L223 is because
when I try to initiate an upgrade using the managedUpgrade operator I would get this error "no version gate exists for 4.15"
@@ -0,0 +1,631 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "log"
+ "strconv"
+ "strings"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "os"
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+ "time"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ rosaProvider, err := rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
Shouldn't need to recreate another provider, you can reused the one set up in BeforeAll, right?
@@ -0,0 +1,631 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "log"
+ "strconv"
+ "strings"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "os"
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+ "time"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ rosaProvider, err := rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ err = rosaProvider.DeleteCluster(ctx, &rosaprovider.DeleteClusterOptions{
+ ClusterName: testRosaCluster.name,
+ WorkingDir: testRosaCluster.reportDir,
+ STS: true,
+ DeleteOidcConfigID: true,
+ })
+ Expect(err).Should(BeNil(), "failed to delete rosa cluster")
+ }
+ })
+
+ It("rosa cluster is upgraded to 4.15.8 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_15, image4_15, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.15.8 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.15.8-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster is upgraded to 4.16.0-rc.0 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_16, image4_16, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.16.0-rc.0 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.16.0-rc.0-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster migrated from sdn to ovn successfully", sdnToOvn, func(ctx context.Context) {
+ err := addIntenalTestingAnnotation(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = patchNetworkConfig(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = checkMigrationStatus(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+
+ })
+ It("rosa cluster has no critical alerts firing post sdn to ovn migration", postMigrationCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+})
+
+// queryPrometheusAlerts queries prometheus for alerts and provides a count for critical and warning alerts
+func queryPrometheusAlerts(ctx context.Context, client *openshiftclient.Client, logFilename string) (int, int, error) {
+ criticalAlertCount, warningAlertCount := 0, 0
+ alerts := ""
+
+ type metric struct {
+ AlertName string `json:"alertname"`
+ AlertState string `json:"alertstate"`
+ Condition string `json:"condition"`
+ Endpoint string `json:"endpoint"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Severity string `json:"severity"`
+ }
+
+ prometheusClient, _ := prometheusclient.New(ctx, client)
+ vector, err := prometheusClient.InstantQuery(ctx, "ALERTS{alertstate!=\"pending\",alertname!=\"Watchdog\"}")
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to query prometheus: %v", err)
+ }
+
+ for _, model := range vector {
+ metric := metric{}
+
+ metricEncoded, err := json.Marshal(model.Metric)
+ if err != nil {
+ continue
+ }
+
+ err = json.Unmarshal(metricEncoded, &metric)
+ if err != nil {
+ continue
+ }
I'm not sure I understand why we remarshal the metric into a new struct
@@ -0,0 +1,525 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ err := rosaProvider.DeleteCluster(ctx, &rosaprovider.DeleteClusterOptions{
+ ClusterName: testRosaCluster.name,
+ WorkingDir: testRosaCluster.reportDir,
+ STS: true,
+ DeleteOidcConfigID: true,
+ })
+ Expect(err).Should(BeNil(), "failed to delete rosa cluster")
+ }
+ })
+
+ It("rosa cluster is upgraded to 4.15.8 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_15, image4_15, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+ })
+
+ It("rosa cluster is healthy post 4.15.8 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.15.8-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+ })
+
+ It("rosa cluster is upgraded to 4.16.0-rc.0 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_16, image4_16, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+ })
+
+ It("rosa cluster is healthy post 4.16.0-rc.0 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.16.0-rc.0-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+ })
+
+ It("rosa cluster migrated from sdn to ovn successfully", sdnToOvn, func(ctx context.Context) {
+ err := addIntenalTestingAnnotation(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = patchNetworkConfig(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = checkMigrationStatus(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ })
+ It("rosa cluster has no critical alerts firing post sdn to ovn migration", postMigrationCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+ })
+})
+
+// queryPrometheusAlerts queries prometheus for alerts and provides a count for critical and warning alerts
+func queryPrometheusAlerts(ctx context.Context, client *openshiftclient.Client, logFilename string) (int, int, error) {
+ criticalAlertCount, warningAlertCount := 0, 0
+ alerts := ""
+
+ type metric struct {
+ AlertName string `json:"alertname"`
+ AlertState string `json:"alertstate"`
+ Condition string `json:"condition"`
+ Endpoint string `json:"endpoint"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Severity string `json:"severity"`
+ }
+
+ prometheusClient, _ := prometheusclient.New(ctx, client)
+ vector, err := prometheusClient.InstantQuery(ctx, "ALERTS{alertstate!=\"pending\",alertname!=\"Watchdog\"}")
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to query prometheus: %v", err)
+ }
+
+ for _, model := range vector {
+ metric := metric{}
+
+ metricEncoded, err := json.Marshal(model.Metric)
+ if err != nil {
+ continue
+ }
+
+ err = json.Unmarshal(metricEncoded, &metric)
+ if err != nil {
+ continue
+ }
+
+ alerts += fmt.Sprintf("Since: %s : %+v\n", time.Unix(model.Timestamp.Unix(), 0), metric)
+
+ switch model.Metric["severity"] {
+ case "critical":
+ criticalAlertCount += 1
+ case "warning":
+ warningAlertCount += 1
+ }
+ }
+
+ if alerts != "" {
+ if err = os.WriteFile(logFilename, []byte(alerts), os.FileMode(0o644)); err != nil {
+ return criticalAlertCount, warningAlertCount, fmt.Errorf("failed to write prometheus alerts to file: %v", err)
+ }
+ }
+
+ return criticalAlertCount, warningAlertCount, nil
+}
+
+// getEnvVar returns the env variable value and if unset returns default provided
+func getEnvVar(key, value string) string {
+ result, exist := os.LookupEnv(key)
+ if exist {
+ return result
+ }
+ return value
+}
+
+// osdClusterReadyHealthCheck verifies the osd-cluster-ready health check job is passing
+func osdClusterReadyHealthCheck(ctx context.Context, clusterClient *openshiftclient.Client, action, reportDir string) error {
+ var (
+ err error
+ job batchv1.Job
+ )
+
+ if err = clusterClient.Get(ctx, osdClusterReadyJobName, "openshift-monitoring", &job); err != nil {
+ return fmt.Errorf("failed to get existing %s job %v", osdClusterReadyJobName, err)
+ }
+
+ newJob := &batchv1.Job{
+ ObjectMeta: metav1.ObjectMeta{
+ GenerateName: osdClusterReadyJobName,
+ Annotations: job.Annotations,
+ Namespace: job.Namespace,
+ },
+ Spec: job.Spec,
+ }
+
+ newJob.Spec.Selector.MatchLabels = map[string]string{}
+ newJob.Spec.Template.ObjectMeta.Name = newJob.GetGenerateName()
+ newJob.Spec.Template.ObjectMeta.Labels = map[string]string{}
+ newJob.Spec.Template.Spec.Containers[0].Name = newJob.GetGenerateName()
+
+ if err = clusterClient.Create(ctx, newJob); err != nil {
+ return fmt.Errorf("failed to create %s job: %v", newJob.GetName(), err)
+ }
+
+ defer func() {
+ _ = clusterClient.Delete(ctx, newJob)
+ }()
+
+ return clusterClient.OSDClusterHealthy(ctx, newJob.GetName(), reportDir, osdClusterReadyJobTimeout)
+}
+
+type upgradeError struct {
+ err error
+}
+
+// Error returns the formatted error message when upgradeError is invoked
+func (e *upgradeError) Error() string {
+ return fmt.Sprintf("osd upgrade failed: %v", e.err)
+}
+
+func getOpenshiftConfig(ctx context.Context, dynamicClient *dynamic.DynamicClient, resource string, name string) (*unstructured.Unstructured, error) {
This func can be deleted now it seems!
@@ -0,0 +1,525 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ err := rosaProvider.DeleteCluster(ctx, &rosaprovider.DeleteClusterOptions{
+ ClusterName: testRosaCluster.name,
+ WorkingDir: testRosaCluster.reportDir,
+ STS: true,
+ DeleteOidcConfigID: true,
+ })
+ Expect(err).Should(BeNil(), "failed to delete rosa cluster")
+ }
+ })
+
+ It("rosa cluster is upgraded to 4.15.8 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_15, image4_15, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+ })
+
+ It("rosa cluster is healthy post 4.15.8 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.15.8-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+ })
+
+ It("rosa cluster is upgraded to 4.16.0-rc.0 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_16, image4_16, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+ })
+
+ It("rosa cluster is healthy post 4.16.0-rc.0 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.16.0-rc.0-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+ })
+
+ It("rosa cluster migrated from sdn to ovn successfully", sdnToOvn, func(ctx context.Context) {
+ err := addIntenalTestingAnnotation(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = patchNetworkConfig(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = checkMigrationStatus(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ })
+ It("rosa cluster has no critical alerts firing post sdn to ovn migration", postMigrationCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+ })
+})
+
+// queryPrometheusAlerts queries prometheus for alerts and provides a count for critical and warning alerts
+func queryPrometheusAlerts(ctx context.Context, client *openshiftclient.Client, logFilename string) (int, int, error) {
+ criticalAlertCount, warningAlertCount := 0, 0
+ alerts := ""
+
+ type metric struct {
+ AlertName string `json:"alertname"`
+ AlertState string `json:"alertstate"`
+ Condition string `json:"condition"`
+ Endpoint string `json:"endpoint"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Severity string `json:"severity"`
+ }
+
+ prometheusClient, _ := prometheusclient.New(ctx, client)
+ vector, err := prometheusClient.InstantQuery(ctx, "ALERTS{alertstate!=\"pending\",alertname!=\"Watchdog\"}")
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to query prometheus: %v", err)
+ }
+
+ for _, model := range vector {
+ metric := metric{}
+
+ metricEncoded, err := json.Marshal(model.Metric)
+ if err != nil {
+ continue
+ }
+
+ err = json.Unmarshal(metricEncoded, &metric)
+ if err != nil {
+ continue
+ }
+
+ alerts += fmt.Sprintf("Since: %s : %+v\n", time.Unix(model.Timestamp.Unix(), 0), metric)
+
+ switch model.Metric["severity"] {
+ case "critical":
+ criticalAlertCount += 1
+ case "warning":
+ warningAlertCount += 1
+ }
+ }
+
+ if alerts != "" {
+ if err = os.WriteFile(logFilename, []byte(alerts), os.FileMode(0o644)); err != nil {
+ return criticalAlertCount, warningAlertCount, fmt.Errorf("failed to write prometheus alerts to file: %v", err)
+ }
+ }
+
+ return criticalAlertCount, warningAlertCount, nil
+}
+
+// getEnvVar returns the env variable value and if unset returns default provided
+func getEnvVar(key, value string) string {
+ result, exist := os.LookupEnv(key)
+ if exist {
+ return result
+ }
+ return value
+}
+
+// osdClusterReadyHealthCheck verifies the osd-cluster-ready health check job is passing
+func osdClusterReadyHealthCheck(ctx context.Context, clusterClient *openshiftclient.Client, action, reportDir string) error {
+ var (
+ err error
+ job batchv1.Job
+ )
+
+ if err = clusterClient.Get(ctx, osdClusterReadyJobName, "openshift-monitoring", &job); err != nil {
+ return fmt.Errorf("failed to get existing %s job %v", osdClusterReadyJobName, err)
+ }
+
+ newJob := &batchv1.Job{
+ ObjectMeta: metav1.ObjectMeta{
+ GenerateName: osdClusterReadyJobName,
+ Annotations: job.Annotations,
+ Namespace: job.Namespace,
+ },
+ Spec: job.Spec,
+ }
+
+ newJob.Spec.Selector.MatchLabels = map[string]string{}
+ newJob.Spec.Template.ObjectMeta.Name = newJob.GetGenerateName()
+ newJob.Spec.Template.ObjectMeta.Labels = map[string]string{}
+ newJob.Spec.Template.Spec.Containers[0].Name = newJob.GetGenerateName()
+
+ if err = clusterClient.Create(ctx, newJob); err != nil {
+ return fmt.Errorf("failed to create %s job: %v", newJob.GetName(), err)
+ }
+
+ defer func() {
+ _ = clusterClient.Delete(ctx, newJob)
+ }()
+
+ return clusterClient.OSDClusterHealthy(ctx, newJob.GetName(), reportDir, osdClusterReadyJobTimeout)
+}
+
+type upgradeError struct {
+ err error
+}
+
+// Error returns the formatted error message when upgradeError is invoked
+func (e *upgradeError) Error() string {
+ return fmt.Sprintf("osd upgrade failed: %v", e.err)
+}
+
+func getOpenshiftConfig(ctx context.Context, dynamicClient *dynamic.DynamicClient, resource string, name string) (*unstructured.Unstructured, error) {
+ gvr := schema.GroupVersionResource{
+ Group: "config.openshift.io",
+ Version: "v1",
+ Resource: resource,
+ }
+ return dynamicClient.Resource(gvr).Get(ctx, name, metav1.GetOptions{})
+}
+
+// checkMigrationStatus probes the status of the SDN-to-OVN migration
+func checkMigrationStatus(ctx context.Context, client *openshiftclient.Client) error {
+ var (
+ err error
+ network configv1.Network
+ )
+
+ for i := 1; i <= upgradeMaxAttempts; i++ {
+ // Get the current network configuration
+ err = client.Get(ctx, "cluster", "", &network)
+ if err != nil {
+ return fmt.Errorf("failed to get network configuration: %v", err)
+ }
+
+ // Check for the migration condition
+ migrationInProgress := false
+ for _, cond := range network.Status.Conditions {
+ if cond.Type == "NetworkTypeMigrationInProgress" {
+ if cond.Status == "True" && cond.Reason == "NetworkTypeMigrationStarted" {
+ migrationInProgress = true
+ break
+ }
+
+ if cond.Status == "False" && cond.Reason == "NetworkTypeMigrationCompleted" {
+ fmt.Println("Network migration completed successfully!")
Could you try to standardize so that all log messages are logged using GinkgoLogr? That way you can control verbosity through ginkgo and it writes the output to the correct spec report
Few more small things, awesome work on this @reedcort !
@@ -0,0 +1,631 @@
+package sdn_migration_test
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "github.com/Masterminds/semver/v3"
+ configv1 "github.com/openshift/api/config/v1"
+ openshiftclient "github.com/openshift/osde2e-common/pkg/clients/openshift"
+ prometheusclient "github.com/openshift/osde2e-common/pkg/clients/prometheus"
+ "github.com/openshift/osde2e-common/pkg/clouds/aws"
+ osdprovider "github.com/openshift/osde2e-common/pkg/openshift/osd"
+ rosaprovider "github.com/openshift/osde2e-common/pkg/openshift/rosa"
+ "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ "k8s.io/apimachinery/pkg/runtime/schema"
+ "k8s.io/client-go/dynamic"
+ "log"
+ "strconv"
+ "strings"
+
+ batchv1 "k8s.io/api/batch/v1"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "os"
+ "sigs.k8s.io/e2e-framework/klient/k8s"
+ "sigs.k8s.io/e2e-framework/pkg/envconf"
+ "time"
+
+ "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/openshift/osde2e-common/pkg/clients/ocm"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+
+const (
+ osdClusterReadyJobName = "osd-cluster-ready"
+ osdClusterReadyJobTimeout = 45 * time.Minute
+ version4_15 = "4.15.8"
+ version4_16 = "4.16.0-rc.0"
+ image4_15 = "quay.io/openshift-release-dev/ocp-release@sha256:8032c4248d7ae032d5e79debf975d08683cc34d5f08ab2e937ce2d1e940c007b"
+ image4_16 = "quay.io/openshift-release-dev/ocp-release@sha256:c56b01191de4cbb4b97c6eeaf61c5c122fcd465d1d0d671db640d877638ed790"
+ channel4_15 = "14.15.8"
+ channel4_16 = "4.16.0-rc.0"
+ upgradeMaxAttempts = 1080
+ upgradeDelay = 10
+)
+
+type rosaCluster struct {
+ id string
+ name string
+ channelGroup string
+ version string
+ reportDir string
+ upgradeVersion *semver.Version
+ kubeconfigFile string
+
+ client *openshiftclient.Client
+}
+
+var _ = Describe("SDN migration", ginkgo.Ordered, func() {
+ var (
+ clusterName = os.Getenv("CLUSTER_NAME")
+ testRosaCluster *rosaCluster
+ clusterOptions *rosaprovider.CreateClusterOptions
+ reportDir = getEnvVar("REPORT_DIR", envconf.RandomName(fmt.Sprintf("%s/sdn_migration", os.TempDir()), 25))
+ ocmToken = os.Getenv("OCM_TOKEN")
+ clientID = os.Getenv("CLIENT_ID")
+ clientSecret = os.Getenv("CLIENT_SECRET")
+ region = os.Getenv("AWS_REGION")
+ replicas, _ = strconv.Atoi(os.Getenv("REPLICAS"))
+ ocmEnv = ocm.Stage
+ logger = GinkgoLogr
+ rosaProvider *rosaprovider.Provider
+ createRosaCluster = Label("CreateRosaCluster")
+ enableClusterProxy = Label("EnableClusterProxy")
+ removeRosaCluster = Label("RemoveRosaCluster")
+ postMigrationCheck = Label("PostMigrationCheck")
+ rosaUpgrade = Label("RosaUpgrade")
+ postUpgradeCheck = Label("PostUpgradeCheck")
+ sdnToOvn = Label("SdnToOvn")
+ secretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
+ accessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
+ )
+
+ _ = BeforeAll(func(ctx context.Context) {
+ var err error
+ testRosaCluster = &rosaCluster{}
+
+ Expect(ocmToken).ShouldNot(BeEmpty(), "ocm token is undefined")
+
+ rosaProvider, err = rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct rosa provider")
+ osdProvider, err := osdprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct osd provider")
+ DeferCleanup(osdProvider.Client.Close)
+
+ if createRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions = &rosaprovider.CreateClusterOptions{
+ ClusterName: clusterName,
+ Version: "4.14.14",
+ UseDefaultAccountRolesPrefix: true,
+ STS: true,
+ Mode: "auto",
+ ChannelGroup: "stable",
+ ComputeMachineType: "m5.xlarge",
+ Replicas: replicas,
+ MultiAZ: true,
+ ETCDEncryption: true,
+ NetworkType: "OpenShiftSDN",
+ SkipHealthCheck: true,
+ }
+ }
+ if os.Getenv("CLUSTER_ID") == "" {
+ if enableClusterProxy.MatchesLabelFilter(GinkgoLabelFilter()) {
+ clusterOptions.HTTPSProxy = os.Getenv("AWS_HTTPS_PROXY")
+ clusterOptions.HTTPProxy = os.Getenv("AWS_HTTP_PROXY")
+ clusterOptions.AdditionalTrustBundleFile = os.Getenv("CA_BUNDLE")
+ clusterOptions.SubnetIDs = os.Getenv("SUBNETS")
+ clusterOptions.NoProxy = "api.stage.openshift.com"
+ }
+ testRosaCluster.id, err = rosaProvider.CreateCluster(ctx, clusterOptions)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to create rosa cluster")
+ } else {
+ testRosaCluster.id = os.Getenv("CLUSTER_ID")
+ }
+
+ rosaCluster, err := osdProvider.ClustersMgmt().V1().Clusters().Cluster(testRosaCluster.id).Get().SendContext(ctx)
+ Expect(err).ShouldNot(HaveOccurred())
+ testRosaCluster.name = rosaCluster.Body().Name()
+ testRosaCluster.version = rosaCluster.Body().Version().RawID()
+ testRosaCluster.channelGroup = rosaCluster.Body().Version().ChannelGroup()
+
+ testRosaCluster.kubeconfigFile, err = rosaProvider.KubeconfigFile(ctx, testRosaCluster.id, os.TempDir())
+ Expect(err).ShouldNot(HaveOccurred())
+
+ testRosaCluster.client, err = openshiftclient.NewFromKubeconfig(testRosaCluster.kubeconfigFile, logger)
+ Expect(err).ShouldNot(HaveOccurred(), "failed to construct service cluster client")
+
+ testRosaCluster.reportDir = fmt.Sprintf("%s/%s", reportDir, testRosaCluster.name)
+ Expect(os.MkdirAll(reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create report directory")
+ Expect(os.MkdirAll(testRosaCluster.reportDir, os.ModePerm)).ShouldNot(HaveOccurred(), "failed to create rosa cluster report directory")
+
+ })
+
+ AfterAll(func(ctx context.Context) {
+ if removeRosaCluster.MatchesLabelFilter(GinkgoLabelFilter()) {
+ rosaProvider, err := rosaprovider.New(ctx, ocmToken, clientID, clientSecret, ocmEnv, logger, &aws.AWSCredentials{
+ Region: region,
+ SecretAccessKey: secretAccessKey,
+ AccessKeyID: accessKeyID,
+ })
+ err = rosaProvider.DeleteCluster(ctx, &rosaprovider.DeleteClusterOptions{
+ ClusterName: testRosaCluster.name,
+ WorkingDir: testRosaCluster.reportDir,
+ STS: true,
+ DeleteOidcConfigID: true,
+ })
+ Expect(err).Should(BeNil(), "failed to delete rosa cluster")
+ }
+ })
+
+ It("rosa cluster is upgraded to 4.15.8 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_15, image4_15, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_15)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.15.8 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.15.8-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster is upgraded to 4.16.0-rc.0 successfully", rosaUpgrade, func(ctx context.Context) {
+ err := patchVersionConfig(ctx, testRosaCluster.client, channel4_16, image4_16, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), "rosa cluster upgrade failed")
+ err = checkUpgradeStatus(ctx, testRosaCluster.client, version4_16)
+ Expect(err).ShouldNot(HaveOccurred(), err)
+
+ })
+
+ It("rosa cluster is healthy post 4.16.0-rc.0 upgrade", postUpgradeCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/4.16.0-rc.0-prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+
+ It("rosa cluster migrated from sdn to ovn successfully", sdnToOvn, func(ctx context.Context) {
+ err := addIntenalTestingAnnotation(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = patchNetworkConfig(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+ err = checkMigrationStatus(ctx, testRosaCluster.client)
+ Expect(err).ShouldNot(HaveOccurred(), "Rosa Cluster failed to patch network")
+
+ })
+ It("rosa cluster has no critical alerts firing post sdn to ovn migration", postMigrationCheck, func(ctx context.Context) {
+ criticalAlerts, _, err := queryPrometheusAlerts(ctx, testRosaCluster.client, fmt.Sprintf("%s/prometheus-alerts-pre-upgrade.log", testRosaCluster.reportDir))
+ Expect(err).ShouldNot(HaveOccurred(), "failed to retrieve prometheus alerts")
+ Expect(criticalAlerts).ToNot(BeNumerically(">", 0), "critical alerts are firing pre upgrade")
+ err = osdClusterReadyHealthCheck(ctx, testRosaCluster.client, "post-upgrade", testRosaCluster.reportDir)
+ Expect(err).ShouldNot(HaveOccurred(), "osd-cluster-ready health check job failed post upgrade")
+
+ })
+})
+
+// queryPrometheusAlerts queries prometheus for alerts and provides a count for critical and warning alerts
+func queryPrometheusAlerts(ctx context.Context, client *openshiftclient.Client, logFilename string) (int, int, error) {
+ criticalAlertCount, warningAlertCount := 0, 0
+ alerts := ""
+
+ type metric struct {
+ AlertName string `json:"alertname"`
+ AlertState string `json:"alertstate"`
+ Condition string `json:"condition"`
+ Endpoint string `json:"endpoint"`
+ Name string `json:"name"`
+ Namespace string `json:"namespace"`
+ Severity string `json:"severity"`
+ }
+
+ prometheusClient, _ := prometheusclient.New(ctx, client)
+ vector, err := prometheusClient.InstantQuery(ctx, "ALERTS{alertstate!=\"pending\",alertname!=\"Watchdog\"}")
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to query prometheus: %v", err)
+ }
+
+ for _, model := range vector {
+ metric := metric{}
+
+ metricEncoded, err := json.Marshal(model.Metric)
+ if err != nil {
+ continue
+ }
+
+ err = json.Unmarshal(metricEncoded, &metric)
+ if err != nil {
+ continue
+ }
I'm not entirely sure either; I copied it from https://github.com/openshift/osde2e/blob/main/test/mcscupgrade/mcscupgrade_test.go#L314. Since the goal is to eventually export the metrics to Grafana, I’ve removed it for now.
Hey @reedcort , would you mind adding an OWNERS file in this directory (in the format of the root OWNERS file) with approvers/reviewers for this suite? You don't have to add us, just yourself and teammates that need to be added.
/lgtm
/unhold
/approve
[APPROVALNOTIFIER] This PR is APPROVED
This pull-request has been approved by: <a href="https://github.com/openshift/osde2e/pull/2668#issuecomment-2338888696" title="Approved">jbpratt</a>, <a href="https://github.com/openshift/osde2e/pull/2668#" title="Author self-approved">reedcort</a>
The full list of commands accepted by this bot can be found here.
The pull request process is described here
<details >
Needs approval from an approver in each of these files:
Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment
</details>
<!-- META={"approvers":[]} -->
reedcort
Residual = Change × (1 − Confidence)
jbpratt
What is being added?
OSDE2E suite to run a cluster creation , update to required version, and then a migration from SDN to OVN