diff --git a/.gitignore b/.gitignore index 35c6a018..366b5c5b 100644 --- a/.gitignore +++ b/.gitignore @@ -12,7 +12,7 @@ *.out # Dependency directories (remove the comment below to include it) -# vendor/ +vendor/ # Goreleaser dist/ diff --git a/.golangci.yml b/.golangci.yml index 9cdc1156..f9618763 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -16,3 +16,4 @@ linters: - staticcheck - typecheck - unused + - stylecheck diff --git a/cmd/ocm-backplane/cloud/assume.go b/cmd/ocm-backplane/cloud/assume.go index fb60a87b..2a26eac6 100644 --- a/cmd/ocm-backplane/cloud/assume.go +++ b/cmd/ocm-backplane/cloud/assume.go @@ -4,14 +4,16 @@ import ( "context" "encoding/json" "fmt" + "io" + "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/sts" - "github.com/openshift/backplane-cli/pkg/awsUtil" + "github.com/spf13/cobra" + + "github.com/openshift/backplane-cli/pkg/awsutil" "github.com/openshift/backplane-cli/pkg/cli/config" "github.com/openshift/backplane-cli/pkg/utils" - "github.com/spf13/cobra" - "io" ) const ( @@ -70,16 +72,16 @@ func runAssume(_ *cobra.Command, args []string) error { return fmt.Errorf("error retrieving backplane configuration: %w", err) } - initialClient, err := awsUtil.StsClientWithProxy(bpConfig.ProxyURL) + initialClient, err := awsutil.StsClientWithProxy(bpConfig.ProxyURL) if err != nil { return fmt.Errorf("failed to create sts client: %w", err) } - seedCredentials, err := awsUtil.AssumeRoleWithJWT(*ocmToken, assumeArgs.roleArn, initialClient) + seedCredentials, err := awsutil.AssumeRoleWithJWT(*ocmToken, assumeArgs.roleArn, initialClient) if err != nil { return fmt.Errorf("failed to assume role using JWT: %w", err) } - clusterId, _, err := utils.DefaultOCMInterface.GetTargetCluster(args[0]) + clusterID, _, err := utils.DefaultOCMInterface.GetTargetCluster(args[0]) if err != nil { return fmt.Errorf("failed to get target cluster: %w", err) } @@ -89,7 +91,7 @@ func runAssume(_ *cobra.Command, args []string) error { return fmt.Errorf("failed to create backplane client with access token: %w", err) } - response, err := backplaneClient.GetAssumeRoleSequence(context.TODO(), clusterId) + response, err := backplaneClient.GetAssumeRoleSequence(context.TODO(), clusterID) if err != nil { return fmt.Errorf("failed to fetch arn sequence: %w", err) } @@ -119,13 +121,13 @@ func runAssume(_ *cobra.Command, args []string) error { Region: "us-east-1", Credentials: credentials.NewStaticCredentialsProvider(*seedCredentials.AccessKeyId, *seedCredentials.SecretAccessKey, *seedCredentials.SessionToken), }) - targetCredentials, err := awsUtil.AssumeRoleSequence(email, seedClient, roleAssumeSequence, bpConfig.ProxyURL, awsUtil.DefaultSTSClientProviderFunc) + targetCredentials, err := awsutil.AssumeRoleSequence(email, seedClient, roleAssumeSequence, bpConfig.ProxyURL, awsutil.DefaultSTSClientProviderFunc) if err != nil { return fmt.Errorf("failed to assume role sequence: %w", err) } - credsResponse := awsUtil.AWSCredentialsResponse{ - AccessKeyId: *targetCredentials.AccessKeyId, + credsResponse := awsutil.AWSCredentialsResponse{ + AccessKeyID: *targetCredentials.AccessKeyId, SecretAccessKey: *targetCredentials.SecretAccessKey, SessionToken: *targetCredentials.SessionToken, Expiration: targetCredentials.Expiration.String(), diff --git a/cmd/ocm-backplane/cloud/console.go b/cmd/ocm-backplane/cloud/console.go index 2f5cdc01..f84a6f76 100644 --- a/cmd/ocm-backplane/cloud/console.go +++ b/cmd/ocm-backplane/cloud/console.go @@ -15,6 +15,7 @@ import ( "sigs.k8s.io/yaml" BackplaneApi "github.com/openshift/backplane-api/pkg/client" + "github.com/openshift/backplane-cli/pkg/cli/config" "github.com/openshift/backplane-cli/pkg/utils" ) @@ -103,13 +104,13 @@ func runConsole(cmd *cobra.Command, argv []string) (err error) { clusterKey = clusterInfo.ClusterID } - clusterId, clusterName, err := utils.DefaultOCMInterface.GetTargetCluster(clusterKey) + clusterID, clusterName, err := utils.DefaultOCMInterface.GetTargetCluster(clusterKey) if err != nil { return err } logger.WithFields(logger.Fields{ - "ID": clusterId, + "ID": clusterID, "Name": clusterName}).Infoln("Target cluster") // ============Get Backplane URl ========================== @@ -130,8 +131,8 @@ func runConsole(cmd *cobra.Command, argv []string) (err error) { logger.Infof("Using backplane URL: %s\n", bpURL) } - // ======== Get cloudconsole from backplane API ============ - response, err := getCloudConsole(bpURL, clusterId) + // ======== Get cloud console from backplane API ============ + response, err := getCloudConsole(bpURL, clusterID) if err != nil { return err } @@ -160,13 +161,13 @@ func validateParams(argv []string) (err error) { } // getCloudConsole returns console response calling to public Backplane API -func getCloudConsole(backplaneURL string, clusterId string) (*ConsoleResponse, error) { +func getCloudConsole(backplaneURL string, clusterID string) (*ConsoleResponse, error) { logger.Debugln("Getting Cloud Console") client, err := utils.DefaultClientUtils.GetBackplaneClient(backplaneURL) if err != nil { return nil, err } - resp, err := client.GetCloudConsole(context.TODO(), clusterId) + resp, err := client.GetCloudConsole(context.TODO(), clusterID) if err != nil { return nil, err } diff --git a/cmd/ocm-backplane/cloud/console_test.go b/cmd/ocm-backplane/cloud/console_test.go index d92db1a0..9c08c7ca 100644 --- a/cmd/ocm-backplane/cloud/console_test.go +++ b/cmd/ocm-backplane/cloud/console_test.go @@ -9,13 +9,14 @@ import ( "github.com/golang/mock/gomock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + log "github.com/sirupsen/logrus" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/client-go/tools/clientcmd/api" + "github.com/openshift/backplane-cli/pkg/client/mocks" "github.com/openshift/backplane-cli/pkg/info" "github.com/openshift/backplane-cli/pkg/utils" mocks2 "github.com/openshift/backplane-cli/pkg/utils/mocks" - log "github.com/sirupsen/logrus" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/client-go/tools/clientcmd/api" ) var _ = Describe("Cloud console command", func() { @@ -27,11 +28,11 @@ var _ = Describe("Cloud console command", func() { mockOcmInterface *mocks2.MockOCMInterface mockClientUtil *mocks2.MockClientUtils - testClusterId string - trueClusterId string - proxyUri string - consoleAWSUrl string - consoleGcloudUrl string + testClusterID string + trueClusterID string + proxyURI string + consoleAWSURL string + consoleGcloudURL string fakeAWSResp *http.Response fakeGCloudResp *http.Response @@ -48,18 +49,18 @@ var _ = Describe("Cloud console command", func() { mockClientUtil = mocks2.NewMockClientUtils(mockCtrl) utils.DefaultClientUtils = mockClientUtil - testClusterId = "test123" - trueClusterId = "trueID123" - proxyUri = "https://shard.apps" - consoleAWSUrl = "https://signin.aws.amazon.com/federation?Action=login" - consoleGcloudUrl = "https://cloud.google.com/" + testClusterID = "test123" + trueClusterID = "trueID123" + proxyURI = "https://shard.apps" + consoleAWSURL = "https://signin.aws.amazon.com/federation?Action=login" + consoleGcloudURL = "https://cloud.google.com/" mockClientWithResp.EXPECT().LoginClusterWithResponse(gomock.Any(), gomock.Any()).Return(nil, nil).Times(0) // Define fake AWS response fakeAWSResp = &http.Response{ Body: MakeIoReader( - fmt.Sprintf(`{"proxy_uri":"proxy", "message":"msg", "ConsoleLink":"%s"}`, consoleAWSUrl), + fmt.Sprintf(`{"proxy_uri":"proxy", "message":"msg", "ConsoleLink":"%s"}`, consoleAWSURL), ), Header: map[string][]string{}, StatusCode: http.StatusOK, @@ -69,7 +70,7 @@ var _ = Describe("Cloud console command", func() { // Define fake AWS response fakeGCloudResp = &http.Response{ Body: MakeIoReader( - fmt.Sprintf(`{"proxy_uri":"proxy", "message":"msg", "ConsoleLink":"%s"}`, consoleGcloudUrl), + fmt.Sprintf(`{"proxy_uri":"proxy", "message":"msg", "ConsoleLink":"%s"}`, consoleGcloudURL), ), Header: map[string][]string{}, StatusCode: http.StatusOK, @@ -82,30 +83,30 @@ var _ = Describe("Cloud console command", func() { // Disabled log output log.SetOutput(io.Discard) - os.Setenv(info.BACKPLANE_URL_ENV_NAME, proxyUri) + os.Setenv(info.BackplaneURLEnvName, proxyURI) }) AfterEach(func() { - os.Setenv(info.BACKPLANE_URL_ENV_NAME, "") + os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) Context("Execute cloud console command", func() { It("should return AWS cloud console", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockClientUtil.EXPECT().GetBackplaneClient(proxyUri).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterId).Return(fakeAWSResp, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockClientUtil.EXPECT().GetBackplaneClient(proxyURI).Return(mockClient, nil).AnyTimes() + mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterID).Return(fakeAWSResp, nil) - err := runConsole(nil, []string{testClusterId}) + err := runConsole(nil, []string{testClusterID}) Expect(err).To(BeNil()) }) It("should return GCP cloud console", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockClientUtil.EXPECT().GetBackplaneClient(proxyUri).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterId).Return(fakeGCloudResp, nil) - err := runConsole(nil, []string{testClusterId}) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockClientUtil.EXPECT().GetBackplaneClient(proxyURI).Return(mockClient, nil).AnyTimes() + mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterID).Return(fakeGCloudResp, nil) + err := runConsole(nil, []string{testClusterID}) Expect(err).To(BeNil()) }) @@ -114,32 +115,32 @@ var _ = Describe("Cloud console command", func() { Context("get Cloud Console", func() { It("should return AWS cloud URL", func() { - mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterId).Return(fakeAWSResp, nil) - mockClientUtil.EXPECT().GetBackplaneClient(proxyUri).Return(mockClient, nil).AnyTimes() - cloudResponse, err := getCloudConsole(proxyUri, trueClusterId) + mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterID).Return(fakeAWSResp, nil) + mockClientUtil.EXPECT().GetBackplaneClient(proxyURI).Return(mockClient, nil).AnyTimes() + cloudResponse, err := getCloudConsole(proxyURI, trueClusterID) Expect(err).To(BeNil()) - Expect(cloudResponse.ConsoleLink).To(Equal(consoleAWSUrl)) + Expect(cloudResponse.ConsoleLink).To(Equal(consoleAWSURL)) }) It("should return Gcloud cloud URL", func() { - mockClientUtil.EXPECT().GetBackplaneClient(proxyUri).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterId).Return(fakeGCloudResp, nil) - cloudResponse, err := getCloudConsole(proxyUri, trueClusterId) + mockClientUtil.EXPECT().GetBackplaneClient(proxyURI).Return(mockClient, nil).AnyTimes() + mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterID).Return(fakeGCloudResp, nil) + cloudResponse, err := getCloudConsole(proxyURI, trueClusterID) Expect(err).To(BeNil()) - Expect(cloudResponse.ConsoleLink).To(Equal(consoleGcloudUrl)) + Expect(cloudResponse.ConsoleLink).To(Equal(consoleGcloudURL)) }) It("should fail when AWS Unavailable", func() { fakeAWSResp.StatusCode = http.StatusInternalServerError - mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterId).Return(fakeAWSResp, nil) - mockClientUtil.EXPECT().GetBackplaneClient(proxyUri).Return(mockClient, nil).AnyTimes() - _, err := getCloudConsole(proxyUri, trueClusterId) + mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterID).Return(fakeAWSResp, nil) + mockClientUtil.EXPECT().GetBackplaneClient(proxyURI).Return(mockClient, nil).AnyTimes() + _, err := getCloudConsole(proxyURI, trueClusterID) Expect(err).NotTo(BeNil()) Expect(err.Error()).Should(ContainSubstring("error from backplane: \n Status Code: 500\n")) @@ -148,9 +149,9 @@ var _ = Describe("Cloud console command", func() { It("should fail when GCP Unavailable", func() { fakeGCloudResp.StatusCode = http.StatusInternalServerError - mockClientUtil.EXPECT().GetBackplaneClient(proxyUri).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterId).Return(fakeGCloudResp, nil) - _, err := getCloudConsole(proxyUri, trueClusterId) + mockClientUtil.EXPECT().GetBackplaneClient(proxyURI).Return(mockClient, nil).AnyTimes() + mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterID).Return(fakeGCloudResp, nil) + _, err := getCloudConsole(proxyURI, trueClusterID) Expect(err).NotTo(BeNil()) Expect(err.Error()).Should(ContainSubstring("error from backplane: \n Status Code: 500\n")) @@ -159,9 +160,9 @@ var _ = Describe("Cloud console command", func() { It("should fail for unauthorized BP-API", func() { fakeAWSResp.StatusCode = http.StatusUnauthorized - mockClientUtil.EXPECT().GetBackplaneClient(proxyUri).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterId).Return(fakeAWSResp, nil) - _, err := getCloudConsole(proxyUri, trueClusterId) + mockClientUtil.EXPECT().GetBackplaneClient(proxyURI).Return(mockClient, nil).AnyTimes() + mockClient.EXPECT().GetCloudConsole(gomock.Any(), trueClusterID).Return(fakeAWSResp, nil) + _, err := getCloudConsole(proxyURI, trueClusterID) Expect(err).NotTo(BeNil()) Expect(err.Error()).Should(ContainSubstring("error from backplane: \n Status Code: 401\n")) diff --git a/cmd/ocm-backplane/cloud/credentials.go b/cmd/ocm-backplane/cloud/credentials.go index 4206ec79..042de148 100644 --- a/cmd/ocm-backplane/cloud/credentials.go +++ b/cmd/ocm-backplane/cloud/credentials.go @@ -15,6 +15,7 @@ import ( "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" BackplaneApi "github.com/openshift/backplane-api/pkg/client" + bpconfig "github.com/openshift/backplane-cli/pkg/cli/config" "github.com/openshift/backplane-cli/pkg/utils" ) @@ -36,7 +37,7 @@ type CredentialsResponse interface { } type AWSCredentialsResponse struct { - AccessKeyId string `json:"AccessKeyId" yaml:"AccessKeyId"` + AccessKeyID string `json:"AccessKeyID" yaml:"AccessKeyID"` SecretAccessKey string `json:"SecretAccessKey" yaml:"SecretAccessKey"` SessionToken string `json:"SessionToken" yaml:"SessionToken"` Region string `json:"Region" yaml:"Region"` @@ -44,13 +45,13 @@ type AWSCredentialsResponse struct { } type GCPCredentialsResponse struct { - ProjectId string `json:"project_id" yaml:"project_id"` + ProjectID string `json:"project_id" yaml:"project_id"` } const ( // format strings for printing AWS credentials as a string or as environment variables awsCredentialsStringFormat = `Temporary Credentials: - AccessKeyId: %s + AccessKeyID: %s SecretAccessKey: %s SessionToken: %s Region: %s @@ -67,27 +68,27 @@ gcloud config set project %s` ) func (r *AWSCredentialsResponse) String() string { - return fmt.Sprintf(awsCredentialsStringFormat, r.AccessKeyId, r.SecretAccessKey, r.SessionToken, r.Region, r.Expiration) + return fmt.Sprintf(awsCredentialsStringFormat, r.AccessKeyID, r.SecretAccessKey, r.SessionToken, r.Region, r.Expiration) } func (r *AWSCredentialsResponse) fmtExport() string { - return fmt.Sprintf(awsExportFormat, r.AccessKeyId, r.SecretAccessKey, r.SessionToken, r.Region) + return fmt.Sprintf(awsExportFormat, r.AccessKeyID, r.SecretAccessKey, r.SessionToken, r.Region) } // AWSV2Config returns an aws-sdk-go-v2 config that can be used to programmatically access the AWS API func (r *AWSCredentialsResponse) AWSV2Config() (aws.Config, error) { return config.LoadDefaultConfig(context.TODO(), config.WithRegion(r.Region), - config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(r.AccessKeyId, r.SecretAccessKey, r.SessionToken)), + config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(r.AccessKeyID, r.SecretAccessKey, r.SessionToken)), ) } func (r *GCPCredentialsResponse) String() string { - return fmt.Sprintf(gcpCredentialsStringFormat, r.ProjectId) + return fmt.Sprintf(gcpCredentialsStringFormat, r.ProjectID) } func (r *GCPCredentialsResponse) fmtExport() string { - return fmt.Sprintf(gcpExportFormat, r.ProjectId) + return fmt.Sprintf(gcpExportFormat, r.ProjectID) } // CredentialsCmd represents the cloud credentials command @@ -139,20 +140,20 @@ func runCredentials(cmd *cobra.Command, argv []string) error { return fmt.Errorf("expected exactly one cluster") } - clusterId, clusterName, err := utils.DefaultOCMInterface.GetTargetCluster(clusterKey) + clusterID, clusterName, err := utils.DefaultOCMInterface.GetTargetCluster(clusterKey) if err != nil { return err } - cluster, err := utils.DefaultOCMInterface.GetClusterInfoByID(clusterId) + cluster, err := utils.DefaultOCMInterface.GetClusterInfoByID(clusterID) if err != nil { - return fmt.Errorf("failed to get cluster info for %s: %w", clusterId, err) + return fmt.Errorf("failed to get cluster info for %s: %w", clusterID, err) } cloudProvider := utils.DefaultClusterUtils.GetCloudProvider(cluster) logger.WithFields(logger.Fields{ - "ID": clusterId, + "ID": clusterID, "Name": clusterName}).Infoln("Target cluster") // ============Get Backplane URl ========================== @@ -176,7 +177,7 @@ func runCredentials(cmd *cobra.Command, argv []string) error { // ======== Call Endpoint ================================== logger.Debugln("Getting Cloud Credentials") - credsResp, _ := getCloudCredential(bpURL, clusterId) + credsResp, _ := getCloudCredential(bpURL, clusterID) // ======== Render cloud credentials ======================= switch cloudProvider { @@ -209,8 +210,8 @@ func runCredentials(cmd *cobra.Command, argv []string) error { } // GetAWSV2Config allows consumers to get an aws-sdk-go-v2 Config to programmatically access the AWS API -func GetAWSV2Config(backplaneURL string, clusterId string) (aws.Config, error) { - cluster, err := utils.DefaultOCMInterface.GetClusterInfoByID(clusterId) +func GetAWSV2Config(backplaneURL string, clusterID string) (aws.Config, error) { + cluster, err := utils.DefaultOCMInterface.GetClusterInfoByID(clusterID) if err != nil { return aws.Config{}, err } @@ -220,7 +221,7 @@ func GetAWSV2Config(backplaneURL string, clusterId string) (aws.Config, error) { return aws.Config{}, fmt.Errorf("only supported for the aws cloud provider, this cluster has: %s", cloudProvider) } - resp, err := getCloudCredential(backplaneURL, clusterId) + resp, err := getCloudCredential(backplaneURL, clusterID) if err != nil { return aws.Config{}, err } @@ -235,13 +236,13 @@ func GetAWSV2Config(backplaneURL string, clusterId string) (aws.Config, error) { } // getCloudCredential returns Cloud Credentials Response -func getCloudCredential(backplaneURL string, clusterId string) (*BackplaneApi.GetCloudCredentialsResponse, error) { +func getCloudCredential(backplaneURL string, clusterID string) (*BackplaneApi.GetCloudCredentialsResponse, error) { client, err := utils.DefaultClientUtils.GetBackplaneClient(backplaneURL) if err != nil { return nil, err } - resp, err := client.GetCloudCredentials(context.TODO(), clusterId) + resp, err := client.GetCloudCredentials(context.TODO(), clusterID) if err != nil { return nil, err diff --git a/cmd/ocm-backplane/cloud/credentials_test.go b/cmd/ocm-backplane/cloud/credentials_test.go index c9a36cc8..2769ace0 100644 --- a/cmd/ocm-backplane/cloud/credentials_test.go +++ b/cmd/ocm-backplane/cloud/credentials_test.go @@ -38,8 +38,8 @@ var _ = Describe("Cloud console command", func() { mockClientUtil *mocks2.MockClientUtils mockClusterUtils *mocks2.MockClusterUtils - trueClusterId string - proxyUri string + trueClusterID string + proxyURI string credentialAWS string credentialGcp string @@ -47,7 +47,7 @@ var _ = Describe("Cloud console command", func() { fakeGCloudResp *http.Response fakeBrokenAWSResp *http.Response fakeBrokenGCPResp *http.Response - fakeMalformedJsonResp *http.Response + fakeMalformedJSONResp *http.Response ) BeforeEach(func() { @@ -65,8 +65,8 @@ var _ = Describe("Cloud console command", func() { utils.DefaultClusterUtils = mockClusterUtils utils.DefaultClientUtils = mockClientUtil - trueClusterId = "trueID123" - proxyUri = "https://shard.apps" + trueClusterID = "trueID123" + proxyURI = "https://shard.apps" credentialAWS = "fake aws credential" credentialGcp = "fake gcp credential" @@ -92,14 +92,14 @@ var _ = Describe("Cloud console command", func() { } fakeGCloudResp.Header.Add("Content-Type", "json") - fakeMalformedJsonResp = &http.Response{ + fakeMalformedJSONResp = &http.Response{ Body: MakeIoReader( `{"proxy_uri":proxy"}`, ), Header: map[string][]string{}, StatusCode: http.StatusOK, } - fakeMalformedJsonResp.Header.Add("Content-Type", "json") + fakeMalformedJSONResp.Header.Add("Content-Type", "json") // Define broken AWS response // https://stackoverflow.com/questions/32708717/go-when-will-json-unmarshal-to-struct-return-error @@ -136,11 +136,11 @@ var _ = Describe("Cloud console command", func() { // Disabled log output log.SetOutput(io.Discard) - os.Setenv(info.BACKPLANE_URL_ENV_NAME, proxyUri) + os.Setenv(info.BackplaneURLEnvName, proxyURI) }) AfterEach(func() { - os.Setenv(info.BACKPLANE_URL_ENV_NAME, "") + os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) @@ -148,10 +148,10 @@ var _ = Describe("Cloud console command", func() { It("should return AWS cloud credential", func() { - mockClientUtil.EXPECT().GetBackplaneClient(proxyUri).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().GetCloudCredentials(gomock.Any(), trueClusterId).Return(fakeAWSResp, nil) + mockClientUtil.EXPECT().GetBackplaneClient(proxyURI).Return(mockClient, nil).AnyTimes() + mockClient.EXPECT().GetCloudCredentials(gomock.Any(), trueClusterID).Return(fakeAWSResp, nil) - crdentialResponse, err := getCloudCredential(proxyUri, trueClusterId) + crdentialResponse, err := getCloudCredential(proxyURI, trueClusterID) Expect(err).To(BeNil()) Expect(crdentialResponse.JSON200).NotTo(BeNil()) @@ -161,9 +161,9 @@ var _ = Describe("Cloud console command", func() { It("should fail when AWS Unavailable", func() { fakeAWSResp.StatusCode = http.StatusInternalServerError - mockClientUtil.EXPECT().GetBackplaneClient(proxyUri).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().GetCloudCredentials(gomock.Any(), trueClusterId).Return(fakeAWSResp, nil) - _, err := getCloudCredential(proxyUri, trueClusterId) + mockClientUtil.EXPECT().GetBackplaneClient(proxyURI).Return(mockClient, nil).AnyTimes() + mockClient.EXPECT().GetCloudCredentials(gomock.Any(), trueClusterID).Return(fakeAWSResp, nil) + _, err := getCloudCredential(proxyURI, trueClusterID) Expect(err).NotTo(BeNil()) Expect(err.Error()).To(ContainSubstring("error from backplane: \n Status Code: 500\n")) @@ -173,9 +173,9 @@ var _ = Describe("Cloud console command", func() { It("should fail when GCP Unavailable", func() { fakeGCloudResp.StatusCode = http.StatusInternalServerError - mockClientUtil.EXPECT().GetBackplaneClient(proxyUri).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().GetCloudCredentials(gomock.Any(), trueClusterId).Return(fakeGCloudResp, nil) - _, err := getCloudCredential(proxyUri, trueClusterId) + mockClientUtil.EXPECT().GetBackplaneClient(proxyURI).Return(mockClient, nil).AnyTimes() + mockClient.EXPECT().GetCloudCredentials(gomock.Any(), trueClusterID).Return(fakeGCloudResp, nil) + _, err := getCloudCredential(proxyURI, trueClusterID) Expect(err).NotTo(BeNil()) Expect(err.Error()).To(ContainSubstring("error from backplane: \n Status Code: 500\n")) @@ -183,9 +183,9 @@ var _ = Describe("Cloud console command", func() { }) It("should fail when we can't parse the response from backplane", func() { - mockClientUtil.EXPECT().GetBackplaneClient(proxyUri).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().GetCloudCredentials(gomock.Any(), trueClusterId).Return(fakeMalformedJsonResp, nil) - _, err := getCloudCredential(proxyUri, trueClusterId) + mockClientUtil.EXPECT().GetBackplaneClient(proxyURI).Return(mockClient, nil).AnyTimes() + mockClient.EXPECT().GetCloudCredentials(gomock.Any(), trueClusterID).Return(fakeMalformedJSONResp, nil) + _, err := getCloudCredential(proxyURI, trueClusterID) Expect(err).NotTo(BeNil()) Expect(err.Error()).To(ContainSubstring(fmt.Errorf("unable to parse response body from backplane:\n Status Code: %d", 200).Error())) @@ -195,9 +195,9 @@ var _ = Describe("Cloud console command", func() { It("should fail for unauthorized BP-API", func() { fakeAWSResp.StatusCode = http.StatusUnauthorized - mockClientUtil.EXPECT().GetBackplaneClient(proxyUri).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().GetCloudCredentials(gomock.Any(), trueClusterId).Return(fakeAWSResp, nil) - _, err := getCloudCredential(proxyUri, trueClusterId) + mockClientUtil.EXPECT().GetBackplaneClient(proxyURI).Return(mockClient, nil).AnyTimes() + mockClient.EXPECT().GetCloudCredentials(gomock.Any(), trueClusterID).Return(fakeAWSResp, nil) + _, err := getCloudCredential(proxyURI, trueClusterID) Expect(err).NotTo(BeNil()) Expect(err.Error()).Should(ContainSubstring("error from backplane: \n Status Code: 401\n")) @@ -315,7 +315,7 @@ var _ = Describe("Cloud console command", func() { Context("test renderCloudCredentials", func() { creds := AWSCredentialsResponse{ - AccessKeyId: "foo", + AccessKeyID: "foo", SecretAccessKey: "bar", SessionToken: "baz", Region: "quux", @@ -349,7 +349,7 @@ var _ = Describe("Cloud console command", func() { Context("TestAWSCredentialsResponseString(", func() { It("It formats the output correctly", func() { r := &AWSCredentialsResponse{ - AccessKeyId: "12345", + AccessKeyID: "12345", SecretAccessKey: "56789", SessionToken: "sessiontoken", Region: "region", @@ -357,7 +357,7 @@ var _ = Describe("Cloud console command", func() { } formattedcreds := `Temporary Credentials: - AccessKeyId: 12345 + AccessKeyID: 12345 SecretAccessKey: 56789 SessionToken: sessiontoken Region: region @@ -368,7 +368,7 @@ var _ = Describe("Cloud console command", func() { Context("TestGCPCredentialsResponseString", func() { It("It formats the output correctly", func() { r := &GCPCredentialsResponse{ - ProjectId: "foo", + ProjectID: "foo", } expect := `If this is your first time, run "gcloud auth login" and then gcloud config set project foo` @@ -379,7 +379,7 @@ gcloud config set project foo` Context("TestAWSCredentialsResponseFmtEformattedcredsxport", func() { It("It formats the output correctly", func() { r := &AWSCredentialsResponse{ - AccessKeyId: "foo", + AccessKeyID: "foo", SecretAccessKey: "bar", SessionToken: "baz", Region: "quux", @@ -396,7 +396,7 @@ export AWS_DEFAULT_REGION=quux` Context("TestGCPCredentialsResponseFmtExport", func() { It("It formats the output correctly", func() { r := &GCPCredentialsResponse{ - ProjectId: "foo", + ProjectID: "foo", } gcpExportFormatOut := `export CLOUDSDK_CORE_PROJECT=foo` diff --git a/cmd/ocm-backplane/cloud/token.go b/cmd/ocm-backplane/cloud/token.go index e18b6254..2836df41 100644 --- a/cmd/ocm-backplane/cloud/token.go +++ b/cmd/ocm-backplane/cloud/token.go @@ -2,10 +2,12 @@ package cloud import ( "fmt" - "github.com/openshift/backplane-cli/pkg/awsUtil" + + "github.com/spf13/cobra" + + "github.com/openshift/backplane-cli/pkg/awsutil" "github.com/openshift/backplane-cli/pkg/cli/config" "github.com/openshift/backplane-cli/pkg/utils" - "github.com/spf13/cobra" ) var tokenArgs struct { @@ -43,18 +45,18 @@ func runToken(*cobra.Command, []string) error { if err != nil { return fmt.Errorf("error retrieving backplane configuration: %w", err) } - svc, err := awsUtil.StsClientWithProxy(bpConfig.ProxyURL) + svc, err := awsutil.StsClientWithProxy(bpConfig.ProxyURL) if err != nil { return fmt.Errorf("error creating STS client: %w", err) } - result, err := awsUtil.AssumeRoleWithJWT(*ocmToken, tokenArgs.roleArn, svc) + result, err := awsutil.AssumeRoleWithJWT(*ocmToken, tokenArgs.roleArn, svc) if err != nil { return fmt.Errorf("failed to assume role with JWT: %w", err) } - credsResponse := awsUtil.AWSCredentialsResponse{ - AccessKeyId: *result.AccessKeyId, + credsResponse := awsutil.AWSCredentialsResponse{ + AccessKeyID: *result.AccessKeyId, SecretAccessKey: *result.SecretAccessKey, SessionToken: *result.SessionToken, Expiration: result.Expiration.String(), diff --git a/cmd/ocm-backplane/console/console.go b/cmd/ocm-backplane/console/console.go index 51768274..efb9417d 100644 --- a/cmd/ocm-backplane/console/console.go +++ b/cmd/ocm-backplane/console/console.go @@ -263,16 +263,16 @@ func runConsole(cmd *cobra.Command, argv []string) (err error) { if err != nil { return err } - clusterId := currentClusterInfo.ClusterID + clusterID := currentClusterInfo.ClusterID - consoleContainerName := fmt.Sprintf("console-%s", clusterId) + consoleContainerName := fmt.Sprintf("console-%s", clusterID) err = checkAndFindContainerURL(consoleContainerName, containerEngine) if err != nil { return err } - fmt.Printf("Starting console for cluster %s\n", clusterId) + fmt.Printf("Starting console for cluster %s\n", clusterID) // Get the RESTconfig from the current kubeconfig context. cf := genericclioptions.NewConfigFlags(true) @@ -362,14 +362,14 @@ func runConsole(cmd *cobra.Command, argv []string) (err error) { } // Set proxy URL to the container - proxyUrl, err := getProxyUrl() + proxyURL, err := getProxyURL() if err != nil { return err } - if proxyUrl != "" { + if proxyURL != "" { engRunArgs = append(engRunArgs, - "--env", fmt.Sprintf("HTTPS_PROXY=%s", proxyUrl), + "--env", fmt.Sprintf("HTTPS_PROXY=%s", proxyURL), ) } @@ -389,13 +389,13 @@ func runConsole(cmd *cobra.Command, argv []string) (err error) { consoleArgs.image, ) - c, err := utils.DefaultOCMInterface.GetClusterInfoByID(clusterId) + c, err := utils.DefaultOCMInterface.GetClusterInfoByID(clusterID) if err != nil { return err } p, ok := c.GetProduct() if !ok { - return fmt.Errorf("Could not get product information") + return fmt.Errorf("could not get product information") } logger.WithField("Command", fmt.Sprintf("`%s %s`", containerEngine, strings.Join(pullArgs, " "))).Infoln("Pulling image") @@ -408,10 +408,10 @@ func runConsole(cmd *cobra.Command, argv []string) (err error) { } branding := "dedicated" - documentationUrl := "https://docs.openshift.com/dedicated/4/" + documentationURL := "https://docs.openshift.com/dedicated/4/" if p.ID() == "rosa" { branding = "ocp" - documentationUrl = "https://docs.openshift.com/rosa/" + documentationURL = "https://docs.openshift.com/rosa/" } // Run the console container @@ -421,7 +421,7 @@ func runConsole(cmd *cobra.Command, argv []string) (err error) { "--public-dir=/opt/bridge/static", "-base-address", fmt.Sprintf("http://127.0.0.1:%s", consoleArgs.port), "-branding", branding, - "-documentation-base-url", documentationUrl, + "-documentation-base-url", documentationURL, "-user-settings-location", "localstorage", "-user-auth", "disabled", "-k8s-mode", "off-cluster", @@ -444,24 +444,24 @@ func runConsole(cmd *cobra.Command, argv []string) (err error) { } // Store the locally running console URL or splice it into a url provided in consoleArgs.url - consoleUrl, err := replaceConsoleUrl(fmt.Sprintf("http://127.0.0.1:%s", consoleArgs.port)) + consoleURL, err := replaceConsoleURL(fmt.Sprintf("http://127.0.0.1:%s", consoleArgs.port)) if err != nil { return fmt.Errorf("failed to replace url: %v", err) } - fmt.Printf("== Console is available at %s ==\n\n", consoleUrl) + fmt.Printf("== Console is available at %s ==\n\n", consoleURL) logger.WithField("Command", fmt.Sprintf("`%s %s`", containerEngine, strings.Join(containerArgs, " "))).Infoln("Running container") if consoleArgs.openBrowser { go func() { err := wait.PollImmediate(time.Second, 5*time.Second, func() (bool, error) { - return utils.CheckHealth(fmt.Sprintf("%s/health", consoleUrl)), nil + return utils.CheckHealth(fmt.Sprintf("%s/health", consoleURL)), nil }) if err != nil { logger.Warnf("failed waiting for container to become ready: %s", err) return } - err = browser.OpenURL(consoleUrl) + err = browser.OpenURL(consoleURL) if err != nil { logger.Warnf("failed opening a browser: %s", err) } @@ -484,7 +484,7 @@ func runConsole(cmd *cobra.Command, argv []string) (err error) { // If a url is provided via consoleArgs.url, then the original url pointing to the homepage of the locally-running // console will have its scheme and host inserted into consoleArgs.url. // This is commonly used when trying to open a console url provided by PagerDuty or an end-user. -func replaceConsoleUrl(original string) (string, error) { +func replaceConsoleURL(original string) (string, error) { if consoleArgs.url != "" { o, err := url.Parse(original) if err != nil { @@ -508,16 +508,16 @@ func replaceConsoleUrl(original string) (string, error) { } // Get the proxy url -func getProxyUrl() (proxyUrl string, err error) { +func getProxyURL() (proxyURL string, err error) { bpConfig, err := config.GetBackplaneConfiguration() if err != nil { return "", err } - proxyUrl = bpConfig.ProxyURL + proxyURL = bpConfig.ProxyURL - return proxyUrl, nil + return proxyURL, nil } // getImageFromCluster get the image from the console deployment diff --git a/cmd/ocm-backplane/console/console_test.go b/cmd/ocm-backplane/console/console_test.go index 879caee5..23371809 100644 --- a/cmd/ocm-backplane/console/console_test.go +++ b/cmd/ocm-backplane/console/console_test.go @@ -133,7 +133,7 @@ var _ = Describe("console command", func() { }) setupConfig := func() { - err := os.Setenv(info.BACKPLANE_PROXY_ENV_NAME, proxyURL) + err := os.Setenv(info.BackplaneProxyEnvName, proxyURL) Expect(err).To(BeNil()) err = utils.CreateTempKubeConfig(&testKubeCfg) diff --git a/cmd/ocm-backplane/login/login.go b/cmd/ocm-backplane/login/login.go index 2d1fa0c4..a03b737f 100644 --- a/cmd/ocm-backplane/login/login.go +++ b/cmd/ocm-backplane/login/login.go @@ -98,50 +98,50 @@ func runLogin(cmd *cobra.Command, argv []string) (err error) { } // Set proxy url to http client - proxyUrl := globalOpts.ProxyURL - if proxyUrl != "" { - err = utils.DefaultClientUtils.SetClientProxyUrl(proxyUrl) + proxyURL := globalOpts.ProxyURL + if proxyURL != "" { + err = utils.DefaultClientUtils.SetClientProxyURL(proxyURL) if err != nil { return err } - logger.Debugf("Using backplane Proxy URL: %s\n", proxyUrl) + logger.Debugf("Using backplane Proxy URL: %s\n", proxyURL) } - if len(proxyUrl) == 0 { - proxyUrl = bpConfig.ProxyURL + if len(proxyURL) == 0 { + proxyURL = bpConfig.ProxyURL } - clusterId, clusterName, err := utils.DefaultOCMInterface.GetTargetCluster(clusterKey) + clusterID, clusterName, err := utils.DefaultOCMInterface.GetTargetCluster(clusterKey) if err != nil { return err } logger.WithFields(logger.Fields{ - "ID": clusterId, + "ID": clusterID, "Name": clusterName}).Infoln("Target cluster") if globalOpts.Manager { - logger.WithField("Cluster ID", clusterId).Debugln("Finding managing cluster") - clusterId, clusterName, err = utils.DefaultOCMInterface.GetManagingCluster(clusterId) + logger.WithField("Cluster ID", clusterID).Debugln("Finding managing cluster") + clusterID, clusterName, err = utils.DefaultOCMInterface.GetManagingCluster(clusterID) if err != nil { return err } logger.WithFields(logger.Fields{ - "ID": clusterId, + "ID": clusterID, "Name": clusterName}).Infoln("Management cluster") } if globalOpts.Service { - logger.WithField("Cluster ID", clusterId).Debugln("Finding service cluster") - clusterId, clusterName, err = utils.DefaultOCMInterface.GetServiceCluster(clusterId) + logger.WithField("Cluster ID", clusterID).Debugln("Finding service cluster") + clusterID, clusterName, err = utils.DefaultOCMInterface.GetServiceCluster(clusterID) if err != nil { return err } logger.WithFields(logger.Fields{ - "ID": clusterId, + "ID": clusterID, "Name": clusterName}).Infoln("Service cluster") } @@ -156,16 +156,16 @@ func runLogin(cmd *cobra.Command, argv []string) (err error) { } // Get Backplane URL - bpUrl := globalOpts.BackplaneURL - if bpUrl == "" { - bpUrl = bpConfig.URL + bpURL := globalOpts.BackplaneURL + if bpURL == "" { + bpURL = bpConfig.URL } - if bpUrl == "" { + if bpURL == "" { return errors.New("empty backplane url - check your backplane-cli configuration") } - logger.Debugf("Using backplane URL: %s\n", bpUrl) + logger.Debugf("Using backplane URL: %s\n", bpURL) // Get ocm access token logger.Debugln("Finding ocm token") @@ -176,16 +176,16 @@ func runLogin(cmd *cobra.Command, argv []string) (err error) { logger.Debugln("Found OCM access token") // Not great if there's an error checking if the cluster is hibernating, but ignore it for now and continue - if isHibernating, _ := utils.DefaultOCMInterface.IsClusterHibernating(clusterId); isHibernating { + if isHibernating, _ := utils.DefaultOCMInterface.IsClusterHibernating(clusterID); isHibernating { // If it is hibernating, don't try to connect as it will fail return fmt.Errorf("cluster %s is hibernating, login failed", clusterKey) } // Query backplane-api for proxy url - bpAPIClusterUrl, err := doLogin(bpUrl, clusterId, *accessToken) + bpAPIClusterURL, err := doLogin(bpURL, clusterID, *accessToken) if err != nil { // If login failed, we try to find out if the cluster is hibernating - isHibernating, _ := utils.DefaultOCMInterface.IsClusterHibernating(clusterId) + isHibernating, _ := utils.DefaultOCMInterface.IsClusterHibernating(clusterID) if isHibernating { // Hibernating, print an error return fmt.Errorf("cluster %s is hibernating, login failed", clusterKey) @@ -198,7 +198,7 @@ func runLogin(cmd *cobra.Command, argv []string) (err error) { // Otherwise, return the failure return fmt.Errorf("can't login to cluster: %v", err) } - logger.WithField("URL", bpAPIClusterUrl).Debugln("Proxy") + logger.WithField("URL", bpAPIClusterURL).Debugln("Proxy") cf := genericclioptions.NewConfigFlags(true) rc, err := cf.ToRawKubeConfigLoader().RawConfig() @@ -219,12 +219,12 @@ func runLogin(cmd *cobra.Command, argv []string) (err error) { targetUser := api.NewAuthInfo() targetContext := api.NewContext() - targetCluster.Server = bpAPIClusterUrl + targetCluster.Server = bpAPIClusterURL // Add proxy URL to target cluster - if proxyUrl != "" { - targetCluster.ProxyURL = proxyUrl + if proxyURL != "" { + targetCluster.ProxyURL = proxyURL } targetUserNickName := getUsernameFromJWT(*accessToken) @@ -243,15 +243,15 @@ func runLogin(cmd *cobra.Command, argv []string) (err error) { rc.CurrentContext = targetContextNickName // Save the config. - err = login.SaveKubeConfig(clusterId, rc, args.multiCluster, args.kubeConfigPath) + err = login.SaveKubeConfig(clusterID, rc, args.multiCluster, args.kubeConfigPath) return err } // GetRestConfig returns a client-go *rest.Config which can be used to programmatically interact with the -// Kubernetes API of a provided clusterId -func GetRestConfig(bp config.BackplaneConfiguration, clusterId string) (*rest.Config, error) { - cluster, err := utils.DefaultOCMInterface.GetClusterInfoByID(clusterId) +// Kubernetes API of a provided clusterID +func GetRestConfig(bp config.BackplaneConfiguration, clusterID string) (*rest.Config, error) { + cluster, err := utils.DefaultOCMInterface.GetClusterInfoByID(clusterID) if err != nil { return nil, err } @@ -261,13 +261,13 @@ func GetRestConfig(bp config.BackplaneConfiguration, clusterId string) (*rest.Co return nil, err } - bpAPIClusterUrl, err := doLogin(bp.URL, clusterId, *accessToken) + bpAPIClusterURL, err := doLogin(bp.URL, clusterID, *accessToken) if err != nil { return nil, fmt.Errorf("failed to backplane login to cluster %s: %v", cluster.Name(), err) } cfg := &rest.Config{ - Host: bpAPIClusterUrl, + Host: bpAPIClusterURL, BearerToken: *accessToken, } @@ -282,8 +282,8 @@ func GetRestConfig(bp config.BackplaneConfiguration, clusterId string) (*rest.Co // GetRestConfigAsUser returns a client-go *rest.Config like GetRestConfig, but supports configuring an // impersonation username. Commonly, this is "backplane-cluster-admin" -func GetRestConfigAsUser(bp config.BackplaneConfiguration, clusterId, username string) (*rest.Config, error) { - cfg, err := GetRestConfig(bp, clusterId) +func GetRestConfigAsUser(bp config.BackplaneConfiguration, clusterID, username string) (*rest.Config, error) { + cfg, err := GetRestConfig(bp, clusterID) if err != nil { return nil, err } @@ -320,7 +320,7 @@ func getUsernameFromJWT(token string) string { } // doLogin returns the proxy url for the target cluster. -func doLogin(api, clusterId, accessToken string) (string, error) { +func doLogin(api, clusterID, accessToken string) (string, error) { client, err := utils.DefaultClientUtils.MakeRawBackplaneAPIClientWithAccessToken(api, accessToken) @@ -328,7 +328,7 @@ func doLogin(api, clusterId, accessToken string) (string, error) { return "", fmt.Errorf("unable to create backplane api client") } - resp, err := client.LoginCluster(context.TODO(), clusterId) + resp, err := client.LoginCluster(context.TODO(), clusterID) // Print the whole response if we can't parse it. Eg. 5xx error from http server. if err != nil { // trying to determine the error diff --git a/cmd/ocm-backplane/login/login_test.go b/cmd/ocm-backplane/login/login_test.go index f30b232c..91547fcb 100644 --- a/cmd/ocm-backplane/login/login_test.go +++ b/cmd/ocm-backplane/login/login_test.go @@ -34,12 +34,12 @@ var _ = Describe("Login command", func() { mockOcmInterface *mocks2.MockOCMInterface mockClientUtil *mocks2.MockClientUtils - testClusterId string + testClusterID string testToken string - trueClusterId string - managingClusterId string - backplaneAPIUri string - serviceClusterId string + trueClusterID string + managingClusterID string + backplaneAPIURI string + serviceClusterID string serviceClusterName string fakeResp *http.Response ) @@ -55,13 +55,13 @@ var _ = Describe("Login command", func() { mockClientUtil = mocks2.NewMockClientUtils(mockCtrl) utils.DefaultClientUtils = mockClientUtil - testClusterId = "test123" + testClusterID = "test123" testToken = "hello123" - trueClusterId = "trueID123" - managingClusterId = "managingID123" - serviceClusterId = "hs-sc-123456" + trueClusterID = "trueID123" + managingClusterID = "managingID123" + serviceClusterID = "hs-sc-123456" serviceClusterName = "hs-sc-654321" - backplaneAPIUri = "https://shard.apps" + backplaneAPIURI = "https://shard.apps" mockClientWithResp.EXPECT().LoginClusterWithResponse(gomock.Any(), gomock.Any()).Return(nil, nil).Times(0) @@ -76,7 +76,7 @@ var _ = Describe("Login command", func() { _ = clientcmd.ModifyConfig(clientcmd.NewDefaultPathOptions(), api.Config{}, true) clientcmd.UseModifyConfigLock = false - globalOpts.BackplaneURL = backplaneAPIUri + globalOpts.BackplaneURL = backplaneAPIURI }) AfterEach(func() { @@ -92,11 +92,11 @@ var _ = Describe("Login command", func() { Context("check ocm token", func() { It("Should fail when failed to get OCM token", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) mockOcmInterface.EXPECT().GetOCMAccessToken().Return(nil, errors.New("err")).AnyTimes() - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() - err := runLogin(nil, []string{testClusterId}) + err := runLogin(nil, []string{testClusterID}) Expect(err).ToNot(BeNil()) }) @@ -105,14 +105,14 @@ var _ = Describe("Login command", func() { err := utils.CreateTempKubeConfig(nil) Expect(err).To(BeNil()) globalOpts.ProxyURL = "https://squid.myproxy.com" - mockClientUtil.EXPECT().SetClientProxyUrl(globalOpts.ProxyURL).Return(nil) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockClientUtil.EXPECT().SetClientProxyURL(globalOpts.ProxyURL).Return(nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil) - mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil) - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterId)).Return(fakeResp, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil) + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).Return(fakeResp, nil) - err = runLogin(nil, []string{testClusterId}) + err = runLogin(nil, []string{testClusterID}) Expect(err).To(BeNil()) @@ -129,13 +129,13 @@ var _ = Describe("Login command", func() { err := utils.CreateTempKubeConfig(nil) Expect(err).To(BeNil()) globalOpts.BackplaneURL = "https://sadge.app" - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil) mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken("https://sadge.app", testToken).Return(mockClient, nil) - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterId)).Return(fakeResp, nil) + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).Return(fakeResp, nil) - err = runLogin(nil, []string{testClusterId}) + err = runLogin(nil, []string{testClusterID}) Expect(err).To(BeNil()) @@ -143,7 +143,7 @@ var _ = Describe("Login command", func() { Expect(err).To(BeNil()) Expect(cfg.CurrentContext).To(Equal("default/test123/anonymous")) Expect(len(cfg.Contexts)).To(Equal(1)) - Expect(cfg.Contexts["default/test123/anonymous"].Cluster).To(Equal(testClusterId)) + Expect(cfg.Contexts["default/test123/anonymous"].Cluster).To(Equal(testClusterID)) Expect(cfg.Contexts["default/test123/anonymous"].Namespace).To(Equal("default")) }) @@ -151,14 +151,14 @@ var _ = Describe("Login command", func() { err := utils.CreateTempKubeConfig(nil) Expect(err).To(BeNil()) globalOpts.ProxyURL = "https://squid.myproxy.com" - mockClientUtil.EXPECT().SetClientProxyUrl(globalOpts.ProxyURL).Return(nil) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockClientUtil.EXPECT().SetClientProxyURL(globalOpts.ProxyURL).Return(nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil) - mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil) - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterId)).Return(fakeResp, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil) + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).Return(fakeResp, nil) - err = runLogin(nil, []string{testClusterId}) + err = runLogin(nil, []string{testClusterID}) Expect(err).To(BeNil()) @@ -167,18 +167,18 @@ var _ = Describe("Login command", func() { Expect(err).To(BeNil()) Expect(cfg.CurrentContext).To(Equal("default/test123/anonymous")) Expect(len(cfg.Contexts)).To(Equal(1)) - Expect(cfg.Contexts["default/test123/anonymous"].Cluster).To(Equal(testClusterId)) - Expect(cfg.Clusters[testClusterId].ProxyURL).To(Equal(globalOpts.ProxyURL)) + Expect(cfg.Contexts["default/test123/anonymous"].Cluster).To(Equal(testClusterID)) + Expect(cfg.Clusters[testClusterID].ProxyURL).To(Equal(globalOpts.ProxyURL)) Expect(cfg.Contexts["default/test123/anonymous"].Namespace).To(Equal("default")) }) It("should fail if unable to create api client", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil) - mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(nil, errors.New("err")) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(nil, errors.New("err")) - err := runLogin(nil, []string{testClusterId}) + err := runLogin(nil, []string{testClusterID}) Expect(err).ToNot(BeNil()) }) @@ -193,13 +193,13 @@ var _ = Describe("Login command", func() { It("when running with a simple case should work as expected", func() { err := utils.CreateTempKubeConfig(nil) Expect(err).To(BeNil()) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil) - mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil) - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterId)).Return(fakeResp, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil) + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).Return(fakeResp, nil) - err = runLogin(nil, []string{testClusterId}) + err = runLogin(nil, []string{testClusterID}) Expect(err).To(BeNil()) @@ -207,49 +207,49 @@ var _ = Describe("Login command", func() { Expect(err).To(BeNil()) Expect(cfg.CurrentContext).To(Equal("default/test123/anonymous")) Expect(len(cfg.Contexts)).To(Equal(1)) - Expect(cfg.Contexts["default/test123/anonymous"].Cluster).To(Equal(testClusterId)) + Expect(cfg.Contexts["default/test123/anonymous"].Cluster).To(Equal(testClusterID)) Expect(cfg.Contexts["default/test123/anonymous"].Namespace).To(Equal("default")) }) It("Should fail when trying to find a non existent cluster", func() { mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return("", "", errors.New("err")) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return("", "", errors.New("err")) - err := runLogin(nil, []string{testClusterId}) + err := runLogin(nil, []string{testClusterID}) Expect(err).ToNot(BeNil()) }) It("should return the managing cluster if one is requested", func() { globalOpts.Manager = true - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().GetManagingCluster(trueClusterId).Return(managingClusterId, managingClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(managingClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().GetManagingCluster(trueClusterID).Return(managingClusterID, managingClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(managingClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil) - mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil) - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(managingClusterId)).Return(fakeResp, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil) + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(managingClusterID)).Return(fakeResp, nil) - err := runLogin(nil, []string{testClusterId}) + err := runLogin(nil, []string{testClusterID}) Expect(err).To(BeNil()) }) It("should failed if managing cluster not exist in same env", func() { globalOpts.Manager = true - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().GetManagingCluster(trueClusterId).Return( - managingClusterId, - managingClusterId, - fmt.Errorf("failed to find management cluster for cluster %s in %s env", testClusterId, "http://test.env"), + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().GetManagingCluster(trueClusterID).Return( + managingClusterID, + managingClusterID, + fmt.Errorf("failed to find management cluster for cluster %s in %s env", testClusterID, "http://test.env"), ) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(managingClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(managingClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(managingClusterId)).Return(fakeResp, nil).AnyTimes() + mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil).AnyTimes() + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(managingClusterID)).Return(fakeResp, nil).AnyTimes() - err := runLogin(nil, []string{testClusterId}) + err := runLogin(nil, []string{testClusterID}) Expect(err).NotTo(BeNil()) @@ -258,14 +258,14 @@ var _ = Describe("Login command", func() { It("should return the service cluster if hosted cluster is given", func() { globalOpts.Service = true - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().GetServiceCluster(trueClusterId).Return(serviceClusterId, serviceClusterName, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(serviceClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().GetServiceCluster(trueClusterID).Return(serviceClusterID, serviceClusterName, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(serviceClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil) - mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil) - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(serviceClusterId)).Return(fakeResp, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil) + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(serviceClusterID)).Return(fakeResp, nil) - err := runLogin(nil, []string{testClusterId}) + err := runLogin(nil, []string{testClusterID}) Expect(err).To(BeNil()) }) @@ -274,12 +274,12 @@ var _ = Describe("Login command", func() { err := utils.CreateTempKubeConfig(nil) Expect(err).To(BeNil()) globalOpts.ProxyURL = "https://squid.myproxy.com" - mockClientUtil.EXPECT().SetClientProxyUrl(globalOpts.ProxyURL).Return(nil) - mockOcmInterface.EXPECT().GetTargetCluster("configcluster").Return(testClusterId, "dummy_cluster", nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(testClusterId)).Return(false, nil).AnyTimes() + mockClientUtil.EXPECT().SetClientProxyURL(globalOpts.ProxyURL).Return(nil) + mockOcmInterface.EXPECT().GetTargetCluster("configcluster").Return(testClusterID, "dummy_cluster", nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(testClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil) - mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil) - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(testClusterId)).Return(fakeResp, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil) + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(testClusterID)).Return(fakeResp, nil) err = runLogin(nil, nil) @@ -296,13 +296,13 @@ var _ = Describe("Login command", func() { err := utils.CreateTempKubeConfig(nil) Expect(err).To(BeNil()) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil) - mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil) - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterId)).Return(fakeResp, errors.New("dial tcp: lookup yourproxy.com: no such host")) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil) + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).Return(fakeResp, errors.New("dial tcp: lookup yourproxy.com: no such host")) - err = runLogin(nil, []string{testClusterId}) + err = runLogin(nil, []string{testClusterID}) Expect(err).NotTo(BeNil()) @@ -311,7 +311,7 @@ var _ = Describe("Login command", func() { It("Check KUBECONFIG when logging into multiple clusters.", func() { globalOpts.Manager = false args.multiCluster = true - err := utils.ModifyTempKubeConfigFileName(trueClusterId) + err := utils.ModifyTempKubeConfigFileName(trueClusterID) Expect(err).To(BeNil()) kubePath, err := os.MkdirTemp("", ".kube") @@ -320,18 +320,18 @@ var _ = Describe("Login command", func() { err = login.SetKubeConfigBasePath(kubePath) Expect(err).To(BeNil()) - _, err = login.CreateClusterKubeConfig(trueClusterId, utils.GetDefaultKubeConfig()) + _, err = login.CreateClusterKubeConfig(trueClusterID, utils.GetDefaultKubeConfig()) Expect(err).To(BeNil()) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil) - mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil) - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterId)).Return(fakeResp, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil) + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).Return(fakeResp, nil) - err = runLogin(nil, []string{testClusterId}) + err = runLogin(nil, []string{testClusterID}) - Expect(os.Getenv("KUBECONFIG")).Should(ContainSubstring(trueClusterId)) + Expect(os.Getenv("KUBECONFIG")).Should(ContainSubstring(trueClusterID)) Expect(err).To(BeNil()) }) diff --git a/cmd/ocm-backplane/logout/logout.go b/cmd/ocm-backplane/logout/logout.go index 3f84679d..128a003d 100644 --- a/cmd/ocm-backplane/logout/logout.go +++ b/cmd/ocm-backplane/logout/logout.go @@ -4,7 +4,6 @@ import ( "fmt" "regexp" - "github.com/sirupsen/logrus" logger "github.com/sirupsen/logrus" "github.com/spf13/cobra" "k8s.io/client-go/tools/clientcmd" @@ -13,7 +12,7 @@ import ( "github.com/openshift/backplane-cli/pkg/utils" ) -// logoutCmd represents the logout command +// LogoutCmd represents the logout command var LogoutCmd = &cobra.Command{ Use: "logout", Short: "Logout of the current cluster by deleting the related reference in kubeconfig", @@ -29,13 +28,13 @@ func runLogout(cmd *cobra.Command, argv []string) error { // Logout specific cluster if len(argv) == 1 { - clusterId, _, err := utils.DefaultOCMInterface.GetTargetCluster(argv[0]) + clusterID, _, err := utils.DefaultOCMInterface.GetTargetCluster(argv[0]) if err != nil { return err } // Remove cluster specific Kubeconfig file - err = login.RemoveClusterKubeConfig(clusterId) + err = login.RemoveClusterKubeConfig(clusterID) if err != nil { return err } @@ -68,9 +67,9 @@ func runLogout(cmd *cobra.Command, argv []string) error { // backplane should only handle `logout` associated context // created with backplane itself, we check this via matching // the cluster server endpoint - backplaneServerRegex := regexp.MustCompile(utils.BackplaneApiUrlRegexp) + backplaneServerRegex := regexp.MustCompile(utils.BackplaneAPIURLRegexp) - logger.WithFields(logrus.Fields{ + logger.WithFields(logger.Fields{ "currentServer": currentServer, "currentUser": currentUser, "currentContext": rc.CurrentContext, diff --git a/cmd/ocm-backplane/logout/logout_test.go b/cmd/ocm-backplane/logout/logout_test.go index b14fde45..ed65c1db 100644 --- a/cmd/ocm-backplane/logout/logout_test.go +++ b/cmd/ocm-backplane/logout/logout_test.go @@ -9,14 +9,15 @@ import ( "github.com/golang/mock/gomock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/spf13/cobra" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/client-go/tools/clientcmd/api" + "github.com/openshift/backplane-cli/cmd/ocm-backplane/login" "github.com/openshift/backplane-cli/pkg/client/mocks" "github.com/openshift/backplane-cli/pkg/info" "github.com/openshift/backplane-cli/pkg/utils" mocks2 "github.com/openshift/backplane-cli/pkg/utils/mocks" - "github.com/spf13/cobra" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/client-go/tools/clientcmd/api" ) func MakeIoReader(s string) io.ReadCloser { @@ -33,10 +34,10 @@ var _ = Describe("Logout command", func() { mockOcmInterface *mocks2.MockOCMInterface mockClientUtil *mocks2.MockClientUtils - testClusterId string + testClusterID string testToken string - trueClusterId string - backplaneAPIUri string + trueClusterID string + backplaneAPIURI string fakeResp *http.Response @@ -59,10 +60,10 @@ var _ = Describe("Logout command", func() { mockClientWithResp.EXPECT().LoginClusterWithResponse(gomock.Any(), gomock.Any()).Return(nil, nil).Times(0) - testClusterId = "test123" + testClusterID = "test123" testToken = "hello123" - trueClusterId = "trueID123" - backplaneAPIUri = "https://api.integration.backplane.example.com" + trueClusterID = "trueID123" + backplaneAPIURI = "https://api.integration.backplane.example.com" fakeResp = &http.Response{ Body: MakeIoReader(`{"proxy_uri":"proxy", "statusCode":200, "message":"msg"}`), @@ -109,12 +110,12 @@ var _ = Describe("Logout command", func() { CurrentContext: "default/myopenshiftcluster/example.openshift", } - os.Setenv(info.BACKPLANE_URL_ENV_NAME, backplaneAPIUri) + os.Setenv(info.BackplaneURLEnvName, backplaneAPIURI) }) AfterEach(func() { utils.RemoveTempKubeConfig() - os.Setenv(info.BACKPLANE_URL_ENV_NAME, "") + os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) @@ -124,13 +125,13 @@ var _ = Describe("Logout command", func() { err := utils.CreateTempKubeConfig(&kubeConfig) Expect(err).To(BeNil()) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil).AnyTimes() - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterId)).Return(fakeResp, nil).AnyTimes() + mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil).AnyTimes() + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).Return(fakeResp, nil).AnyTimes() - loginCmd.SetArgs([]string{testClusterId}) + loginCmd.SetArgs([]string{testClusterID}) err = loginCmd.Execute() Expect(err).To(BeNil()) diff --git a/cmd/ocm-backplane/managedJob/createManagedJob.go b/cmd/ocm-backplane/managedJob/createManagedJob.go index 97413cff..dc9030d7 100644 --- a/cmd/ocm-backplane/managedJob/createManagedJob.go +++ b/cmd/ocm-backplane/managedJob/createManagedJob.go @@ -1,4 +1,4 @@ -package managedJob +package managedjob import ( "context" @@ -20,7 +20,7 @@ var ( canonicalName string params []string wait bool - clusterId string + clusterID string url string raw bool logs bool @@ -74,7 +74,7 @@ func runCreateManagedJob(cmd *cobra.Command, args []string) (err error) { } // ======== Initialize backplaneURL ======== - bpCluster, err := utils.DefaultClusterUtils.GetBackplaneCluster(options.clusterId) + bpCluster, err := utils.DefaultClusterUtils.GetBackplaneCluster(options.clusterID) if err != nil { return err } @@ -88,7 +88,7 @@ func runCreateManagedJob(cmd *cobra.Command, args []string) (err error) { backplaneHost := bpCluster.BackplaneHost clusterID := bpCluster.ClusterID - options.clusterId = clusterID + options.clusterID = clusterID if options.url != "" { backplaneHost = options.url @@ -143,7 +143,7 @@ func initParams(cmd *cobra.Command, argv []string) (err error) { options.canonicalName = canonicalNameArg // init Cluster key - options.clusterId, err = cmd.Flags().GetString("cluster-id") + options.clusterID, err = cmd.Flags().GetString("cluster-id") if err != nil { return err } @@ -181,7 +181,7 @@ func createJob(client BackplaneApi.ClientInterface) (*BackplaneApi.Job, error) { } // call create end point - resp, err := client.CreateJob(context.TODO(), options.clusterId, createJob) + resp, err := client.CreateJob(context.TODO(), options.clusterID, createJob) if err != nil { return nil, err @@ -201,7 +201,7 @@ func createJob(client BackplaneApi.ClientInterface) (*BackplaneApi.Job, error) { // render job details fmt.Printf("%s\nJobId: %s\n", *createResp.JSON200.Message, *createResp.JSON200.JobId) if options.raw { - _ = utils.RenderJsonBytes(createResp.JSON200) + _ = utils.RenderJSONBytes(createResp.JSON200) } return createResp.JSON200, nil } @@ -273,7 +273,7 @@ func fetchJobLogs(client BackplaneApi.ClientInterface, job *BackplaneApi.Job) er version := "v2" follow := true - resp, err := client.GetJobLogs(context.TODO(), options.clusterId, *job.JobId, &BackplaneApi.GetJobLogsParams{Version: &version, Follow: &follow}) + resp, err := client.GetJobLogs(context.TODO(), options.clusterID, *job.JobId, &BackplaneApi.GetJobLogsParams{Version: &version, Follow: &follow}) if err != nil { return err } @@ -290,7 +290,7 @@ func fetchJobLogs(client BackplaneApi.ClientInterface, job *BackplaneApi.Job) er } func getJobStatus(client BackplaneApi.ClientInterface, job *BackplaneApi.Job) (BackplaneApi.JobStatusStatus, error) { - jobResp, err := client.GetRun(context.TODO(), options.clusterId, *job.JobId) + jobResp, err := client.GetRun(context.TODO(), options.clusterID, *job.JobId) if err != nil { return "", err diff --git a/cmd/ocm-backplane/managedJob/createManagedJob_test.go b/cmd/ocm-backplane/managedJob/createManagedJob_test.go index bc89cd6e..ec5eb58a 100644 --- a/cmd/ocm-backplane/managedJob/createManagedJob_test.go +++ b/cmd/ocm-backplane/managedJob/createManagedJob_test.go @@ -1,4 +1,4 @@ -package managedJob +package managedjob import ( "bytes" @@ -29,10 +29,10 @@ var _ = Describe("managedJob create command", func() { mockOcmInterface *mocks2.MockOCMInterface mockClientUtil *mocks2.MockClientUtils - testClusterId string + testClusterID string testToken string - trueClusterId string - proxyUri string + trueClusterID string + proxyURI string fakeResp *http.Response fakeJobResp *http.Response @@ -51,10 +51,10 @@ var _ = Describe("managedJob create command", func() { mockClientUtil = mocks2.NewMockClientUtils(mockCtrl) utils.DefaultClientUtils = mockClientUtil - testClusterId = "test123" + testClusterID = "test123" testToken = "hello123" - trueClusterId = "trueID123" - proxyUri = "https://shard.apps" + trueClusterID = "trueID123" + proxyURI = "https://shard.apps" sut = NewManagedJobCmd() @@ -92,25 +92,25 @@ var _ = Describe("managedJob create command", func() { // Clear config file _ = clientcmd.ModifyConfig(clientcmd.NewDefaultPathOptions(), api.Config{}, true) - os.Setenv(info.BACKPLANE_URL_ENV_NAME, proxyUri) + os.Setenv(info.BackplaneURLEnvName, proxyURI) }) AfterEach(func() { - os.Setenv(info.BACKPLANE_URL_ENV_NAME, "") + os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) Context("create managed job", func() { It("when running with a simple case should work as expected", func() { // It should query for the internal cluster id first - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) // Then it will look for the backplane shard - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(gomock.Any()).Return(mockClient, nil) - mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterId, gomock.Any()).Return(fakeResp, nil) + mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterID, gomock.Any()).Return(fakeResp, nil) - sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).To(BeNil()) @@ -118,55 +118,55 @@ var _ = Describe("managedJob create command", func() { It("should respect url flag", func() { // It should query for the internal cluster id first - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) // Then it will look for the backplane shard - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://newbackplane.url").Return(mockClient, nil) - mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterId, gomock.Any()).Return(fakeResp, nil) + mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterID, gomock.Any()).Return(fakeResp, nil) - sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterId, "--url", "https://newbackplane.url"}) + sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterID, "--url", "https://newbackplane.url"}) err := sut.Execute() Expect(err).To(BeNil()) }) It("should fail when backplane did not return a 200", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(gomock.Any()).Return(mockClient, nil) - mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterId, gomock.Any()).Return(nil, errors.New("err")) + mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterID, gomock.Any()).Return(nil, errors.New("err")) - sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) }) It("should fail when backplane returns a non parsable response", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(gomock.Any()).Return(mockClient, nil) fakeResp.Body = MakeIoReader("Sad") - mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterId, gomock.Any()).Return(fakeResp, errors.New("err")) + mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterID, gomock.Any()).Return(fakeResp, errors.New("err")) - sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) }) It("should wait for job to be finished", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://newbackplane.url").Return(mockClient, nil) - mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterId, gomock.Any()).Return(fakeResp, nil) - mockClient.EXPECT().GetRun(gomock.Any(), trueClusterId, gomock.Eq("jid")).Return(fakeJobResp, nil) + mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterID, gomock.Any()).Return(fakeResp, nil) + mockClient.EXPECT().GetRun(gomock.Any(), trueClusterID, gomock.Eq("jid")).Return(fakeJobResp, nil) - sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterId, "--url", "https://newbackplane.url", "--wait"}) + sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterID, "--url", "https://newbackplane.url", "--wait"}) outPuts := bytes.NewBufferString("") sut.SetOut(outPuts) @@ -186,14 +186,14 @@ var _ = Describe("managedJob create command", func() { } fakeJobResp.Header.Add("Content-Type", "json") - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://newbackplane.url").Return(mockClient, nil) - mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterId, gomock.Any()).Return(fakeResp, nil).AnyTimes() - mockClient.EXPECT().GetRun(gomock.Any(), trueClusterId, gomock.Eq("jid")).Return(fakeJobResp, nil).AnyTimes() + mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterID, gomock.Any()).Return(fakeResp, nil).AnyTimes() + mockClient.EXPECT().GetRun(gomock.Any(), trueClusterID, gomock.Eq("jid")).Return(fakeJobResp, nil).AnyTimes() - sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterId, "--url", "https://newbackplane.url", "--wait"}) + sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterID, "--url", "https://newbackplane.url", "--wait"}) err := sut.Execute() Expect(err).NotTo(BeNil()) @@ -207,14 +207,14 @@ var _ = Describe("managedJob create command", func() { } fakeJobResp.Header.Add("Content-Type", "json") - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://newbackplane.url").Return(mockClient, nil) - mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterId, gomock.Any()).Return(fakeResp, nil).AnyTimes() - mockClient.EXPECT().GetRun(gomock.Any(), trueClusterId, gomock.Eq("jid")).Return(fakeJobResp, nil).AnyTimes() + mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterID, gomock.Any()).Return(fakeResp, nil).AnyTimes() + mockClient.EXPECT().GetRun(gomock.Any(), trueClusterID, gomock.Eq("jid")).Return(fakeJobResp, nil).AnyTimes() - sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterId, "--url", "https://newbackplane.url", "--wait"}) + sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterID, "--url", "https://newbackplane.url", "--wait"}) outPuts := bytes.NewBufferString("") sut.SetOut(outPuts) @@ -227,15 +227,15 @@ var _ = Describe("managedJob create command", func() { }) It("should stream the log of the job if it is in running status", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://newbackplane.url").Return(mockClient, nil) - mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterId, gomock.Any()).Return(fakeResp, nil) - mockClient.EXPECT().GetRun(gomock.Any(), trueClusterId, gomock.Eq("jid")).Return(fakeJobResp, nil) + mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterID, gomock.Any()).Return(fakeResp, nil) + mockClient.EXPECT().GetRun(gomock.Any(), trueClusterID, gomock.Eq("jid")).Return(fakeJobResp, nil) mockClient.EXPECT().GetJobLogs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(fakeJobResp, nil) - sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterId, "--url", "https://newbackplane.url", "--logs"}) + sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterID, "--url", "https://newbackplane.url", "--logs"}) outPuts := bytes.NewBufferString("") sut.SetOut(outPuts) @@ -254,14 +254,14 @@ var _ = Describe("managedJob create command", func() { StatusCode: http.StatusOK, } fakeJobResp.Header.Add("Content-Type", "json") - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://newbackplane.url").Return(mockClient, nil) - mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterId, gomock.Any()).Return(fakeResp, nil) - mockClient.EXPECT().GetRun(gomock.Any(), trueClusterId, gomock.Eq("jid")).Return(fakeJobResp, nil).AnyTimes() + mockClient.EXPECT().CreateJob(gomock.Any(), trueClusterID, gomock.Any()).Return(fakeResp, nil) + mockClient.EXPECT().GetRun(gomock.Any(), trueClusterID, gomock.Eq("jid")).Return(fakeJobResp, nil).AnyTimes() - sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterId, "--url", "https://newbackplane.url", "--logs"}) + sut.SetArgs([]string{"create", "SREP/something", "--cluster-id", testClusterID, "--url", "https://newbackplane.url", "--logs"}) err := sut.Execute() diff --git a/cmd/ocm-backplane/managedJob/deleteManagedJob.go b/cmd/ocm-backplane/managedJob/deleteManagedJob.go index d076121a..bcf369ba 100644 --- a/cmd/ocm-backplane/managedJob/deleteManagedJob.go +++ b/cmd/ocm-backplane/managedJob/deleteManagedJob.go @@ -13,7 +13,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ -package managedJob +package managedjob import ( "context" diff --git a/cmd/ocm-backplane/managedJob/deleteManagedJob_test.go b/cmd/ocm-backplane/managedJob/deleteManagedJob_test.go index fcb1106d..28d6007a 100644 --- a/cmd/ocm-backplane/managedJob/deleteManagedJob_test.go +++ b/cmd/ocm-backplane/managedJob/deleteManagedJob_test.go @@ -1,4 +1,4 @@ -package managedJob +package managedjob import ( "errors" @@ -8,13 +8,14 @@ import ( "github.com/golang/mock/gomock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/spf13/cobra" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/client-go/tools/clientcmd/api" + "github.com/openshift/backplane-cli/pkg/client/mocks" "github.com/openshift/backplane-cli/pkg/info" "github.com/openshift/backplane-cli/pkg/utils" mocks2 "github.com/openshift/backplane-cli/pkg/utils/mocks" - "github.com/spf13/cobra" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/client-go/tools/clientcmd/api" ) var _ = Describe("managedJob delete command", func() { @@ -25,11 +26,11 @@ var _ = Describe("managedJob delete command", func() { mockOcmInterface *mocks2.MockOCMInterface mockClientUtil *mocks2.MockClientUtils - testClusterId string + testClusterID string testToken string - trueClusterId string - proxyUri string - testJobId string + trueClusterID string + proxyURI string + testJobID string fakeResp *http.Response @@ -46,11 +47,11 @@ var _ = Describe("managedJob delete command", func() { mockClientUtil = mocks2.NewMockClientUtils(mockCtrl) utils.DefaultClientUtils = mockClientUtil - testClusterId = "test123" + testClusterID = "test123" testToken = "hello123" - trueClusterId = "trueID123" - proxyUri = "https://shard.apps" - testJobId = "jid123" + trueClusterID = "trueID123" + proxyURI = "https://shard.apps" + testJobID = "jid123" sut = NewManagedJobCmd() @@ -63,67 +64,67 @@ var _ = Describe("managedJob delete command", func() { // Clear config file _ = clientcmd.ModifyConfig(clientcmd.NewDefaultPathOptions(), api.Config{}, true) - os.Setenv(info.BACKPLANE_URL_ENV_NAME, proxyUri) + os.Setenv(info.BackplaneURLEnvName, proxyURI) }) AfterEach(func() { - os.Setenv(info.BACKPLANE_URL_ENV_NAME, "") + os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) Context("delete managed job", func() { It("when running with a simple case should work as expected", func() { // It should query for the internal cluster id first - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) // Then it will look for the backplane shard - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) - mockClient.EXPECT().DeleteJob(gomock.Any(), trueClusterId, gomock.Eq(testJobId)).Return(fakeResp, nil) + mockClient.EXPECT().DeleteJob(gomock.Any(), trueClusterID, gomock.Eq(testJobID)).Return(fakeResp, nil) - sut.SetArgs([]string{"delete", testJobId, "--cluster-id", testClusterId, "-y"}) + sut.SetArgs([]string{"delete", testJobID, "--cluster-id", testClusterID, "-y"}) err := sut.Execute() Expect(err).To(BeNil()) }) It("should respect url flag", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) // Then it will look for the backplane shard - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://newbackplane.url").Return(mockClient, nil) - mockClient.EXPECT().DeleteJob(gomock.Any(), trueClusterId, gomock.Eq(testJobId)).Return(fakeResp, nil) + mockClient.EXPECT().DeleteJob(gomock.Any(), trueClusterID, gomock.Eq(testJobID)).Return(fakeResp, nil) - sut.SetArgs([]string{"delete", testJobId, "--cluster-id", testClusterId, "--url", "https://newbackplane.url", "-y"}) + sut.SetArgs([]string{"delete", testJobID, "--cluster-id", testClusterID, "--url", "https://newbackplane.url", "-y"}) err := sut.Execute() Expect(err).To(BeNil()) }) It("should fail when backplane did not return a 200", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) - mockClient.EXPECT().DeleteJob(gomock.Any(), trueClusterId, gomock.Eq(testJobId)).Return(nil, errors.New("err")) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) + mockClient.EXPECT().DeleteJob(gomock.Any(), trueClusterID, gomock.Eq(testJobID)).Return(nil, errors.New("err")) - sut.SetArgs([]string{"delete", testJobId, "--cluster-id", testClusterId, "-y"}) + sut.SetArgs([]string{"delete", testJobID, "--cluster-id", testClusterID, "-y"}) err := sut.Execute() Expect(err).ToNot(BeNil()) }) It("should not work when backplane returns a non parsable response with 200 return", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) fakeResp.Body = MakeIoReader("Sad") - mockClient.EXPECT().DeleteJob(gomock.Any(), trueClusterId, gomock.Eq(testJobId)).Return(fakeResp, errors.New("err")) + mockClient.EXPECT().DeleteJob(gomock.Any(), trueClusterID, gomock.Eq(testJobID)).Return(fakeResp, errors.New("err")) - sut.SetArgs([]string{"delete", testJobId, "--cluster-id", testClusterId, "-y"}) + sut.SetArgs([]string{"delete", testJobID, "--cluster-id", testClusterID, "-y"}) err := sut.Execute() Expect(err).ToNot(BeNil()) diff --git a/cmd/ocm-backplane/managedJob/getManagedJob.go b/cmd/ocm-backplane/managedJob/getManagedJob.go index 2e84a302..c15922eb 100644 --- a/cmd/ocm-backplane/managedJob/getManagedJob.go +++ b/cmd/ocm-backplane/managedJob/getManagedJob.go @@ -13,7 +13,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ -package managedJob +package managedjob import ( "context" @@ -23,6 +23,7 @@ import ( "github.com/spf13/cobra" BackplaneApi "github.com/openshift/backplane-api/pkg/client" + "github.com/openshift/backplane-cli/pkg/cli/config" "github.com/openshift/backplane-cli/pkg/utils" ) diff --git a/cmd/ocm-backplane/managedJob/getManagedJob_test.go b/cmd/ocm-backplane/managedJob/getManagedJob_test.go index c23472cd..c2b6f63e 100644 --- a/cmd/ocm-backplane/managedJob/getManagedJob_test.go +++ b/cmd/ocm-backplane/managedJob/getManagedJob_test.go @@ -1,4 +1,4 @@ -package managedJob +package managedjob import ( "errors" @@ -8,13 +8,14 @@ import ( "github.com/golang/mock/gomock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/spf13/cobra" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/client-go/tools/clientcmd/api" + "github.com/openshift/backplane-cli/pkg/client/mocks" "github.com/openshift/backplane-cli/pkg/info" "github.com/openshift/backplane-cli/pkg/utils" mocks2 "github.com/openshift/backplane-cli/pkg/utils/mocks" - "github.com/spf13/cobra" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/client-go/tools/clientcmd/api" ) var _ = Describe("managedJob get command", func() { @@ -25,11 +26,11 @@ var _ = Describe("managedJob get command", func() { mockOcmInterface *mocks2.MockOCMInterface mockClientUtil *mocks2.MockClientUtils - testClusterId string + testClusterID string testToken string - trueClusterId string - proxyUri string - testJobId string + trueClusterID string + proxyURI string + testJobID string fakeResp *http.Response fakeRespMultiple *http.Response @@ -47,11 +48,11 @@ var _ = Describe("managedJob get command", func() { mockClientUtil = mocks2.NewMockClientUtils(mockCtrl) utils.DefaultClientUtils = mockClientUtil - testClusterId = "test123" + testClusterID = "test123" testToken = "hello123" - trueClusterId = "trueID123" - proxyUri = "https://shard.apps" - testJobId = "jid123" + trueClusterID = "trueID123" + proxyURI = "https://shard.apps" + testJobID = "jid123" sut = NewManagedJobCmd() @@ -118,66 +119,66 @@ var _ = Describe("managedJob get command", func() { // Clear config file _ = clientcmd.ModifyConfig(clientcmd.NewDefaultPathOptions(), api.Config{}, true) - os.Setenv(info.BACKPLANE_URL_ENV_NAME, proxyUri) + os.Setenv(info.BackplaneURLEnvName, proxyURI) }) AfterEach(func() { - os.Setenv(info.BACKPLANE_URL_ENV_NAME, "") + os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) Context("get a single managed job", func() { It("when running with a simple case should work as expected for single job", func() { // It should query for the internal cluster id first - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) // Then it will look for the backplane shard - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) - mockClient.EXPECT().GetRun(gomock.Any(), trueClusterId, gomock.Eq(testJobId)).Return(fakeResp, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) + mockClient.EXPECT().GetRun(gomock.Any(), trueClusterID, gomock.Eq(testJobID)).Return(fakeResp, nil) - sut.SetArgs([]string{"get", testJobId, "--cluster-id", testClusterId}) + sut.SetArgs([]string{"get", testJobID, "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).To(BeNil()) }) It("should respect url flag", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) // Then it will look for the backplane shard - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://newbackplane.url").Return(mockClient, nil) - mockClient.EXPECT().GetRun(gomock.Any(), trueClusterId, gomock.Eq(testJobId)).Return(fakeResp, nil) + mockClient.EXPECT().GetRun(gomock.Any(), trueClusterID, gomock.Eq(testJobID)).Return(fakeResp, nil) - sut.SetArgs([]string{"get", testJobId, "--cluster-id", testClusterId, "--url", "https://newbackplane.url"}) + sut.SetArgs([]string{"get", testJobID, "--cluster-id", testClusterID, "--url", "https://newbackplane.url"}) err := sut.Execute() Expect(err).To(BeNil()) }) It("should fail when backplane did not return a 200", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) - mockClient.EXPECT().GetRun(gomock.Any(), trueClusterId, gomock.Eq(testJobId)).Return(nil, errors.New("err")) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) + mockClient.EXPECT().GetRun(gomock.Any(), trueClusterID, gomock.Eq(testJobID)).Return(nil, errors.New("err")) - sut.SetArgs([]string{"get", testJobId, "--cluster-id", testClusterId}) + sut.SetArgs([]string{"get", testJobID, "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) }) It("should not work when backplane returns a non parsable response", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) fakeResp.Body = MakeIoReader("Sad") - mockClient.EXPECT().GetRun(gomock.Any(), trueClusterId, gomock.Eq(testJobId)).Return(fakeResp, errors.New("err")) + mockClient.EXPECT().GetRun(gomock.Any(), trueClusterID, gomock.Eq(testJobID)).Return(fakeResp, errors.New("err")) - sut.SetArgs([]string{"get", testJobId, "--cluster-id", testClusterId}) + sut.SetArgs([]string{"get", testJobID, "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) @@ -187,55 +188,55 @@ var _ = Describe("managedJob get command", func() { Context("get a all managed jobs", func() { It("when running with a simple case should work as expected", func() { // It should query for the internal cluster id first - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) // Then it will look for the backplane shard - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) - mockClient.EXPECT().GetAllJobs(gomock.Any(), trueClusterId).Return(fakeRespMultiple, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) + mockClient.EXPECT().GetAllJobs(gomock.Any(), trueClusterID).Return(fakeRespMultiple, nil) - sut.SetArgs([]string{"get", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"get", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).To(BeNil()) }) It("should respect url flag", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) // Then it will look for the backplane shard - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://newbackplane.url").Return(mockClient, nil) - mockClient.EXPECT().GetAllJobs(gomock.Any(), trueClusterId).Return(fakeRespMultiple, nil) + mockClient.EXPECT().GetAllJobs(gomock.Any(), trueClusterID).Return(fakeRespMultiple, nil) - sut.SetArgs([]string{"get", "--cluster-id", testClusterId, "--url", "https://newbackplane.url"}) + sut.SetArgs([]string{"get", "--cluster-id", testClusterID, "--url", "https://newbackplane.url"}) err := sut.Execute() Expect(err).To(BeNil()) }) It("should fail when backplane did not return a 200", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) - mockClient.EXPECT().GetAllJobs(gomock.Any(), trueClusterId).Return(nil, errors.New("err")) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) + mockClient.EXPECT().GetAllJobs(gomock.Any(), trueClusterID).Return(nil, errors.New("err")) - sut.SetArgs([]string{"get", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"get", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) }) It("should not work when backplane returns a non parsable response", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) fakeRespMultiple.Body = MakeIoReader("Sad") - mockClient.EXPECT().GetAllJobs(gomock.Any(), trueClusterId).Return(fakeRespMultiple, errors.New("err")) + mockClient.EXPECT().GetAllJobs(gomock.Any(), trueClusterID).Return(fakeRespMultiple, errors.New("err")) - sut.SetArgs([]string{"get", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"get", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) diff --git a/cmd/ocm-backplane/managedJob/logsManagedJob.go b/cmd/ocm-backplane/managedJob/logsManagedJob.go index deb18cb4..728c061a 100644 --- a/cmd/ocm-backplane/managedJob/logsManagedJob.go +++ b/cmd/ocm-backplane/managedJob/logsManagedJob.go @@ -1,4 +1,4 @@ -package managedJob +package managedjob import ( "context" @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" BackplaneApi "github.com/openshift/backplane-api/pkg/client" + "github.com/openshift/backplane-cli/pkg/cli/config" "github.com/openshift/backplane-cli/pkg/utils" ) diff --git a/cmd/ocm-backplane/managedJob/managedJob.go b/cmd/ocm-backplane/managedJob/managedJob.go index 7384fbf5..6286c97a 100644 --- a/cmd/ocm-backplane/managedJob/managedJob.go +++ b/cmd/ocm-backplane/managedJob/managedJob.go @@ -1,4 +1,4 @@ -package managedJob +package managedjob import ( "github.com/spf13/cobra" diff --git a/cmd/ocm-backplane/managedJob/managedJob_suite_test.go b/cmd/ocm-backplane/managedJob/managedJob_suite_test.go index b8a16876..0f06d6a6 100644 --- a/cmd/ocm-backplane/managedJob/managedJob_suite_test.go +++ b/cmd/ocm-backplane/managedJob/managedJob_suite_test.go @@ -1,4 +1,4 @@ -package managedJob +package managedjob import ( "io" diff --git a/cmd/ocm-backplane/monitoring/monitoring.go b/cmd/ocm-backplane/monitoring/monitoring.go index b75a0cdd..cfb744c1 100644 --- a/cmd/ocm-backplane/monitoring/monitoring.go +++ b/cmd/ocm-backplane/monitoring/monitoring.go @@ -5,8 +5,9 @@ import ( "net/http" "strings" - "github.com/openshift/backplane-cli/pkg/monitoring" "github.com/spf13/cobra" + + "github.com/openshift/backplane-cli/pkg/monitoring" ) var MonitoringCmd = &cobra.Command{ @@ -50,7 +51,7 @@ func init() { "The port the remote application listens on. (Default will be picked by server based on application's conventional port.)", ) flags.StringVarP( - &monitoring.MonitoringOpts.OriginUrl, + &monitoring.MonitoringOpts.OriginURL, "origin", "u", "", diff --git a/cmd/ocm-backplane/root.go b/cmd/ocm-backplane/root.go index 4e86e525..3ddcdedc 100644 --- a/cmd/ocm-backplane/root.go +++ b/cmd/ocm-backplane/root.go @@ -19,6 +19,9 @@ package main import ( "os" + log "github.com/sirupsen/logrus" + "github.com/spf13/cobra" + "github.com/openshift/backplane-cli/cmd/ocm-backplane/cloud" "github.com/openshift/backplane-cli/cmd/ocm-backplane/config" "github.com/openshift/backplane-cli/cmd/ocm-backplane/console" @@ -34,8 +37,6 @@ import ( "github.com/openshift/backplane-cli/cmd/ocm-backplane/upgrade" "github.com/openshift/backplane-cli/cmd/ocm-backplane/version" "github.com/openshift/backplane-cli/pkg/cli/globalflags" - log "github.com/sirupsen/logrus" - "github.com/spf13/cobra" ) // rootCmd represents the base command when called without any subcommands @@ -69,11 +70,11 @@ func init() { rootCmd.AddCommand(elevate.ElevateCmd) rootCmd.AddCommand(login.LoginCmd) rootCmd.AddCommand(logout.LogoutCmd) - rootCmd.AddCommand(managedJob.NewManagedJobCmd()) + rootCmd.AddCommand(managedjob.NewManagedJobCmd()) rootCmd.AddCommand(script.NewScriptCmd()) rootCmd.AddCommand(status.StatusCmd) rootCmd.AddCommand(session.NewCmdSession()) - rootCmd.AddCommand(testJob.NewTestJobCommand()) + rootCmd.AddCommand(testjob.NewTestJobCommand()) rootCmd.AddCommand(upgrade.UpgradeCmd) rootCmd.AddCommand(version.VersionCmd) rootCmd.AddCommand(monitoring.MonitoringCmd) diff --git a/cmd/ocm-backplane/script/describeScript.go b/cmd/ocm-backplane/script/describeScript.go index 6e7f9a7c..8b441adc 100644 --- a/cmd/ocm-backplane/script/describeScript.go +++ b/cmd/ocm-backplane/script/describeScript.go @@ -23,6 +23,7 @@ import ( "github.com/spf13/cobra" bpclient "github.com/openshift/backplane-api/pkg/client" + "github.com/openshift/backplane-cli/pkg/utils" ) @@ -74,13 +75,13 @@ func newDescribeScriptCmd() *cobra.Command { } // ======== Transform clusterKey to clusterID (clusterKey can be name, ID external ID) ======== - clusterId, _, err := utils.DefaultOCMInterface.GetTargetCluster(clusterKey) + clusterID, _, err := utils.DefaultOCMInterface.GetTargetCluster(clusterKey) if err != nil { return err } // ======== Call Endpoint ======== - resp, err := client.GetScriptsByCluster(context.TODO(), clusterId, &bpclient.GetScriptsByClusterParams{Scriptname: &args[0]}) + resp, err := client.GetScriptsByCluster(context.TODO(), clusterID, &bpclient.GetScriptsByClusterParams{Scriptname: &args[0]}) if err != nil { return err diff --git a/cmd/ocm-backplane/script/describeScript_test.go b/cmd/ocm-backplane/script/describeScript_test.go index cc832b2c..f00b847a 100644 --- a/cmd/ocm-backplane/script/describeScript_test.go +++ b/cmd/ocm-backplane/script/describeScript_test.go @@ -13,6 +13,7 @@ import ( "k8s.io/client-go/tools/clientcmd/api" bpclient "github.com/openshift/backplane-api/pkg/client" + "github.com/openshift/backplane-cli/pkg/client/mocks" "github.com/openshift/backplane-cli/pkg/info" "github.com/openshift/backplane-cli/pkg/utils" @@ -27,12 +28,12 @@ var _ = Describe("describe script command", func() { mockOcmInterface *mocks2.MockOCMInterface mockClientUtil *mocks2.MockClientUtils - testClusterId string + testClusterID string testToken string - trueClusterId string + trueClusterID string testScriptName string - proxyUri string + proxyURI string fakeResp *http.Response @@ -49,12 +50,12 @@ var _ = Describe("describe script command", func() { mockClientUtil = mocks2.NewMockClientUtils(mockCtrl) utils.DefaultClientUtils = mockClientUtil - testClusterId = "test123" + testClusterID = "test123" testToken = "hello123" - trueClusterId = "trueID123" + trueClusterID = "trueID123" testScriptName = "CEE/abc" - proxyUri = "https://shard.apps" + proxyURI = "https://shard.apps" sut = NewScriptCmd() @@ -81,39 +82,39 @@ var _ = Describe("describe script command", func() { // Clear config file _ = clientcmd.ModifyConfig(clientcmd.NewDefaultPathOptions(), api.Config{}, true) - os.Setenv(info.BACKPLANE_URL_ENV_NAME, proxyUri) + os.Setenv(info.BackplaneURLEnvName, proxyURI) }) AfterEach(func() { - os.Setenv(info.BACKPLANE_URL_ENV_NAME, "") + os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) Context("describe script", func() { It("when running with a simple case should work as expected", func() { // It should query for the internal cluster id first - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) // Then it will look for the backplane shard - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(gomock.Any()).Return(mockClient, nil) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterId, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(fakeResp, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterID, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(fakeResp, nil) - sut.SetArgs([]string{"describe", testScriptName, "--cluster-id", testClusterId}) + sut.SetArgs([]string{"describe", testScriptName, "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).To(BeNil()) }) It("should respect url flag", func() { - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://newbackplane.url").Return(mockClient, nil) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterId, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(fakeResp, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterID, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(fakeResp, nil) - sut.SetArgs([]string{"describe", testScriptName, "--cluster-id", testClusterId, "--url", "https://newbackplane.url"}) + sut.SetArgs([]string{"describe", testScriptName, "--cluster-id", testClusterID, "--url", "https://newbackplane.url"}) err := sut.Execute() Expect(err).To(BeNil()) @@ -125,8 +126,8 @@ var _ = Describe("describe script command", func() { mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq("configcluster")).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://api-backplane.apps.something.com").Return(mockClient, nil) - mockOcmInterface.EXPECT().GetTargetCluster("configcluster").Return(trueClusterId, testClusterId, nil) - mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterId, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(fakeResp, nil) + mockOcmInterface.EXPECT().GetTargetCluster("configcluster").Return(trueClusterID, testClusterID, nil) + mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterID, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(fakeResp, nil) sut.SetArgs([]string{"describe", testScriptName}) err = sut.Execute() @@ -135,14 +136,14 @@ var _ = Describe("describe script command", func() { }) It("should fail when backplane did not return a 200", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(gomock.Any()).Return(mockClient, nil) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterId, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(nil, errors.New("err")) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterID, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(nil, errors.New("err")) - sut.SetArgs([]string{"describe", testScriptName, "--cluster-id", testClusterId}) + sut.SetArgs([]string{"describe", testScriptName, "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) @@ -156,14 +157,14 @@ var _ = Describe("describe script command", func() { } fakeRespBlank.Header.Add("Content-Type", "json") - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(gomock.Any()).Return(mockClient, nil) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterId, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(fakeRespBlank, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterID, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(fakeRespBlank, nil) - sut.SetArgs([]string{"describe", testScriptName, "--cluster-id", testClusterId}) + sut.SetArgs([]string{"describe", testScriptName, "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) @@ -188,29 +189,29 @@ var _ = Describe("describe script command", func() { } fakeRespNoEnv.Header.Add("Content-Type", "json") - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(gomock.Any()).Return(mockClient, nil) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterId, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(fakeRespNoEnv, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterID, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(fakeRespNoEnv, nil) - sut.SetArgs([]string{"describe", testScriptName, "--cluster-id", testClusterId}) + sut.SetArgs([]string{"describe", testScriptName, "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).To(BeNil()) }) It("should not work when backplane returns a non parsable response with 200 return", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(gomock.Any()).Return(mockClient, nil) fakeResp.Body = MakeIoReader("Sad") - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterId, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(fakeResp, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterID, &bpclient.GetScriptsByClusterParams{Scriptname: &testScriptName}).Return(fakeResp, nil) - sut.SetArgs([]string{"describe", testScriptName, "--cluster-id", testClusterId}) + sut.SetArgs([]string{"describe", testScriptName, "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) diff --git a/cmd/ocm-backplane/script/listScripts.go b/cmd/ocm-backplane/script/listScripts.go index 1f2e3a0e..a6cda670 100644 --- a/cmd/ocm-backplane/script/listScripts.go +++ b/cmd/ocm-backplane/script/listScripts.go @@ -23,6 +23,7 @@ import ( "github.com/spf13/cobra" bpclient "github.com/openshift/backplane-api/pkg/client" + "github.com/openshift/backplane-cli/pkg/utils" ) @@ -74,15 +75,13 @@ func newListScriptCmd() *cobra.Command { } // ======== Transform clusterKey to clusterID (clusterKey can be name, ID external ID) ======== - clusterId, _, err := utils.DefaultOCMInterface.GetTargetCluster(clusterKey) + clusterID, _, err := utils.DefaultOCMInterface.GetTargetCluster(clusterKey) if err != nil { return err } - - // ======== Call Endpoint ======== - resp, err := client.GetScriptsByCluster(context.TODO(), clusterId, &bpclient.GetScriptsByClusterParams{}) + resp, err := client.GetScriptsByCluster(context.TODO(), clusterID, &bpclient.GetScriptsByClusterParams{}) if err != nil { return err diff --git a/cmd/ocm-backplane/script/listScripts_test.go b/cmd/ocm-backplane/script/listScripts_test.go index e2f1739d..c4e70645 100644 --- a/cmd/ocm-backplane/script/listScripts_test.go +++ b/cmd/ocm-backplane/script/listScripts_test.go @@ -10,11 +10,12 @@ import ( . "github.com/onsi/gomega" bpclient "github.com/openshift/backplane-api/pkg/client" + "github.com/spf13/cobra" + "github.com/openshift/backplane-cli/pkg/client/mocks" "github.com/openshift/backplane-cli/pkg/info" "github.com/openshift/backplane-cli/pkg/utils" mocks2 "github.com/openshift/backplane-cli/pkg/utils/mocks" - "github.com/spf13/cobra" ) var _ = Describe("list script command", func() { @@ -25,13 +26,13 @@ var _ = Describe("list script command", func() { mockOcmInterface *mocks2.MockOCMInterface mockClientUtil *mocks2.MockClientUtils - testClusterId string + testClusterID string testToken string - trueClusterId string + trueClusterID string //testKubeCfg api.Config - testJobId string + testJobID string - proxyUri string + proxyURI string fakeResp *http.Response @@ -48,12 +49,12 @@ var _ = Describe("list script command", func() { mockClientUtil = mocks2.NewMockClientUtils(mockCtrl) utils.DefaultClientUtils = mockClientUtil - testClusterId = "test123" + testClusterID = "test123" testToken = "hello123" - trueClusterId = "trueID123" - testJobId = "jid123" + trueClusterID = "trueID123" + testJobID = "jid123" - proxyUri = "https://shard.apps" + proxyURI = "https://shard.apps" sut = NewScriptCmd() @@ -77,11 +78,11 @@ var _ = Describe("list script command", func() { } fakeResp.Header.Add("Content-Type", "json") - os.Setenv(info.BACKPLANE_URL_ENV_NAME, proxyUri) + os.Setenv(info.BackplaneURLEnvName, proxyURI) }) AfterEach(func() { - os.Setenv(info.BACKPLANE_URL_ENV_NAME, "") + os.Setenv(info.BackplaneURLEnvName, "") utils.RemoveTempKubeConfig() mockCtrl.Finish() }) @@ -89,15 +90,15 @@ var _ = Describe("list script command", func() { Context("list scripts", func() { It("when running with a simple case should work as expected", func() { // It should query for the internal cluster id first - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) // Then it will look for the backplane shard - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(gomock.Any()).Return(mockClient, nil) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterId, &bpclient.GetScriptsByClusterParams{}).Return(fakeResp, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterID, &bpclient.GetScriptsByClusterParams{}).Return(fakeResp, nil) - sut.SetArgs([]string{"list", testJobId, "--cluster-id", testClusterId}) + sut.SetArgs([]string{"list", testJobID, "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).To(BeNil()) @@ -105,13 +106,13 @@ var _ = Describe("list script command", func() { It("should respect url flag", func() { // Then it will look for the backplane shard - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://newbackplane.url").Return(mockClient, nil) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterId, &bpclient.GetScriptsByClusterParams{}).Return(fakeResp, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterID, &bpclient.GetScriptsByClusterParams{}).Return(fakeResp, nil) - sut.SetArgs([]string{"list", testJobId, "--cluster-id", testClusterId, "--url", "https://newbackplane.url"}) + sut.SetArgs([]string{"list", testJobID, "--cluster-id", testClusterID, "--url", "https://newbackplane.url"}) err := sut.Execute() Expect(err).To(BeNil()) @@ -123,54 +124,54 @@ var _ = Describe("list script command", func() { mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq("configcluster")).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://api-backplane.apps.something.com").Return(mockClient, nil) - mockOcmInterface.EXPECT().GetTargetCluster("configcluster").Return(trueClusterId, testClusterId, nil) - mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterId, &bpclient.GetScriptsByClusterParams{}).Return(fakeResp, nil) + mockOcmInterface.EXPECT().GetTargetCluster("configcluster").Return(trueClusterID, testClusterID, nil) + mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterID, &bpclient.GetScriptsByClusterParams{}).Return(fakeResp, nil) - sut.SetArgs([]string{"list", testJobId}) + sut.SetArgs([]string{"list", testJobID}) err = sut.Execute() Expect(err).To(BeNil()) }) It("should fail when backplane did not return a 200", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(gomock.Any()).Return(mockClient, nil) - mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterId, &bpclient.GetScriptsByClusterParams{}).Return(nil, errors.New("err")) + mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterID, &bpclient.GetScriptsByClusterParams{}).Return(nil, errors.New("err")) - sut.SetArgs([]string{"list", testJobId, "--cluster-id", testClusterId}) + sut.SetArgs([]string{"list", testJobID, "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) }) It("should not work when backplane returns a non parsable response with 200 return", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(gomock.Any()).Return(mockClient, nil) fakeResp.Body = MakeIoReader("Sad") - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterId, &bpclient.GetScriptsByClusterParams{}).Return(fakeResp, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterID, &bpclient.GetScriptsByClusterParams{}).Return(fakeResp, nil) - sut.SetArgs([]string{"list", testJobId, "--cluster-id", testClusterId}) + sut.SetArgs([]string{"list", testJobID, "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) }) It("should handle an empty list of scripts without errors", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(gomock.Any()).Return(mockClient, nil) fakeResp.Body = MakeIoReader("[]") - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterId, &bpclient.GetScriptsByClusterParams{}).Return(fakeResp, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockClient.EXPECT().GetScriptsByCluster(gomock.Any(), trueClusterID, &bpclient.GetScriptsByClusterParams{}).Return(fakeResp, nil) - sut.SetArgs([]string{"list", testJobId, "--cluster-id", testClusterId}) + sut.SetArgs([]string{"list", testJobID, "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) diff --git a/cmd/ocm-backplane/session/session.go b/cmd/ocm-backplane/session/session.go index 7227ca8b..38707796 100644 --- a/cmd/ocm-backplane/session/session.go +++ b/cmd/ocm-backplane/session/session.go @@ -5,10 +5,11 @@ import ( "path/filepath" "strings" + "github.com/spf13/cobra" + "github.com/openshift/backplane-cli/pkg/cli/globalflags" "github.com/openshift/backplane-cli/pkg/cli/session" "github.com/openshift/backplane-cli/pkg/info" - "github.com/spf13/cobra" ) var globalOpts = &globalflags.GlobalOptions{} @@ -27,7 +28,7 @@ func NewCmdSession() *cobra.Command { RunE: session.RunCommand, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { validEnvs := []string{} - files, err := os.ReadDir(filepath.Join(os.Getenv("HOME"), info.BACKPLANE_DEFAULT_SESSION_DIRECTORY)) + files, err := os.ReadDir(filepath.Join(os.Getenv("HOME"), info.BackplaneDefaultSessionDirectory)) if err != nil { return validEnvs, cobra.ShellCompDirectiveNoFileComp } @@ -55,7 +56,7 @@ func NewCmdSession() *cobra.Command { ) sessionCmd.Flags().StringVarP( - &options.ClusterId, + &options.ClusterID, "cluster-id", "c", "", diff --git a/cmd/ocm-backplane/testJob/createTestJob.go b/cmd/ocm-backplane/testJob/createTestJob.go index d6d86563..3cd2a171 100644 --- a/cmd/ocm-backplane/testJob/createTestJob.go +++ b/cmd/ocm-backplane/testJob/createTestJob.go @@ -1,4 +1,4 @@ -package testJob +package testjob import ( "bytes" @@ -17,6 +17,7 @@ import ( "sigs.k8s.io/yaml" backplaneApi "github.com/openshift/backplane-api/pkg/client" + "github.com/openshift/backplane-cli/pkg/cli/config" "github.com/openshift/backplane-cli/pkg/utils" ) @@ -170,7 +171,7 @@ func runCreateTestJob(cmd *cobra.Command, args []string) error { fmt.Printf("%s\nTestId: %s\n", *createResp.JSON200.Message, createResp.JSON200.TestId) if rawFlag { - _ = utils.RenderJsonBytes(createResp.JSON200) + _ = utils.RenderJSONBytes(createResp.JSON200) } return nil } diff --git a/cmd/ocm-backplane/testJob/createTestJob_test.go b/cmd/ocm-backplane/testJob/createTestJob_test.go index db269f87..785f0ba6 100644 --- a/cmd/ocm-backplane/testJob/createTestJob_test.go +++ b/cmd/ocm-backplane/testJob/createTestJob_test.go @@ -1,4 +1,4 @@ -package testJob +package testjob import ( "errors" @@ -60,10 +60,10 @@ var _ = Describe("testJob create command", func() { mockOcmInterface *mocks2.MockOCMInterface mockClientUtil *mocks2.MockClientUtils - testClusterId string + testClusterID string testToken string - trueClusterId string - proxyUri string + trueClusterID string + proxyURI string tempDir string fakeResp *http.Response @@ -88,10 +88,10 @@ var _ = Describe("testJob create command", func() { mockClientUtil = mocks2.NewMockClientUtils(mockCtrl) utils.DefaultClientUtils = mockClientUtil - testClusterId = "test123" + testClusterID = "test123" testToken = "hello123" - trueClusterId = "trueID123" - proxyUri = "https://shard.apps" + trueClusterID = "trueID123" + proxyURI = "https://shard.apps" sut = NewTestJobCommand() @@ -107,11 +107,11 @@ var _ = Describe("testJob create command", func() { StatusCode: http.StatusOK, } fakeResp.Header.Add("Content-Type", "json") - os.Setenv(info.BACKPLANE_URL_ENV_NAME, proxyUri) + os.Setenv(info.BackplaneURLEnvName, proxyURI) }) AfterEach(func() { - os.Setenv(info.BACKPLANE_URL_ENV_NAME, "") + os.Setenv(info.BackplaneURLEnvName, "") _ = os.RemoveAll(tempDir) // Clear kube config file utils.RemoveTempKubeConfig() @@ -122,13 +122,13 @@ var _ = Describe("testJob create command", func() { It("when running with a simple case should work as expected", func() { mockOcmInterface.EXPECT().IsProduction().Return(false, nil) // It should query for the internal cluster id first - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) - mockClient.EXPECT().CreateTestScriptRun(gomock.Any(), trueClusterId, gomock.Any()).Return(fakeResp, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) + mockClient.EXPECT().CreateTestScriptRun(gomock.Any(), trueClusterID, gomock.Any()).Return(fakeResp, nil) - sut.SetArgs([]string{"create", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"create", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).To(BeNil()) @@ -137,20 +137,20 @@ var _ = Describe("testJob create command", func() { It("should respect url flag", func() { mockOcmInterface.EXPECT().IsProduction().Return(false, nil) // It should query for the internal cluster id first - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://newbackplane.url").Return(mockClient, nil) - mockClient.EXPECT().CreateTestScriptRun(gomock.Any(), trueClusterId, gomock.Any()).Return(fakeResp, nil) + mockClient.EXPECT().CreateTestScriptRun(gomock.Any(), trueClusterID, gomock.Any()).Return(fakeResp, nil) - sut.SetArgs([]string{"create", "--cluster-id", testClusterId, "--url", "https://newbackplane.url"}) + sut.SetArgs([]string{"create", "--cluster-id", testClusterID, "--url", "https://newbackplane.url"}) err := sut.Execute() Expect(err).To(BeNil()) }) It("Should able use the current logged in cluster if non specified and retrieve from config file", func() { - os.Setenv(info.BACKPLANE_URL_ENV_NAME, "https://api-backplane.apps.something.com") + os.Setenv(info.BackplaneURLEnvName, "https://api-backplane.apps.something.com") mockOcmInterface.EXPECT().IsProduction().Return(false, nil) err := utils.CreateTempKubeConfig(nil) Expect(err).To(BeNil()) @@ -167,13 +167,13 @@ var _ = Describe("testJob create command", func() { It("should fail when backplane did not return a 200", func() { mockOcmInterface.EXPECT().IsProduction().Return(false, nil) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) - mockClient.EXPECT().CreateTestScriptRun(gomock.Any(), trueClusterId, gomock.Any()).Return(nil, errors.New("err")) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) + mockClient.EXPECT().CreateTestScriptRun(gomock.Any(), trueClusterID, gomock.Any()).Return(nil, errors.New("err")) - sut.SetArgs([]string{"create", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"create", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) @@ -181,14 +181,14 @@ var _ = Describe("testJob create command", func() { It("should fail when backplane returns a non parsable response", func() { mockOcmInterface.EXPECT().IsProduction().Return(false, nil) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) fakeResp.Body = MakeIoReader("Sad") - mockClient.EXPECT().CreateTestScriptRun(gomock.Any(), trueClusterId, gomock.Any()).Return(fakeResp, errors.New("err")) + mockClient.EXPECT().CreateTestScriptRun(gomock.Any(), trueClusterID, gomock.Any()).Return(fakeResp, errors.New("err")) - sut.SetArgs([]string{"create", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"create", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) @@ -196,14 +196,14 @@ var _ = Describe("testJob create command", func() { It("should fail when metadata is not found/invalid", func() { mockOcmInterface.EXPECT().IsProduction().Return(false, nil) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) _ = os.Remove(path.Join(tempDir, "metadata.yaml")) - sut.SetArgs([]string{"create", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"create", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) @@ -211,14 +211,14 @@ var _ = Describe("testJob create command", func() { It("should fail when script file is not found/invalid", func() { mockOcmInterface.EXPECT().IsProduction().Return(false, nil) - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) _ = os.Remove(path.Join(tempDir, "script.sh")) - sut.SetArgs([]string{"create", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"create", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) @@ -229,7 +229,7 @@ var _ = Describe("testJob create command", func() { _ = os.Remove(path.Join(tempDir, "script.sh")) - sut.SetArgs([]string{"create", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"create", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) @@ -240,7 +240,7 @@ var _ = Describe("testJob create command", func() { _ = os.Remove(path.Join(tempDir, "script.sh")) - sut.SetArgs([]string{"create", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"create", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) @@ -266,13 +266,13 @@ echo_touch "Hello" _ = os.WriteFile(path.Join(tempDir, "scripts", "lib.sh"), []byte(lib), 0600) mockOcmInterface.EXPECT().IsProduction().Return(false, nil) // It should query for the internal cluster id first - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) - mockClient.EXPECT().CreateTestScriptRun(gomock.Any(), trueClusterId, gomock.Any()).Return(fakeResp, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) + mockClient.EXPECT().CreateTestScriptRun(gomock.Any(), trueClusterID, gomock.Any()).Return(fakeResp, nil) - sut.SetArgs([]string{"create", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"create", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).To(BeNil()) diff --git a/cmd/ocm-backplane/testJob/getTestJob.go b/cmd/ocm-backplane/testJob/getTestJob.go index 445c3b9e..bc53745c 100644 --- a/cmd/ocm-backplane/testJob/getTestJob.go +++ b/cmd/ocm-backplane/testJob/getTestJob.go @@ -1,4 +1,4 @@ -package testJob +package testjob import ( "context" @@ -8,6 +8,7 @@ import ( "github.com/spf13/cobra" backplaneApi "github.com/openshift/backplane-api/pkg/client" + "github.com/openshift/backplane-cli/pkg/cli/config" "github.com/openshift/backplane-cli/pkg/utils" ) @@ -15,7 +16,7 @@ import ( func newGetTestJobCommand() *cobra.Command { cmd := &cobra.Command{ - Use: "get ", + Use: "get ", Short: "Get a backplane testjob resource", Args: cobra.ExactArgs(1), SilenceUsage: true, @@ -72,7 +73,7 @@ func runGetTestJob(cmd *cobra.Command, args []string) error { } // It is always 1 in length, enforced by cobra - testId := args[0] + testID := args[0] client, err := utils.DefaultClientUtils.MakeRawBackplaneAPIClient(backplaneHost) if err != nil { @@ -80,7 +81,7 @@ func runGetTestJob(cmd *cobra.Command, args []string) error { } // ======== Call Endpoint ======== - resp, err := client.GetTestScriptRun(context.TODO(), clusterID, testId) + resp, err := client.GetTestScriptRun(context.TODO(), clusterID, testID) // ======== Render Results ======== if err != nil { @@ -100,7 +101,7 @@ func runGetTestJob(cmd *cobra.Command, args []string) error { fmt.Printf("TestId: %s, Status: %s\n", createResp.JSON200.TestId, *createResp.JSON200.Status) if rawFlag { - _ = utils.RenderJsonBytes(createResp.JSON200) + _ = utils.RenderJSONBytes(createResp.JSON200) } return nil } diff --git a/cmd/ocm-backplane/testJob/getTestJobLogs.go b/cmd/ocm-backplane/testJob/getTestJobLogs.go index feeb9d2e..76e6e041 100644 --- a/cmd/ocm-backplane/testJob/getTestJobLogs.go +++ b/cmd/ocm-backplane/testJob/getTestJobLogs.go @@ -1,4 +1,4 @@ -package testJob +package testjob import ( "context" @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" bpClient "github.com/openshift/backplane-api/pkg/client" + "github.com/openshift/backplane-cli/pkg/cli/config" "github.com/openshift/backplane-cli/pkg/utils" ) @@ -80,7 +81,7 @@ func runGetTestJobLogs(cmd *cobra.Command, args []string) error { } // It is always 1 in length, enforced by cobra - testId := args[0] + testID := args[0] client, err := utils.DefaultClientUtils.MakeRawBackplaneAPIClient(backplaneHost) if err != nil { @@ -89,7 +90,7 @@ func runGetTestJobLogs(cmd *cobra.Command, args []string) error { // ======== Call Endpoint ======== version := "v2" - resp, err := client.GetTestScriptRunLogs(context.TODO(), clusterID, testId, &bpClient.GetTestScriptRunLogsParams{Version: &version, Follow: &logFlag}) + resp, err := client.GetTestScriptRunLogs(context.TODO(), clusterID, testID, &bpClient.GetTestScriptRunLogsParams{Version: &version, Follow: &logFlag}) // ======== Render Results ======== if err != nil { diff --git a/cmd/ocm-backplane/testJob/getTestJob_test.go b/cmd/ocm-backplane/testJob/getTestJob_test.go index 5bd0c14f..278be706 100644 --- a/cmd/ocm-backplane/testJob/getTestJob_test.go +++ b/cmd/ocm-backplane/testJob/getTestJob_test.go @@ -1,4 +1,4 @@ -package testJob +package testjob import ( "errors" @@ -25,10 +25,10 @@ var _ = Describe("testJob get command", func() { mockOcmInterface *mocks2.MockOCMInterface mockClientUtil *mocks2.MockClientUtils - testClusterId string + testClusterID string testToken string - trueClusterId string - proxyUri string + trueClusterID string + proxyURI string tempDir string fakeResp *http.Response @@ -53,10 +53,10 @@ var _ = Describe("testJob get command", func() { mockClientUtil = mocks2.NewMockClientUtils(mockCtrl) utils.DefaultClientUtils = mockClientUtil - testClusterId = "test123" + testClusterID = "test123" testToken = "hello123" - trueClusterId = "trueID123" - proxyUri = "https://shard.apps" + trueClusterID = "trueID123" + proxyURI = "https://shard.apps" sut = NewTestJobCommand() @@ -72,11 +72,11 @@ var _ = Describe("testJob get command", func() { StatusCode: http.StatusOK, } fakeResp.Header.Add("Content-Type", "json") - os.Setenv(info.BACKPLANE_URL_ENV_NAME, proxyUri) + os.Setenv(info.BackplaneURLEnvName, proxyURI) }) AfterEach(func() { - os.Setenv(info.BACKPLANE_URL_ENV_NAME, "") + os.Setenv(info.BackplaneURLEnvName, "") _ = os.RemoveAll(tempDir) mockCtrl.Finish() }) @@ -84,13 +84,13 @@ var _ = Describe("testJob get command", func() { Context("get test job", func() { It("when running with a simple case should work as expected", func() { // It should query for the internal cluster id first - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) - mockClient.EXPECT().GetTestScriptRun(gomock.Any(), trueClusterId, gomock.Eq("tid")).Return(fakeResp, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) + mockClient.EXPECT().GetTestScriptRun(gomock.Any(), trueClusterID, gomock.Eq("tid")).Return(fakeResp, nil) - sut.SetArgs([]string{"get", "tid", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"get", "tid", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).To(BeNil()) @@ -98,41 +98,41 @@ var _ = Describe("testJob get command", func() { It("should respect url flag", func() { // It should query for the internal cluster id first - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) // Then it will look for the backplane shard - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClient("https://newbackplane.url").Return(mockClient, nil) - mockClient.EXPECT().GetTestScriptRun(gomock.Any(), trueClusterId, gomock.Eq("tid")).Return(fakeResp, nil) + mockClient.EXPECT().GetTestScriptRun(gomock.Any(), trueClusterID, gomock.Eq("tid")).Return(fakeResp, nil) - sut.SetArgs([]string{"get", "tid", "--cluster-id", testClusterId, "--url", "https://newbackplane.url"}) + sut.SetArgs([]string{"get", "tid", "--cluster-id", testClusterID, "--url", "https://newbackplane.url"}) err := sut.Execute() Expect(err).To(BeNil()) }) It("should fail when backplane did not return a 200", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) - mockClient.EXPECT().GetTestScriptRun(gomock.Any(), trueClusterId, gomock.Eq("tid")).Return(nil, errors.New("err")) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) + mockClient.EXPECT().GetTestScriptRun(gomock.Any(), trueClusterID, gomock.Eq("tid")).Return(nil, errors.New("err")) - sut.SetArgs([]string{"get", "tid", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"get", "tid", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) }) It("should fail when backplane returns a non parsable response", func() { - mockOcmInterface.EXPECT().GetTargetCluster(testClusterId).Return(trueClusterId, testClusterId, nil) - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() - mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyUri).Return(mockClient, nil) + mockClientUtil.EXPECT().MakeRawBackplaneAPIClient(proxyURI).Return(mockClient, nil) fakeResp.Body = MakeIoReader("Sad") - mockClient.EXPECT().GetTestScriptRun(gomock.Any(), trueClusterId, gomock.Eq("tid")).Return(fakeResp, errors.New("err")) + mockClient.EXPECT().GetTestScriptRun(gomock.Any(), trueClusterID, gomock.Eq("tid")).Return(fakeResp, errors.New("err")) - sut.SetArgs([]string{"get", "tid", "--cluster-id", testClusterId}) + sut.SetArgs([]string{"get", "tid", "--cluster-id", testClusterID}) err := sut.Execute() Expect(err).ToNot(BeNil()) diff --git a/cmd/ocm-backplane/testJob/testJob.go b/cmd/ocm-backplane/testJob/testJob.go index cd1a5818..a63b272d 100644 --- a/cmd/ocm-backplane/testJob/testJob.go +++ b/cmd/ocm-backplane/testJob/testJob.go @@ -1,4 +1,4 @@ -package testJob +package testjob import ( "github.com/spf13/cobra" diff --git a/cmd/ocm-backplane/testJob/testJob_suite_test.go b/cmd/ocm-backplane/testJob/testJob_suite_test.go index 442cbdde..257992a5 100644 --- a/cmd/ocm-backplane/testJob/testJob_suite_test.go +++ b/cmd/ocm-backplane/testJob/testJob_suite_test.go @@ -1,4 +1,4 @@ -package testJob +package testjob import ( "io" diff --git a/internal/github/github.go b/internal/github/github.go index 8909cd06..bb70e3cc 100644 --- a/internal/github/github.go +++ b/internal/github/github.go @@ -22,7 +22,7 @@ var ( ) const ( - gitHubApiEndPoint = "https://api.github.com/repos/openshift/backplane-cli" + gitHubAPIEndPoint = "https://api.github.com/repos/openshift/backplane-cli" assetTemplateName = "ocm-backplane_%s_%s_%s.tar.gz" // version, GOOS, GOARCH timeout = 10 * time.Second ) @@ -153,7 +153,7 @@ func (c *ClientConfig) Option(opts ...ClientOption) { } func (c *ClientConfig) Default() { if c.BaseURL == "" { - c.BaseURL = gitHubApiEndPoint + c.BaseURL = gitHubAPIEndPoint } } @@ -171,7 +171,7 @@ type OSConfig struct { func (osConfig *OSConfig) FindAssetURL(latestVersion upgrade.Release) (string, bool) { for _, asset := range latestVersion.Assets { if osConfig.isMatchingArchive(asset, latestVersion.TagName) { - return asset.DownloadUrl, true + return asset.DownloadURL, true } } diff --git a/internal/github/github_test.go b/internal/github/github_test.go index add97839..3a7e7aa4 100644 --- a/internal/github/github_test.go +++ b/internal/github/github_test.go @@ -129,7 +129,7 @@ func TestFindAssetURL(t *testing.T) { Assets: []upgrade.ReleaseAsset{ { Name: "ocm-backplane_0.0.1_Darwin_arm64.tar.gz", - DownloadUrl: "https://github.com/openshift/backplane-cli/releases/download/v0.0.1/ocm-backplane_0.0.1_Darwin_arm64.tar.gz", + DownloadURL: "https://github.com/openshift/backplane-cli/releases/download/v0.0.1/ocm-backplane_0.0.1_Darwin_arm64.tar.gz", }, }, }, @@ -146,7 +146,7 @@ func TestFindAssetURL(t *testing.T) { Assets: []upgrade.ReleaseAsset{ { Name: "ocm-backplane_0.0.1_Linux_arm64.tar.gz", - DownloadUrl: "https://github.com/openshift/backplane-cli/releases/download/v0.0.1/ocm-backplane_0.0.1_Linux_arm64.tar.gz", + DownloadURL: "https://github.com/openshift/backplane-cli/releases/download/v0.0.1/ocm-backplane_0.0.1_Linux_arm64.tar.gz", }, }, }, @@ -163,11 +163,11 @@ func TestFindAssetURL(t *testing.T) { Assets: []upgrade.ReleaseAsset{ { Name: "ocm-backplane_0.0.1_Linux_arm64.tar.gz", - DownloadUrl: "https://github.com/openshift/backplane-cli/releases/download/v0.0.1/ocm-backplane_0.0.1_Linux_arm64.tar.gz", + DownloadURL: "https://github.com/openshift/backplane-cli/releases/download/v0.0.1/ocm-backplane_0.0.1_Linux_arm64.tar.gz", }, { Name: "ocm-backplane_0.0.1_Darwin_arm64.tar.gz", - DownloadUrl: "https://github.com/openshift/backplane-cli/releases/download/v0.0.1/ocm-backplane_0.0.1_Darwin_arm64.tar.gz", + DownloadURL: "https://github.com/openshift/backplane-cli/releases/download/v0.0.1/ocm-backplane_0.0.1_Darwin_arm64.tar.gz", }, }, }, @@ -184,14 +184,14 @@ func TestFindAssetURL(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - downloadUrl, assertMatch := tc.osConfig.FindAssetURL(tc.LatestRelease) + downloadURL, assertMatch := tc.osConfig.FindAssetURL(tc.LatestRelease) if assertMatch != tc.match { t.Errorf("expected res to be %t got %t", assertMatch, tc.match) } - if downloadUrl != tc.ExpectedAsert { - t.Errorf("expected res to be %s got %s", tc.ExpectedAsert, downloadUrl) + if downloadURL != tc.ExpectedAsert { + t.Errorf("expected res to be %s got %s", tc.ExpectedAsert, downloadURL) } }) diff --git a/internal/upgrade/upgrade.go b/internal/upgrade/upgrade.go index 96590ee1..8112a938 100644 --- a/internal/upgrade/upgrade.go +++ b/internal/upgrade/upgrade.go @@ -25,7 +25,7 @@ type Release struct { // ReleaseAsset defines the name and download url type ReleaseAsset struct { Name string `json:"name"` - DownloadUrl string `json:"browser_download_url"` + DownloadURL string `json:"browser_download_url"` } // GitServer defines generic functions for getting the latest release and archive diff --git a/pkg/awsUtil/credentials.go b/pkg/awsutil/credentials.go similarity index 89% rename from pkg/awsUtil/credentials.go rename to pkg/awsutil/credentials.go index 46214434..f0b0024e 100644 --- a/pkg/awsUtil/credentials.go +++ b/pkg/awsutil/credentials.go @@ -1,8 +1,9 @@ -package awsUtil +package awsutil import ( "encoding/json" "fmt" + "sigs.k8s.io/yaml" ) @@ -11,7 +12,7 @@ export AWS_SECRET_ACCESS_KEY=%s export AWS_SESSION_TOKEN=%s` type AWSCredentialsResponse struct { - AccessKeyId string `json:"AccessKeyId" yaml:"AccessKeyId"` + AccessKeyID string `json:"AccessKeyID" yaml:"AccessKeyID"` SecretAccessKey string `json:"SecretAccessKey" yaml:"SecretAccessKey"` SessionToken string `json:"SessionToken" yaml:"SessionToken"` Region string `json:"Region,omitempty" yaml:"Region,omitempty"` @@ -19,7 +20,7 @@ type AWSCredentialsResponse struct { } func (r AWSCredentialsResponse) EnvFormat() string { - return fmt.Sprintf(awsExportFormat, r.AccessKeyId, r.SecretAccessKey, r.SessionToken) + return fmt.Sprintf(awsExportFormat, r.AccessKeyID, r.SecretAccessKey, r.SessionToken) } func (r AWSCredentialsResponse) RenderOutput(outputFormat string) (string, error) { diff --git a/pkg/awsUtil/credentials_test.go b/pkg/awsutil/credentials_test.go similarity index 89% rename from pkg/awsUtil/credentials_test.go rename to pkg/awsutil/credentials_test.go index a64fc71b..4d1926ca 100644 --- a/pkg/awsUtil/credentials_test.go +++ b/pkg/awsutil/credentials_test.go @@ -1,15 +1,16 @@ -package awsUtil +package awsutil import ( "encoding/json" "fmt" - "sigs.k8s.io/yaml" "testing" + + "sigs.k8s.io/yaml" ) func TestAWSCredentialsResponse_EnvFormat(t *testing.T) { type fields struct { - AccessKeyId string + AccessKeyID string SecretAccessKey string SessionToken string } @@ -24,7 +25,7 @@ func TestAWSCredentialsResponse_EnvFormat(t *testing.T) { }, { name: "Contains Access Key Id only", - fields: fields{AccessKeyId: "test-key"}, + fields: fields{AccessKeyID: "test-key"}, want: fmt.Sprintf(awsExportFormat, "test-key", "", ""), }, { @@ -39,12 +40,12 @@ func TestAWSCredentialsResponse_EnvFormat(t *testing.T) { }, { name: "Contains Access Key Id and Secret Access Key", - fields: fields{AccessKeyId: "test-key", SecretAccessKey: "test-secret-key"}, + fields: fields{AccessKeyID: "test-key", SecretAccessKey: "test-secret-key"}, want: fmt.Sprintf(awsExportFormat, "test-key", "test-secret-key", ""), }, { name: "Contains Access Key Id and Session Token", - fields: fields{AccessKeyId: "test-key", SessionToken: "test-session-token"}, + fields: fields{AccessKeyID: "test-key", SessionToken: "test-session-token"}, want: fmt.Sprintf(awsExportFormat, "test-key", "", "test-session-token"), }, { @@ -54,14 +55,14 @@ func TestAWSCredentialsResponse_EnvFormat(t *testing.T) { }, { name: "Contains Access Key Id, Secret Access Key, and Session Token", - fields: fields{AccessKeyId: "test-key", SecretAccessKey: "test-secret-key", SessionToken: "test-session-token"}, + fields: fields{AccessKeyID: "test-key", SecretAccessKey: "test-secret-key", SessionToken: "test-session-token"}, want: fmt.Sprintf(awsExportFormat, "test-key", "test-secret-key", "test-session-token"), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r := AWSCredentialsResponse{ - AccessKeyId: tt.fields.AccessKeyId, + AccessKeyID: tt.fields.AccessKeyID, SecretAccessKey: tt.fields.SecretAccessKey, SessionToken: tt.fields.SessionToken, } @@ -74,7 +75,7 @@ func TestAWSCredentialsResponse_EnvFormat(t *testing.T) { func TestAWSCredentialsResponse_RenderOutput(t *testing.T) { type fields struct { - AccessKeyId string + AccessKeyID string SecretAccessKey string SessionToken string Region string @@ -84,7 +85,7 @@ func TestAWSCredentialsResponse_RenderOutput(t *testing.T) { outputFormat string } credentials := fields{ - AccessKeyId: "1", + AccessKeyID: "1", SecretAccessKey: "2", SessionToken: "3", Region: "4", @@ -129,7 +130,7 @@ func TestAWSCredentialsResponse_RenderOutput(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r := AWSCredentialsResponse{ - AccessKeyId: tt.fields.AccessKeyId, + AccessKeyID: tt.fields.AccessKeyID, SecretAccessKey: tt.fields.SecretAccessKey, SessionToken: tt.fields.SessionToken, Region: tt.fields.Region, diff --git a/pkg/awsUtil/sts.go b/pkg/awsutil/sts.go similarity index 95% rename from pkg/awsUtil/sts.go rename to pkg/awsutil/sts.go index 06cabb4e..40987a4a 100644 --- a/pkg/awsUtil/sts.go +++ b/pkg/awsutil/sts.go @@ -1,28 +1,30 @@ -package awsUtil +package awsutil import ( "context" "errors" "fmt" + "net/http" + "net/url" + "time" + "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/aws/retry" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/sts" "github.com/aws/aws-sdk-go-v2/service/sts/types" + "github.com/openshift/backplane-cli/pkg/utils" - "net/http" - "net/url" - "time" ) -func StsClientWithProxy(proxyUrl string) (*sts.Client, error) { +func StsClientWithProxy(proxyURL string) (*sts.Client, error) { cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion("us-east-1"), // We don't care about region here, but the API still wants to see one set config.WithHTTPClient(&http.Client{ Transport: &http.Transport{ Proxy: func(*http.Request) (*url.URL, error) { - return url.Parse(proxyUrl) + return url.Parse(proxyURL) }, }, }), @@ -84,7 +86,7 @@ var DefaultSTSClientProviderFunc STSClientProviderFunc = func(optnFns ...func(op return sts.NewFromConfig(cfg), nil } -func AssumeRoleSequence(roleSessionName string, seedClient STSRoleAssumer, roleArnSequence []string, proxyUrl string, stsClientProviderFunc STSClientProviderFunc) (*types.Credentials, error) { +func AssumeRoleSequence(roleSessionName string, seedClient STSRoleAssumer, roleArnSequence []string, proxyURL string, stsClientProviderFunc STSClientProviderFunc) (*types.Credentials, error) { if len(roleArnSequence) == 0 { return nil, errors.New("role ARN sequence cannot be empty") } @@ -105,7 +107,7 @@ func AssumeRoleSequence(roleSessionName string, seedClient STSRoleAssumer, roleA config.WithHTTPClient(&http.Client{ Transport: &http.Transport{ Proxy: func(*http.Request) (*url.URL, error) { - return url.Parse(proxyUrl) + return url.Parse(proxyURL) }, }, }), diff --git a/pkg/awsUtil/sts_test.go b/pkg/awsutil/sts_test.go similarity index 99% rename from pkg/awsUtil/sts_test.go rename to pkg/awsutil/sts_test.go index bdcc2f83..2fcc9ecd 100644 --- a/pkg/awsUtil/sts_test.go +++ b/pkg/awsutil/sts_test.go @@ -1,14 +1,15 @@ -package awsUtil +package awsutil import ( "context" "errors" + "reflect" + "testing" + "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sts" "github.com/aws/aws-sdk-go-v2/service/sts/types" - "reflect" - "testing" ) type STSRoleAssumerMock struct { diff --git a/pkg/cli/config/config.go b/pkg/cli/config/config.go index 4b3e7251..5bcf5b8f 100644 --- a/pkg/cli/config/config.go +++ b/pkg/cli/config/config.go @@ -21,7 +21,7 @@ type BackplaneConfiguration struct { // GetConfigFilePath returns the Backplane CLI configuration filepath func GetConfigFilePath() (string, error) { // Check if user has explicitly defined backplane config path - path, found := os.LookupEnv(info.BACKPLANE_CONFIG_PATH_ENV_NAME) + path, found := os.LookupEnv(info.BackplaneConfigPathEnvName) if found { return path, nil } @@ -31,7 +31,7 @@ func GetConfigFilePath() (string, error) { return "", err } - configFilePath := filepath.Join(UserHomeDir, info.BACKPLANE_CONFIG_DEFAULT_FILE_PATH, info.BACKPLANE_CONFIG_DEFAULT_FILE_NAME) + configFilePath := filepath.Join(UserHomeDir, info.BackplaneConfigDefaultFilePath, info.BackplaneConfigDefaultFileName) return configFilePath, nil } @@ -57,13 +57,13 @@ func GetBackplaneConfiguration() (bpConfig BackplaneConfiguration, err error) { } // Check if user has explicitly defined backplane URL; it has higher precedence over the config file - err = viper.BindEnv("url", info.BACKPLANE_URL_ENV_NAME) + err = viper.BindEnv("url", info.BackplaneURLEnvName) if err != nil { return bpConfig, err } // Check if user has explicitly defined proxy; it has higher precedence over the config file - err = viper.BindEnv("proxy-url", info.BACKPLANE_PROXY_ENV_NAME) + err = viper.BindEnv("proxy-url", info.BackplaneProxyEnvName) if err != nil { return bpConfig, err } @@ -79,7 +79,7 @@ func GetBackplaneConfiguration() (bpConfig BackplaneConfiguration, err error) { func (config BackplaneConfiguration) CheckAPIConnection() error { // make test api connection - connectionOk, err := config.testHttpRequestToBackplaneAPI() + connectionOk, err := config.testHTTPRequestToBackplaneAPI() if !connectionOk { return err @@ -88,18 +88,18 @@ func (config BackplaneConfiguration) CheckAPIConnection() error { return nil } -// testHttpRequestToBackplaneAPI returns status of the the API connection -func (config BackplaneConfiguration) testHttpRequestToBackplaneAPI() (bool, error) { +// testHTTPRequestToBackplaneAPI returns status of the API connection +func (config BackplaneConfiguration) testHTTPRequestToBackplaneAPI() (bool, error) { client := http.Client{ Timeout: 5 * time.Second, } if config.ProxyURL != "" { - proxyUrl, err := url.Parse(config.ProxyURL) + proxyURL, err := url.Parse(config.ProxyURL) if err != nil { return false, err } - http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)} + http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyURL)} } req, err := http.NewRequest("HEAD", config.URL, nil) diff --git a/pkg/cli/config/config_test.go b/pkg/cli/config/config_test.go index 31e4e55a..645c44a6 100644 --- a/pkg/cli/config/config_test.go +++ b/pkg/cli/config/config_test.go @@ -39,14 +39,14 @@ func TestGetBackplaneConfiguration(t *testing.T) { for name, tc := range map[string]struct { envNeedToSet bool backplaneURLEnvVar string - proxyUrl string + proxyURL string expectedBackplaneURL string expectedError bool }{ "backplane url set via env vars": { envNeedToSet: true, backplaneURLEnvVar: "https://api-backplane.apps.openshiftapps.com", - proxyUrl: "http://squid.myproxy.com", + proxyURL: "http://squid.myproxy.com", expectedBackplaneURL: "https://api-backplane.apps.openshiftapps.com", expectedError: false, }, @@ -56,7 +56,7 @@ func TestGetBackplaneConfiguration(t *testing.T) { t.Run(name, func(t *testing.T) { if tc.envNeedToSet { t.Setenv("BACKPLANE_URL", tc.backplaneURLEnvVar) - t.Setenv("HTTPS_PROXY", tc.proxyUrl) + t.Setenv("HTTPS_PROXY", tc.proxyURL) } bpConfig, err := GetBackplaneConfiguration() @@ -78,9 +78,9 @@ func TestGetBackplaneConnection(t *testing.T) { _, _ = w.Write([]byte("dummy data")) })) - proxyUrl := "http://squid.myproxy.com" + proxyURL := "http://squid.myproxy.com" t.Setenv("BACKPLANE_URL", svr.URL) - t.Setenv("HTTPS_PROXY", proxyUrl) + t.Setenv("HTTPS_PROXY", proxyURL) config, err := GetBackplaneConfiguration() if err != nil { t.Error(err) diff --git a/pkg/cli/session/session.go b/pkg/cli/session/session.go index bbdf12b9..8032eadc 100644 --- a/pkg/cli/session/session.go +++ b/pkg/cli/session/session.go @@ -40,7 +40,7 @@ type Options struct { Alias string - ClusterId string + ClusterID string ClusterName string GlobalOpts *globalflags.GlobalOptions @@ -55,50 +55,50 @@ func (e *BackplaneSession) RunCommand(cmd *cobra.Command, args []string) error { if len(args) > 0 { e.Options.Alias = args[0] } - if e.Options.ClusterId == "" && e.Options.Alias == "" { - return fmt.Errorf("ClusterId or Alias required") + if e.Options.ClusterID == "" && e.Options.Alias == "" { + return fmt.Errorf("ClusterID or Alias required") } if e.Options.Alias == "" { log.Println("No Alias set, using cluster ID") - e.Options.Alias = e.Options.ClusterId + e.Options.Alias = e.Options.ClusterID } // Verify validity of the ClusterID clusterKey := e.Options.Alias - if e.Options.ClusterId != "" { - clusterKey = e.Options.ClusterId + if e.Options.ClusterID != "" { + clusterKey = e.Options.ClusterID } - clusterId, clusterName, err := utils.DefaultOCMInterface.GetTargetCluster(clusterKey) + clusterID, clusterName, err := utils.DefaultOCMInterface.GetTargetCluster(clusterKey) if err != nil { return fmt.Errorf("invalid cluster Id %s", clusterKey) } if e.Options.GlobalOpts.Manager { - clusterId, clusterName, err = utils.DefaultOCMInterface.GetManagingCluster(clusterId) - e.Options.Alias = clusterId + clusterID, clusterName, err = utils.DefaultOCMInterface.GetManagingCluster(clusterID) + e.Options.Alias = clusterID if err != nil { return err } - fmt.Printf("Switching to management cluster ID: %v, Name: %v\n", clusterId, clusterName) + fmt.Printf("Switching to management cluster ID: %v, Name: %v\n", clusterID, clusterName) } if e.Options.GlobalOpts.Service { - clusterId, clusterName, err = utils.DefaultOCMInterface.GetServiceCluster(clusterId) - e.Options.Alias = clusterId + clusterID, clusterName, err = utils.DefaultOCMInterface.GetServiceCluster(clusterID) + e.Options.Alias = clusterID if err != nil { return err } - fmt.Printf("Switching to service cluster ID: %v, Name: %v\n", clusterId, clusterName) + fmt.Printf("Switching to service cluster ID: %v, Name: %v\n", clusterID, clusterName) } // set cluster options e.Options.ClusterName = clusterName - e.Options.ClusterId = clusterId + e.Options.ClusterID = clusterID err = e.initSessionPath() if err != nil { @@ -237,9 +237,9 @@ HISTFILE=` + e.Path + `/.history PATH=` + e.Path + `/bin:` + os.Getenv("PATH") + ` ` - if e.Options.ClusterId != "" { - clusterEnvContent := "KUBECONFIG=" + filepath.Join(e.Path, e.Options.ClusterId, "config") + "\n" - clusterEnvContent = clusterEnvContent + "CLUSTERID=" + e.Options.ClusterId + "\n" + if e.Options.ClusterID != "" { + clusterEnvContent := "KUBECONFIG=" + filepath.Join(e.Path, e.Options.ClusterID, "config") + "\n" + clusterEnvContent = clusterEnvContent + "CLUSTERID=" + e.Options.ClusterID + "\n" clusterEnvContent = clusterEnvContent + "CLUSTERNAME=" + e.Options.ClusterName + "\n" envContent = envContent + clusterEnvContent } @@ -298,7 +298,7 @@ func (e *BackplaneSession) createBins() error { log.Fatal(err) } } - err := e.createBin("ocd", "ocm describe cluster "+e.Options.ClusterId) + err := e.createBin("ocd", "ocm describe cluster "+e.Options.ClusterID) if err != nil { return err } @@ -365,7 +365,7 @@ func (e *BackplaneSession) initSessionPath() error { if err != nil { return err } - sessionDir := info.BACKPLANE_DEFAULT_SESSION_DIRECTORY + sessionDir := info.BackplaneDefaultSessionDirectory // Get the session directory name via config if bpConfig.SessionDirectory != "" { @@ -391,7 +391,7 @@ func (e *BackplaneSession) initSessionPath() error { // initClusterLogin login to cluster and save kube config into session for valid clusters func (e *BackplaneSession) initClusterLogin(cmd *cobra.Command) error { - if e.Options.ClusterId != "" { + if e.Options.ClusterID != "" { // Setting up the flags err := login.LoginCmd.Flags().Set("multi", "true") @@ -404,7 +404,7 @@ func (e *BackplaneSession) initClusterLogin(cmd *cobra.Command) error { } // Execute login command - err = login.LoginCmd.RunE(cmd, []string{e.Options.ClusterId}) + err = login.LoginCmd.RunE(cmd, []string{e.Options.ClusterID}) if err != nil { return fmt.Errorf("error occurred when login to the cluster %v", err) } diff --git a/pkg/cli/session/session_test.go b/pkg/cli/session/session_test.go index 404ad93b..eff3cb1d 100644 --- a/pkg/cli/session/session_test.go +++ b/pkg/cli/session/session_test.go @@ -11,12 +11,13 @@ import ( "github.com/golang/mock/gomock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/spf13/cobra" + "github.com/openshift/backplane-cli/pkg/cli/globalflags" "github.com/openshift/backplane-cli/pkg/client/mocks" "github.com/openshift/backplane-cli/pkg/info" "github.com/openshift/backplane-cli/pkg/utils" mocks2 "github.com/openshift/backplane-cli/pkg/utils/mocks" - "github.com/spf13/cobra" ) var _ = Describe("Backplane Session Unit test", func() { @@ -31,9 +32,9 @@ var _ = Describe("Backplane Session Unit test", func() { bpSession BackplaneSession cmd *cobra.Command - testClusterId string + testClusterID string testToken string - trueClusterId string + trueClusterID string backplaneAPIUri string fakeResp *http.Response @@ -67,9 +68,9 @@ var _ = Describe("Backplane Session Unit test", func() { Use: "session", } - testClusterId = "test123" + testClusterID = "test123" testToken = "hello123" - trueClusterId = "trueID123" + trueClusterID = "trueID123" backplaneAPIUri = "https://api.integration.backplane.example.com" fakeResp = &http.Response{ @@ -79,7 +80,7 @@ var _ = Describe("Backplane Session Unit test", func() { } fakeResp.Header.Add("Content-Type", "json") - os.Setenv(info.BACKPLANE_URL_ENV_NAME, backplaneAPIUri) + os.Setenv(info.BackplaneURLEnvName, backplaneAPIUri) }) AfterEach(func() { @@ -141,41 +142,41 @@ var _ = Describe("Backplane Session Unit test", func() { It("should fail for empty session name ", func() { options.Alias = "" - options.ClusterId = "" + options.ClusterID = "" err := bpSession.RunCommand(cmd, []string{}) Expect(err).NotTo(BeNil()) - Expect(err.Error()).Should(ContainSubstring("ClusterId or Alias required")) + Expect(err.Error()).Should(ContainSubstring("ClusterID or Alias required")) }) It("should use clusterID when alias is empty ", func() { options.Alias = "" - options.ClusterId = testClusterId + options.ClusterID = testClusterID mockClientWithResp.EXPECT().LoginClusterWithResponse(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - mockOcmInterface.EXPECT().GetTargetCluster(options.ClusterId).Return(trueClusterId, testClusterId, nil).AnyTimes() - mockOcmInterface.EXPECT().GetTargetCluster(trueClusterId).Return(trueClusterId, testClusterId, nil).AnyTimes() - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(options.ClusterID).Return(trueClusterID, testClusterID, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(trueClusterID).Return(trueClusterID, testClusterID, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterId)).Return(fakeResp, nil).AnyTimes() + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).Return(fakeResp, nil).AnyTimes() err := bpSession.RunCommand(cmd, []string{}) Expect(err).To(BeNil()) - Expect(bpSession.Path).Should(ContainSubstring(testClusterId)) + Expect(bpSession.Path).Should(ContainSubstring(testClusterID)) }) It("should contains cluster env vars ", func() { options.Alias = "test-env" - options.ClusterId = testClusterId + options.ClusterID = testClusterID mockClientWithResp.EXPECT().LoginClusterWithResponse(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - mockOcmInterface.EXPECT().GetTargetCluster(options.ClusterId).Return(trueClusterId, testClusterId, nil).AnyTimes() - mockOcmInterface.EXPECT().GetTargetCluster(trueClusterId).Return(trueClusterId, testClusterId, nil).AnyTimes() - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(options.ClusterID).Return(trueClusterID, testClusterID, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(trueClusterID).Return(trueClusterID, testClusterID, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterId)).Return(fakeResp, nil).AnyTimes() + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).Return(fakeResp, nil).AnyTimes() err := bpSession.RunCommand(cmd, []string{}) Expect(err).To(BeNil()) @@ -187,17 +188,17 @@ var _ = Describe("Backplane Session Unit test", func() { for scanner.Scan() { // check osEnv file contains KUBECONFIG and value contains session name and cluster-id if strings.Contains(scanner.Text(), "KUBECONFIG") { - Expect(scanner.Text()).Should(ContainSubstring("test-env/" + trueClusterId)) + Expect(scanner.Text()).Should(ContainSubstring("test-env/" + trueClusterID)) } // check osEnv file contains CLUSTERID and value contains cluster-id if strings.Contains(scanner.Text(), "CLUSTERID") { - Expect(scanner.Text()).Should(ContainSubstring(trueClusterId)) + Expect(scanner.Text()).Should(ContainSubstring(trueClusterID)) } // check osEnv file contains CLUSTERNAME and value contains cluster-name if strings.Contains(scanner.Text(), "CLUSTERNAME") { - Expect(scanner.Text()).Should(ContainSubstring(testClusterId)) + Expect(scanner.Text()).Should(ContainSubstring(testClusterID)) } } }) @@ -206,15 +207,15 @@ var _ = Describe("Backplane Session Unit test", func() { Context("check Backplane session delete", func() { It("Session should delete ", func() { options.Alias = "my-session" - options.ClusterId = testClusterId + options.ClusterID = testClusterID mockClientWithResp.EXPECT().LoginClusterWithResponse(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - mockOcmInterface.EXPECT().GetTargetCluster(options.ClusterId).Return(trueClusterId, testClusterId, nil).AnyTimes() - mockOcmInterface.EXPECT().GetTargetCluster(trueClusterId).Return(trueClusterId, testClusterId, nil).AnyTimes() - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(options.ClusterID).Return(trueClusterID, testClusterID, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(trueClusterID).Return(trueClusterID, testClusterID, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterId)).Return(fakeResp, nil).AnyTimes() + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).Return(fakeResp, nil).AnyTimes() // Create the session err := bpSession.RunCommand(cmd, []string{}) diff --git a/pkg/elevate/elevate.go b/pkg/elevate/elevate.go index 2e998d95..0dc1bb1c 100644 --- a/pkg/elevate/elevate.go +++ b/pkg/elevate/elevate.go @@ -6,9 +6,10 @@ import ( "os" "os/exec" - "github.com/openshift/backplane-cli/pkg/utils" logger "github.com/sirupsen/logrus" "k8s.io/client-go/tools/clientcmd/api" + + "github.com/openshift/backplane-cli/pkg/utils" ) var ( @@ -21,13 +22,13 @@ var ( func AddElevationReasonToRawKubeconfig(config api.Config, elevationReason string) error { logger.Debugln("Adding reason for backplane-cluster-admin elevation") if config.Contexts[config.CurrentContext] == nil { - return errors.New("No current kubeconfig context") + return errors.New("no current kubeconfig context") } currentCtxUsername := config.Contexts[config.CurrentContext].AuthInfo if config.AuthInfos[currentCtxUsername] == nil { - return errors.New("No current user information") + return errors.New("no current user information") } if config.AuthInfos[currentCtxUsername].ImpersonateUserExtra == nil { diff --git a/pkg/info/info.go b/pkg/info/info.go index 5e86bf98..841e851d 100644 --- a/pkg/info/info.go +++ b/pkg/info/info.go @@ -8,17 +8,17 @@ import ( const ( // Environment Variables - BACKPLANE_URL_ENV_NAME = "BACKPLANE_URL" - BACKPLANE_PROXY_ENV_NAME = "HTTPS_PROXY" - BACKPLANE_CONFIG_PATH_ENV_NAME = "BACKPLANE_CONFIG" - BACKPLANE_KUBECONFIG_ENV_NAME = "KUBECONFIG" + BackplaneURLEnvName = "BACKPLANE_URL" + BackplaneProxyEnvName = "HTTPS_PROXY" + BackplaneConfigPathEnvName = "BACKPLANE_CONFIG" + BackplaneKubeconfigEnvName = "KUBECONFIG" // Configuration - BACKPLANE_CONFIG_DEFAULT_FILE_PATH = ".config/backplane" - BACKPLANE_CONFIG_DEFAULT_FILE_NAME = "config.json" + BackplaneConfigDefaultFilePath = ".config/backplane" + BackplaneConfigDefaultFileName = "config.json" // Session - BACKPLANE_DEFAULT_SESSION_DIRECTORY = "backplane" + BackplaneDefaultSessionDirectory = "backplane" // GitHub API get fetch the latest tag UpstreamReleaseAPI = "https://api.github.com/repos/openshift/backplane-cli/releases/latest" diff --git a/pkg/login/kubeConfig.go b/pkg/login/kubeConfig.go index fba6e5ce..9e5eeb25 100644 --- a/pkg/login/kubeConfig.go +++ b/pkg/login/kubeConfig.go @@ -9,8 +9,9 @@ import ( "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/tools/clientcmd/api" - "github.com/openshift/backplane-cli/pkg/info" logger "github.com/sirupsen/logrus" + + "github.com/openshift/backplane-cli/pkg/info" ) var ( @@ -18,7 +19,7 @@ var ( ) // CreateClusterKubeConfig creates cluster specific kube config based on a cluster ID -func CreateClusterKubeConfig(clusterId string, kubeConfig api.Config) (string, error) { +func CreateClusterKubeConfig(clusterID string, kubeConfig api.Config) (string, error) { basePath, err := getKubeConfigBasePath() if err != nil { @@ -26,7 +27,7 @@ func CreateClusterKubeConfig(clusterId string, kubeConfig api.Config) (string, e } // Create cluster folder - path := filepath.Join(basePath, clusterId) + path := filepath.Join(basePath, clusterID) if _, err = os.Stat(path); errors.Is(err, os.ErrNotExist) { err := os.MkdirAll(path, os.ModePerm) if err != nil { @@ -55,7 +56,7 @@ func CreateClusterKubeConfig(clusterId string, kubeConfig api.Config) (string, e // set kube config env with temp kube config file - err = os.Setenv(info.BACKPLANE_KUBECONFIG_ENV_NAME, filename) + err = os.Setenv(info.BackplaneKubeconfigEnvName, filename) if err != nil { return "", err } @@ -64,14 +65,14 @@ func CreateClusterKubeConfig(clusterId string, kubeConfig api.Config) (string, e } // RemoveClusterKubeConfig delete cluster specific kube config file -func RemoveClusterKubeConfig(clusterId string) error { +func RemoveClusterKubeConfig(clusterID string) error { basePath, err := getKubeConfigBasePath() if err != nil { return err } - path := filepath.Join(basePath, clusterId) + path := filepath.Join(basePath, clusterID) _, err = os.Stat(path) if !errors.Is(err, os.ErrNotExist) { @@ -81,7 +82,7 @@ func RemoveClusterKubeConfig(clusterId string) error { } // SaveKubeConfig modify Kube config based on user setting -func SaveKubeConfig(clusterId string, config api.Config, isMulti bool, kubePath string) error { +func SaveKubeConfig(clusterID string, config api.Config, isMulti bool, kubePath string) error { if isMulti { //update path @@ -92,12 +93,12 @@ func SaveKubeConfig(clusterId string, config api.Config, isMulti bool, kubePath } } //save config to current session - path, err := CreateClusterKubeConfig(clusterId, config) + path, err := CreateClusterKubeConfig(clusterID, config) if kubePath == "" { // Inform how to setup kube config - fmt.Printf("Execute the following command to log into the cluster %s \n", clusterId) - fmt.Println("export " + info.BACKPLANE_KUBECONFIG_ENV_NAME + "=" + path) + fmt.Printf("Execute the following command to log into the cluster %s \n", clusterID) + fmt.Println("export " + info.BackplaneKubeconfigEnvName + "=" + path) } if err != nil { diff --git a/pkg/login/kubeConfig_test.go b/pkg/login/kubeConfig_test.go index b4b271cf..36574f00 100644 --- a/pkg/login/kubeConfig_test.go +++ b/pkg/login/kubeConfig_test.go @@ -12,14 +12,14 @@ import ( var _ = Describe("Login Kube Config test", func() { var ( - testClusterId string + testClusterID string kubeConfig api.Config kubePath string ) BeforeEach(func() { - testClusterId = "test123" + testClusterID = "test123" kubeConfig = api.Config{ Kind: "Config", APIVersion: "v1", @@ -41,10 +41,10 @@ var _ = Describe("Login Kube Config test", func() { err := SetKubeConfigBasePath(kubePath) Expect(err).To(BeNil()) - path, err := CreateClusterKubeConfig(testClusterId, kubeConfig) + path, err := CreateClusterKubeConfig(testClusterID, kubeConfig) Expect(err).To(BeNil()) - Expect(path).Should(ContainSubstring(testClusterId)) + Expect(path).Should(ContainSubstring(testClusterID)) //check file is exist _, err = os.Stat(path) @@ -58,7 +58,7 @@ var _ = Describe("Login Kube Config test", func() { err := SetKubeConfigBasePath(kubePath) Expect(err).To(BeNil()) - path, err := CreateClusterKubeConfig(testClusterId, kubeConfig) + path, err := CreateClusterKubeConfig(testClusterID, kubeConfig) Expect(err).To(BeNil()) // check file is exist @@ -66,7 +66,7 @@ var _ = Describe("Login Kube Config test", func() { Expect(err).To(BeNil()) // delete kube config - err = RemoveClusterKubeConfig(testClusterId) + err = RemoveClusterKubeConfig(testClusterID) Expect(err).To(BeNil()) // check file is not exist diff --git a/pkg/monitoring/monitoring.go b/pkg/monitoring/monitoring.go index 27d95eea..cbde4b0d 100644 --- a/pkg/monitoring/monitoring.go +++ b/pkg/monitoring/monitoring.go @@ -3,32 +3,33 @@ package monitoring import ( "context" "fmt" + "io" + "log" + "net" + "net/http" + "net/http/httputil" + "net/url" + "strings" + "github.com/Masterminds/semver" routev1typedclient "github.com/openshift/client-go/route/clientset/versioned/typed/route/v1" userv1typedclient "github.com/openshift/client-go/user/clientset/versioned/typed/user/v1" "github.com/pkg/browser" logger "github.com/sirupsen/logrus" - "io" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" restclient "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" - "log" - "net" - "net/http" - "net/http/httputil" - "net/url" - "strings" "github.com/openshift/backplane-cli/pkg/cli/config" "github.com/openshift/backplane-cli/pkg/utils" ) const ( - ALERTMANAGER = "alertmanager" - PROMETHEUS = "prometheus" - THANOS = "thanos" - GRAFANA = "grafana" - OPENSHIFT_MONITORING_NS = "openshift-monitoring" + ALERTMANAGER = "alertmanager" + PROMETHEUS = "prometheus" + THANOS = "thanos" + GRAFANA = "grafana" + OpenShiftMonitoringNS = "openshift-monitoring" ) var ( @@ -36,7 +37,7 @@ var ( Namespace string Selector string Port string - OriginUrl string + OriginURL string ListenAddr string Browser bool KeepAlive bool @@ -73,13 +74,13 @@ func (c Client) RunMonitoring(monitoringType string) error { // set up monitoring Url if it's empty if c.url == "" { - c.url, err = getBackplaneMonitoringUrl(monitoringType) + c.url, err = getBackplaneMonitoringURL(monitoringType) if err != nil { return err } } - mUrl, err := url.Parse(c.url) + mURL, err := url.Parse(c.url) if err != nil { return err } @@ -99,10 +100,10 @@ func (c Client) RunMonitoring(monitoringType string) error { hasNs := len(MonitoringOpts.Namespace) != 0 hasAppSelector := len(MonitoringOpts.Selector) != 0 hasPort := len(MonitoringOpts.Port) != 0 - hasUrl := len(MonitoringOpts.OriginUrl) != 0 + hasURL := len(MonitoringOpts.OriginURL) != 0 - // serveUrl is the port-forward url we print to the user in the end. - serveUrl, err := serveUrl(hasUrl, hasNs, cfg) + // serveURL is the port-forward url we print to the user in the end. + serveURL, err := serveURL(hasURL, hasNs, cfg) if err != nil { return err } @@ -129,23 +130,23 @@ func (c Client) RunMonitoring(monitoringType string) error { } // Add http proxy transport - proxyUrl, err := getProxyUrl() + proxyURL, err := getProxyURL() if err != nil { return err } - if proxyUrl != "" { - proxyUrl, err := url.Parse(proxyUrl) + if proxyURL != "" { + proxyURL, err := url.Parse(proxyURL) if err != nil { return err } http.DefaultTransport = &http.Transport{ - Proxy: http.ProxyURL(proxyUrl), + Proxy: http.ProxyURL(proxyURL), } - logger.Debugf("Using backplane Proxy URL: %s\n", proxyUrl) + logger.Debugf("Using backplane Proxy URL: %s\n", proxyURL) } - req = setProxyRequest(req, mUrl, name, accessToken, isGrafana, hasNs, hasAppSelector, hasPort) + req = setProxyRequest(req, mURL, name, accessToken, isGrafana, hasNs, hasAppSelector, hasPort) resp, err := c.http.Do(req) if err != nil { @@ -162,7 +163,7 @@ func (c Client) RunMonitoring(monitoringType string) error { // If the above test pass, we will construct a reverse proxy for the user proxy := &httputil.ReverseProxy{ Director: func(req *http.Request) { - setProxyRequest(req, mUrl, name, accessToken, isGrafana, hasNs, hasAppSelector, hasPort) + setProxyRequest(req, mURL, name, accessToken, isGrafana, hasNs, hasAppSelector, hasPort) }, } @@ -184,10 +185,10 @@ func (c Client) RunMonitoring(monitoringType string) error { return err } - serveUrl.Host = addr + serveURL.Host = addr if MonitoringOpts.Browser { - err = browser.OpenURL(serveUrl.String()) + err = browser.OpenURL(serveURL.String()) if err != nil { logger.Warnf("failed opening a browser: %s", err) } @@ -195,7 +196,7 @@ func (c Client) RunMonitoring(monitoringType string) error { if MonitoringOpts.KeepAlive { if !MonitoringOpts.Browser { - fmt.Printf("Serving %s at %s\n", monitoringType, serveUrl.String()) + fmt.Printf("Serving %s at %s\n", monitoringType, serveURL.String()) } return http.Serve(l, proxy) //#nosec: G114 } else { @@ -204,27 +205,27 @@ func (c Client) RunMonitoring(monitoringType string) error { } -// getBackplaneMonitoringUrl returns the backplane API monitoring URL based on monitoring type -func getBackplaneMonitoringUrl(monitoringType string) (string, error) { - monitoringUrl := "" +// getBackplaneMonitoringURL returns the backplane API monitoring URL based on monitoring type +func getBackplaneMonitoringURL(monitoringType string) (string, error) { + monitoringURL := "" cfg, err := clientcmd.BuildConfigFromFlags("", clientcmd.NewDefaultPathOptions().GetDefaultFilename()) if err != nil { - return monitoringUrl, err + return monitoringURL, err } // creates URL for serving if !strings.Contains(cfg.Host, "backplane/cluster") { - return monitoringUrl, fmt.Errorf("the api server is not a backplane url, please make sure you login to the cluster using backplane") + return monitoringURL, fmt.Errorf("the api server is not a backplane url, please make sure you login to the cluster using backplane") } - monitoringUrl = strings.Replace(cfg.Host, "backplane/cluster", fmt.Sprintf("backplane/%s", monitoringType), 1) - monitoringUrl = strings.TrimSuffix(monitoringUrl, "/") - return monitoringUrl, nil + monitoringURL = strings.Replace(cfg.Host, "backplane/cluster", fmt.Sprintf("backplane/%s", monitoringType), 1) + monitoringURL = strings.TrimSuffix(monitoringURL, "/") + return monitoringURL, nil } // Setting Headers, accessToken, port and selector func setProxyRequest( req *http.Request, - proxyUrl *url.URL, + proxyURL *url.URL, userName string, accessToken *string, isGrafana bool, @@ -233,9 +234,9 @@ func setProxyRequest( hasPort bool, ) *http.Request { req.URL.Scheme = "https" - req.Host = proxyUrl.Host - req.URL.Host = proxyUrl.Host - req.URL.Path = singleJoiningSlash(proxyUrl.Path, req.URL.Path) + req.Host = proxyURL.Host + req.URL.Host = proxyURL.Host + req.URL.Path = singleJoiningSlash(proxyURL.Path, req.URL.Path) if _, ok := req.Header["User-Agent"]; !ok { // explicitly disable User-Agent so it's not set to default value req.Header.Set("User-Agent", "") @@ -270,8 +271,8 @@ func singleJoiningSlash(a, b string) string { return a + b } -// Check if a route of the originUrl exist in the namespace. -func hasMatchRoute(namespace string, originUrl *url.URL, cfg *restclient.Config) bool { +// Check if a route of the originURL exist in the namespace. +func hasMatchRoute(namespace string, originURL *url.URL, cfg *restclient.Config) bool { routeInterface, err := routev1typedclient.NewForConfig(cfg) if err != nil { logger.Warnf("cannot create route client-go interface %s", err) @@ -286,7 +287,7 @@ func hasMatchRoute(namespace string, originUrl *url.URL, cfg *restclient.Config) ri := rt.Status.Ingress for _, ig := range ri { logger.Debugf("found route ingress %s", ig.Host) - if utils.MatchBaseDomain(originUrl.Hostname(), ig.Host) { + if utils.MatchBaseDomain(originURL.Hostname(), ig.Host) { return true } } @@ -294,14 +295,14 @@ func hasMatchRoute(namespace string, originUrl *url.URL, cfg *restclient.Config) return false } -// serveUrl returns the port-forward url to the route -func serveUrl(hasUrl, hasNs bool, cfg *restclient.Config) (*url.URL, error) { - serveUrl := &url.URL{ +// serveURL returns the port-forward url to the route +func serveURL(hasURL, hasNs bool, cfg *restclient.Config) (*url.URL, error) { + serveURL := &url.URL{ Scheme: "http", } - if hasUrl { - originUrl, err := url.Parse(MonitoringOpts.OriginUrl) + if hasURL { + originURL, err := url.Parse(MonitoringOpts.OriginURL) if err != nil { return nil, err } @@ -315,7 +316,7 @@ func serveUrl(hasUrl, hasNs bool, cfg *restclient.Config) (*url.URL, error) { return nil, err } baseDomain := currentCluster.DNS().BaseDomain() - if !utils.MatchBaseDomain(originUrl.Hostname(), baseDomain) { + if !utils.MatchBaseDomain(originURL.Hostname(), baseDomain) { return nil, fmt.Errorf("the basedomain %s of the current logged cluster %s does not match the provided url, please login to the corresponding cluster first", baseDomain, currentClusterInfo.ClusterID) } @@ -325,37 +326,37 @@ func serveUrl(hasUrl, hasNs bool, cfg *restclient.Config) (*url.URL, error) { return nil, fmt.Errorf("namepace should not be blank, please specify namespace by --namespace") } - if !hasMatchRoute(MonitoringOpts.Namespace, originUrl, cfg) { + if !hasMatchRoute(MonitoringOpts.Namespace, originURL, cfg) { return nil, fmt.Errorf("cannot find a matching route in namespace %s for the given url, please specify a correct namespace by --namespace", MonitoringOpts.Namespace) } // append path and query to the url printed later - serveUrl.Path = originUrl.Path - serveUrl.RawQuery = originUrl.RawQuery - serveUrl.Fragment = originUrl.Fragment - return serveUrl, nil + serveURL.Path = originURL.Path + serveURL.RawQuery = originURL.RawQuery + serveURL.Fragment = originURL.Fragment + return serveURL, nil } - return serveUrl, nil + return serveURL, nil } -// getProxyUrl returns the proxy url -func getProxyUrl() (proxyUrl string, err error) { +// getProxyURL returns the proxy url +func getProxyURL() (proxyURL string, err error) { bpConfig, err := config.GetBackplaneConfiguration() if err != nil { return "", err } - proxyUrl = bpConfig.ProxyURL + proxyURL = bpConfig.ProxyURL - return proxyUrl, nil + return proxyURL, nil } // validateClusterVersion checks the clusterversion based on namespace func validateClusterVersion(monitoringName string) error { - if MonitoringOpts.Namespace == OPENSHIFT_MONITORING_NS { + if MonitoringOpts.Namespace == OpenShiftMonitoringNS { //checks cluster version currentClusterInfo, err := utils.DefaultClusterUtils.GetBackplaneClusterFromConfig() if err != nil { diff --git a/pkg/monitoring/monitoring_test.go b/pkg/monitoring/monitoring_test.go index 374dea62..a2ea7330 100644 --- a/pkg/monitoring/monitoring_test.go +++ b/pkg/monitoring/monitoring_test.go @@ -10,11 +10,12 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" cmv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1" + "k8s.io/client-go/tools/clientcmd/api" + "github.com/openshift/backplane-cli/pkg/client/mocks" "github.com/openshift/backplane-cli/pkg/info" "github.com/openshift/backplane-cli/pkg/utils" mocks2 "github.com/openshift/backplane-cli/pkg/utils/mocks" - "k8s.io/client-go/tools/clientcmd/api" ) var _ = Describe("Backplane Monitoring Unit test", func() { @@ -25,9 +26,9 @@ var _ = Describe("Backplane Monitoring Unit test", func() { mockOcmInterface *mocks2.MockOCMInterface mockClientUtil *mocks2.MockClientUtils - testClusterId string + testClusterID string testToken string - trueClusterId string + trueClusterID string backplaneAPIUri string fakeResp *http.Response @@ -49,9 +50,9 @@ var _ = Describe("Backplane Monitoring Unit test", func() { mockClientUtil = mocks2.NewMockClientUtils(mockCtrl) utils.DefaultClientUtils = mockClientUtil - testClusterId = "test123" + testClusterID = "test123" testToken = "hello123" - trueClusterId = "trueID123" + trueClusterID = "trueID123" backplaneAPIUri = "https://api.integration.backplane.example.com" fakeResp = &http.Response{ @@ -111,7 +112,7 @@ var _ = Describe("Backplane Monitoring Unit test", func() { err := utils.CreateTempKubeConfig(&testKubeCfg) Expect(err).To(BeNil()) - os.Setenv(info.BACKPLANE_URL_ENV_NAME, backplaneAPIUri) + os.Setenv(info.BackplaneURLEnvName, backplaneAPIUri) }) AfterEach(func() { @@ -131,14 +132,14 @@ var _ = Describe("Backplane Monitoring Unit test", func() { It("should fail for cluster version greater than 4.11 and openshift monitoring namespace ", func() { mockClientWithResp.EXPECT().LoginClusterWithResponse(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - mockOcmInterface.EXPECT().GetTargetCluster(trueClusterId).Return(trueClusterId, testClusterId, nil).AnyTimes() - mockOcmInterface.EXPECT().GetClusterInfoByID(testClusterId).Return(clusterVersion412, nil).AnyTimes() - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(trueClusterID).Return(trueClusterID, testClusterID, nil).AnyTimes() + mockOcmInterface.EXPECT().GetClusterInfoByID(testClusterID).Return(clusterVersion412, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterId)).Return(fakeResp, nil).AnyTimes() + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).Return(fakeResp, nil).AnyTimes() - MonitoringOpts.Namespace = OPENSHIFT_MONITORING_NS + MonitoringOpts.Namespace = OpenShiftMonitoringNS // check for prometheus @@ -165,12 +166,12 @@ var _ = Describe("Backplane Monitoring Unit test", func() { It("should serve thanos monitoring dashboard for cluster version greater than 4.11", func() { mockClientWithResp.EXPECT().LoginClusterWithResponse(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - mockOcmInterface.EXPECT().GetTargetCluster(trueClusterId).Return(trueClusterId, testClusterId, nil).AnyTimes() - mockOcmInterface.EXPECT().GetClusterInfoByID(testClusterId).Return(clusterVersion412, nil).AnyTimes() - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(trueClusterID).Return(trueClusterID, testClusterID, nil).AnyTimes() + mockOcmInterface.EXPECT().GetClusterInfoByID(testClusterID).Return(clusterVersion412, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterId)).Return(fakeResp, nil).AnyTimes() + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).Return(fakeResp, nil).AnyTimes() MonitoringOpts.KeepAlive = false @@ -188,14 +189,14 @@ var _ = Describe("Backplane Monitoring Unit test", func() { It("should serve monitoring dashboard for cluster version lower than 4.11 and openshift monitoring namespace ", func() { mockClientWithResp.EXPECT().LoginClusterWithResponse(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - mockOcmInterface.EXPECT().GetTargetCluster(trueClusterId).Return(trueClusterId, testClusterId, nil).AnyTimes() - mockOcmInterface.EXPECT().GetClusterInfoByID(testClusterId).Return(clusterVersion410, nil).AnyTimes() - mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterId)).Return(false, nil).AnyTimes() + mockOcmInterface.EXPECT().GetTargetCluster(trueClusterID).Return(trueClusterID, testClusterID, nil).AnyTimes() + mockOcmInterface.EXPECT().GetClusterInfoByID(testClusterID).Return(clusterVersion410, nil).AnyTimes() + mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes() mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes() mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIUri, testToken).Return(mockClient, nil).AnyTimes() - mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterId)).Return(fakeResp, nil).AnyTimes() + mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).Return(fakeResp, nil).AnyTimes() - MonitoringOpts.Namespace = OPENSHIFT_MONITORING_NS + MonitoringOpts.Namespace = OpenShiftMonitoringNS MonitoringOpts.KeepAlive = false svr := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("dummy data")) diff --git a/pkg/utils/clientUtils.go b/pkg/utils/clientUtils.go index 4b6a482e..cefd5774 100644 --- a/pkg/utils/clientUtils.go +++ b/pkg/utils/clientUtils.go @@ -20,11 +20,11 @@ type ClientUtils interface { MakeRawBackplaneAPIClientWithAccessToken(base, accessToken string) (BackplaneApi.ClientInterface, error) MakeRawBackplaneAPIClient(base string) (BackplaneApi.ClientInterface, error) GetBackplaneClient(backplaneURL string) (client BackplaneApi.ClientInterface, err error) - SetClientProxyUrl(proxyUrl string) error + SetClientProxyURL(proxyURL string) error } type DefaultClientUtilsImpl struct { - clientProxyUrl string + clientProxyURL string } var ( @@ -42,23 +42,23 @@ func (s *DefaultClientUtilsImpl) MakeRawBackplaneAPIClientWithAccessToken(base, } // Inject client Proxy Url from config - if s.clientProxyUrl == "" { + if s.clientProxyURL == "" { bpConfig, err := config.GetBackplaneConfiguration() if err != nil { return nil, err } - s.clientProxyUrl = bpConfig.ProxyURL + s.clientProxyURL = bpConfig.ProxyURL } // Update http proxy transport - if s.clientProxyUrl != "" { - proxyUrl, err := url.Parse(s.clientProxyUrl) + if s.clientProxyURL != "" { + proxyURL, err := url.Parse(s.clientProxyURL) if err != nil { return nil, err } - http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)} + http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyURL)} - logger.Debugf("Using backplane Proxy URL: %s\n", s.clientProxyUrl) + logger.Debugf("Using backplane Proxy URL: %s\n", s.clientProxyURL) } return BackplaneApi.NewClient(base, co) @@ -122,11 +122,11 @@ func (s *DefaultClientUtilsImpl) GetBackplaneClient(backplaneURL string) (client return backplaneClient, nil } -// SetClientProxyUrl Set client proxy url for http transport -func (s *DefaultClientUtilsImpl) SetClientProxyUrl(proxyUrl string) error { - if proxyUrl == "" { - return errors.New("proxy Url is empty") +// SetClientProxyURL Set client proxy url for http transport +func (s *DefaultClientUtilsImpl) SetClientProxyURL(proxyURL string) error { + if proxyURL == "" { + return errors.New("proxy URL is empty") } - s.clientProxyUrl = proxyUrl + s.clientProxyURL = proxyURL return nil } diff --git a/pkg/utils/cluster_test.go b/pkg/utils/cluster_test.go index b21a7699..6e1a33df 100644 --- a/pkg/utils/cluster_test.go +++ b/pkg/utils/cluster_test.go @@ -8,10 +8,11 @@ import ( "testing" "github.com/golang/mock/gomock" + "k8s.io/client-go/tools/clientcmd" + "github.com/openshift/backplane-cli/pkg/info" "github.com/openshift/backplane-cli/pkg/utils" "github.com/openshift/backplane-cli/pkg/utils/mocks" - "k8s.io/client-go/tools/clientcmd" ) const ( @@ -207,7 +208,7 @@ func TestGetBackplaneClusterFromClusterKey(t *testing.T) { utils.DefaultOCMInterface = mockOcmInterface t.Run("it returns a cluster struct from a valid cluster key", func(_ *testing.T) { - os.Setenv(info.BACKPLANE_URL_ENV_NAME, "https://backplane-url.cluster-key.redhat.com") + os.Setenv(info.BackplaneURLEnvName, "https://backplane-url.cluster-key.redhat.com") mockOcmInterface.EXPECT().GetTargetCluster("cluster-key").Return("1234", "cluster-key", nil) cluster, err := utils.DefaultClusterUtils.GetBackplaneClusterFromClusterKey("cluster-key") diff --git a/pkg/utils/mocks/clientUtilsMock.go b/pkg/utils/mocks/clientUtilsMock.go index 5fbb9f17..0a924a7d 100644 --- a/pkg/utils/mocks/clientUtilsMock.go +++ b/pkg/utils/mocks/clientUtilsMock.go @@ -109,16 +109,16 @@ func (mr *MockClientUtilsMockRecorder) MakeRawBackplaneAPIClientWithAccessToken( return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MakeRawBackplaneAPIClientWithAccessToken", reflect.TypeOf((*MockClientUtils)(nil).MakeRawBackplaneAPIClientWithAccessToken), arg0, arg1) } -// SetClientProxyUrl mocks base method. -func (m *MockClientUtils) SetClientProxyUrl(arg0 string) error { +// SetClientProxyURL mocks base method. +func (m *MockClientUtils) SetClientProxyURL(arg0 string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetClientProxyUrl", arg0) + ret := m.ctrl.Call(m, "SetClientProxyURL", arg0) ret0, _ := ret[0].(error) return ret0 } -// SetClientProxyUrl indicates an expected call of SetClientProxyUrl. -func (mr *MockClientUtilsMockRecorder) SetClientProxyUrl(arg0 interface{}) *gomock.Call { +// SetClientProxyURL indicates an expected call of SetClientProxyURL. +func (mr *MockClientUtilsMockRecorder) SetClientProxyURL(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetClientProxyUrl", reflect.TypeOf((*MockClientUtils)(nil).SetClientProxyUrl), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetClientProxyURL", reflect.TypeOf((*MockClientUtils)(nil).SetClientProxyURL), arg0) } diff --git a/pkg/utils/ocmWrapper.go b/pkg/utils/ocmWrapper.go index 52db4066..dd847a65 100644 --- a/pkg/utils/ocmWrapper.go +++ b/pkg/utils/ocmWrapper.go @@ -15,12 +15,12 @@ import ( // Provides a minimal interface for backplane-cli to function type OCMInterface interface { - IsClusterHibernating(clusterId string) (bool, error) - GetTargetCluster(clusterKey string) (clusterId, clusterName string, err error) - GetManagingCluster(clusterKey string) (clusterId, clusterName string, err error) + IsClusterHibernating(clusterID string) (bool, error) + GetTargetCluster(clusterKey string) (clusterID, clusterName string, err error) + GetManagingCluster(clusterKey string) (clusterID, clusterName string, err error) GetOCMAccessToken() (*string, error) - GetServiceCluster(clusterKey string) (clusterId, clusterName string, err error) - GetClusterInfoByID(clusterId string) (*cmv1.Cluster, error) + GetServiceCluster(clusterKey string) (clusterID, clusterName string, err error) + GetClusterInfoByID(clusterID string) (*cmv1.Cluster, error) IsProduction() (bool, error) GetPullSecret() (string, error) } @@ -30,13 +30,13 @@ type DefaultOCMInterfaceImpl struct{} var DefaultOCMInterface OCMInterface = &DefaultOCMInterfaceImpl{} // IsClusterHibernating returns a boolean to indicate whether the cluster is hibernating -func (*DefaultOCMInterfaceImpl) IsClusterHibernating(clusterId string) (bool, error) { +func (*DefaultOCMInterfaceImpl) IsClusterHibernating(clusterID string) (bool, error) { connection, err := ocm.NewConnection().Build() if err != nil { return false, fmt.Errorf("failed to create OCM connection: %v", err) } defer connection.Close() - res, err := connection.ClustersMgmt().V1().Clusters().Cluster(clusterId).Get().Send() + res, err := connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).Get().Send() if err != nil { return false, fmt.Errorf("unable get get cluster status: %v", err) } @@ -46,7 +46,7 @@ func (*DefaultOCMInterfaceImpl) IsClusterHibernating(clusterId string) (bool, er } // GetTargetCluster returns one single cluster based on the search key and survery. -func (*DefaultOCMInterfaceImpl) GetTargetCluster(clusterKey string) (clusterId, clusterName string, err error) { +func (*DefaultOCMInterfaceImpl) GetTargetCluster(clusterKey string) (clusterID, clusterName string, err error) { // Create the client for the OCM API: connection, err := ocm.NewConnection().Build() if err != nil { @@ -62,7 +62,7 @@ func (*DefaultOCMInterfaceImpl) GetTargetCluster(clusterKey string) (clusterId, if len(clusters) == 1 { for _, v := range clusters { - clusterId = v.ID() + clusterID = v.ID() clusterName = v.Name() } } else { @@ -70,15 +70,15 @@ func (*DefaultOCMInterfaceImpl) GetTargetCluster(clusterKey string) (clusterId, if err != nil { return "", "", fmt.Errorf("can't find cluster: %v", err) } - clusterId = cluster.ID() + clusterID = cluster.ID() clusterName = cluster.Name() } - return clusterId, clusterName, nil + return clusterID, clusterName, nil } // GetManagingCluster returns the managing cluster (hive shard or hypershift management cluster) -// for the given clusterId -func (o *DefaultOCMInterfaceImpl) GetManagingCluster(targetClusterId string) (clusterId, clusterName string, err error) { +// for the given clusterID +func (o *DefaultOCMInterfaceImpl) GetManagingCluster(targetClusterID string) (clusterID, clusterName string, err error) { // Create the client for the OCM API: connection, err := ocm.NewConnection().Build() if err != nil { @@ -89,7 +89,7 @@ func (o *DefaultOCMInterfaceImpl) GetManagingCluster(targetClusterId string) (cl var managingCluster string // Check if cluster has hypershift enabled hypershiftResp, err := connection.ClustersMgmt().V1().Clusters(). - Cluster(targetClusterId). + Cluster(targetClusterID). Hypershift(). Get(). Send() @@ -98,10 +98,10 @@ func (o *DefaultOCMInterfaceImpl) GetManagingCluster(targetClusterId string) (cl } else { // Get the client for the resource that manages the collection of clusters: clusterCollection := connection.ClustersMgmt().V1().Clusters() - resource := clusterCollection.Cluster(targetClusterId).ProvisionShard() + resource := clusterCollection.Cluster(targetClusterID).ProvisionShard() response, err := resource.Get().Send() if err != nil { - return "", "", fmt.Errorf("failed to find management cluster for cluster %s: %v", targetClusterId, err) + return "", "", fmt.Errorf("failed to find management cluster for cluster %s: %v", targetClusterID, err) } shard := response.Body() hiveAPI := shard.HiveConfig().Server() @@ -113,16 +113,16 @@ func (o *DefaultOCMInterfaceImpl) GetManagingCluster(targetClusterId string) (cl Send() if err != nil { - return "", "", fmt.Errorf("failed to find management cluster for cluster %s: %v", targetClusterId, err) + return "", "", fmt.Errorf("failed to find management cluster for cluster %s: %v", targetClusterID, err) } if mcResp.Items().Len() == 0 { - return "", "", fmt.Errorf("failed to find management cluster for cluster %s in %s env", targetClusterId, connection.URL()) + return "", "", fmt.Errorf("failed to find management cluster for cluster %s in %s env", targetClusterID, connection.URL()) } managingCluster = mcResp.Items().Get(0).Name() } if managingCluster == "" { - return "", "", fmt.Errorf("failed to lookup managing cluster for cluster %s", targetClusterId) + return "", "", fmt.Errorf("failed to lookup managing cluster for cluster %s", targetClusterID) } mcid, _, err := o.GetTargetCluster(managingCluster) @@ -133,7 +133,7 @@ func (o *DefaultOCMInterfaceImpl) GetManagingCluster(targetClusterId string) (cl } // GetServiceCluster gets the service cluster for a given hpyershift hosted cluster -func (*DefaultOCMInterfaceImpl) GetServiceCluster(targetClusterId string) (clusterId, clusterName string, err error) { +func (*DefaultOCMInterfaceImpl) GetServiceCluster(targetClusterID string) (clusterID, clusterName string, err error) { // Create the client for the OCM API connection, err := ocm.NewConnection().Build() if err != nil { @@ -141,10 +141,10 @@ func (*DefaultOCMInterfaceImpl) GetServiceCluster(targetClusterId string) (clust } defer connection.Close() - var svcClusterId, svcClusterName, mgmtCluster string + var svcClusterID, svcClusterName, mgmtCluster string // If given cluster is hypershift hosted cluster hypershiftResp, err := connection.ClustersMgmt().V1().Clusters(). - Cluster(targetClusterId). + Cluster(targetClusterID). Hypershift(). Get(). Send() @@ -153,7 +153,7 @@ func (*DefaultOCMInterfaceImpl) GetServiceCluster(targetClusterId string) (clust } else { // If given cluster is management cluster mgmtClusterResp, err := connection.OSDFleetMgmt().V1().ManagementClusters().List(). - Parameter("search", fmt.Sprintf("cluster_id='%s'", targetClusterId)). + Parameter("search", fmt.Sprintf("cluster_id='%s'", targetClusterID)). Send() if err == nil && mgmtClusterResp.Size() > 0 { mgmtCluster = mgmtClusterResp.Items().Get(0).Name() @@ -161,7 +161,7 @@ func (*DefaultOCMInterfaceImpl) GetServiceCluster(targetClusterId string) (clust } if mgmtCluster == "" { - return "", "", fmt.Errorf("failed to lookup managing cluster for cluster %s", targetClusterId) + return "", "", fmt.Errorf("failed to lookup managing cluster for cluster %s", targetClusterID) } // Get the osd_fleet_mgmt reference for the given mgmt_cluster @@ -180,10 +180,10 @@ func (*DefaultOCMInterfaceImpl) GetServiceCluster(targetClusterId string) (clust if err != nil { return "", "", fmt.Errorf("failed to get the service cluster id") } - svcClusterId = svcClusterResp.Items().Get(0).ID() + svcClusterID = svcClusterResp.Items().Get(0).ID() } - return svcClusterId, svcClusterName, nil + return svcClusterID, svcClusterName, nil } // GetOCMAccessToken initiates the OCM connection and returns the access token @@ -229,7 +229,7 @@ func (*DefaultOCMInterfaceImpl) GetPullSecret() (string, error) { // GetClusterInfoByID calls the OCM to retrieve the cluster info // for a given internal cluster id. -func (*DefaultOCMInterfaceImpl) GetClusterInfoByID(clusterId string) (*cmv1.Cluster, error) { +func (*DefaultOCMInterfaceImpl) GetClusterInfoByID(clusterID string) (*cmv1.Cluster, error) { // Create the client for the OCM API: connection, err := ocm.NewConnection().Build() if err != nil { @@ -238,13 +238,13 @@ func (*DefaultOCMInterfaceImpl) GetClusterInfoByID(clusterId string) (*cmv1.Clus defer connection.Close() // Get the cluster info based on the cluster id - response, err := connection.ClustersMgmt().V1().Clusters().Cluster(clusterId).Get().Send() + response, err := connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).Get().Send() if err != nil { - return nil, fmt.Errorf("can't retrieve cluster for id '%s': %v", clusterId, err) + return nil, fmt.Errorf("can't retrieve cluster for id '%s': %v", clusterID, err) } cluster, ok := response.GetBody() if !ok { - return nil, fmt.Errorf("can't retrieve cluster for id '%s', nil value", clusterId) + return nil, fmt.Errorf("can't retrieve cluster for id '%s', nil value", clusterID) } return cluster, nil } diff --git a/pkg/utils/renderingutils.go b/pkg/utils/renderingutils.go index ca689de8..6df9e57e 100644 --- a/pkg/utils/renderingutils.go +++ b/pkg/utils/renderingutils.go @@ -13,7 +13,7 @@ import ( "golang.org/x/term" ) -// This renderer only uses tabs and renders based on terminal width available +// RenderTabbedTable only uses tabs and renders based on terminal width available // It keeps the first column in it's full length and truncates others func RenderTabbedTable(headers []string, data [][]string) { columnPadding := 2 @@ -97,9 +97,9 @@ func RenderTable(headers []string, data [][]string) { table.Render() } -// RenderJson is an effectual function that renders the reader as JSON +// RenderJSON is an effectual function that renders the reader as JSON // returns err if render fails -func RenderJson(reader io.Reader) error { +func RenderJSON(reader io.Reader) error { body, err := ioutil.ReadAll(reader) if err != nil { return err @@ -112,9 +112,9 @@ func RenderJson(reader io.Reader) error { return nil } -// RenderJsonBytes is an effectual function that renders the reader as JSON +// RenderJSONBytes is an effectual function that renders the reader as JSON // returns err if render fails -func RenderJsonBytes(i interface{}) error { +func RenderJSONBytes(i interface{}) error { resString, err := json.MarshalIndent(i, "", " ") if err != nil { return err diff --git a/pkg/utils/util.go b/pkg/utils/util.go index f3a72b55..6082327d 100644 --- a/pkg/utils/util.go +++ b/pkg/utils/util.go @@ -10,9 +10,10 @@ import ( "reflect" "strings" - logger "github.com/sirupsen/logrus" netUrl "net/url" + logger "github.com/sirupsen/logrus" + BackplaneApi "github.com/openshift/backplane-api/pkg/client" "github.com/spf13/cobra" @@ -26,7 +27,7 @@ import ( const ( ClustersPageSize = 50 - BackplaneApiUrlRegexp string = `(?mi)^https:\/\/api\.(.*)backplane\.(.*)` + BackplaneAPIURLRegexp string = `(?mi)^https:\/\/api\.(.*)backplane\.(.*)` ClusterIDRegexp string = "/?backplane/cluster/([a-zA-Z0-9]+)/?" ) @@ -71,12 +72,12 @@ func GetFreePort() (int, error) { // return false if it not 200 or encounter any error. func CheckHealth(url string) bool { // Parse the given URL and check for ambiguities - parsedUrl, err := netUrl.Parse(url) + parsedURL, err := netUrl.Parse(url) if err != nil { return false //just return false for any error } - resp, err := http.Get(parsedUrl.String()) + resp, err := http.Get(parsedURL.String()) if err != nil { return false //just return false for any error } @@ -123,7 +124,7 @@ func TryRenderErrorRaw(rsp *http.Response) error { if err != nil { return err } - return RenderJsonBytes(data) + return RenderJSONBytes(data) } func GetFormattedError(rsp *http.Response) error { diff --git a/pkg/utils/util_test.go b/pkg/utils/util_test.go index dfe8506b..31770c29 100644 --- a/pkg/utils/util_test.go +++ b/pkg/utils/util_test.go @@ -65,61 +65,61 @@ func TestGetFreePort(t *testing.T) { func TestMatchBaseDomain(t *testing.T) { tests := []struct { name string - longUrl string + longURL string baseDomain string expect bool }{ { name: "case-1", - longUrl: "a.example.com", + longURL: "a.example.com", baseDomain: "example.com", expect: true, }, { name: "case-2", - longUrl: "a.b.c.example.com", + longURL: "a.b.c.example.com", baseDomain: "example.com", expect: true, }, { name: "case-3", - longUrl: "example.com", + longURL: "example.com", baseDomain: "example.com", expect: true, }, { name: "case-4", - longUrl: "a.example.com", + longURL: "a.example.com", baseDomain: "", expect: true, }, { name: "case-5", - longUrl: "", + longURL: "", baseDomain: "", expect: true, }, { name: "case-6", - longUrl: "", + longURL: "", baseDomain: "example.com", expect: false, }, { name: "case-7", - longUrl: "a.example.com.io", + longURL: "a.example.com.io", baseDomain: "example.com", expect: false, }, { name: "case-8", - longUrl: "a.b.c", + longURL: "a.b.c", baseDomain: "e.f.g", expect: false, }, { name: "case-9", - longUrl: "a", + longURL: "a", baseDomain: "a", expect: true, }, @@ -127,7 +127,7 @@ func TestMatchBaseDomain(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - result := MatchBaseDomain(tt.longUrl, tt.baseDomain) + result := MatchBaseDomain(tt.longURL, tt.baseDomain) if result != tt.expect { t.Errorf("Expecting: %t, but get: %t", tt.expect, result) }