Skip to content

Commit

Permalink
Return errors in top level functions
Browse files Browse the repository at this point in the history
  • Loading branch information
JakobGray committed Jul 30, 2024
1 parent 98bdffe commit 1f2641a
Show file tree
Hide file tree
Showing 7 changed files with 119 additions and 125 deletions.
46 changes: 23 additions & 23 deletions cmd/ocm/gcp/create-wif-config.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ const (
// NewCreateWorkloadIdentityConfiguration provides the "gcp create wif-config" subcommand
func NewCreateWorkloadIdentityConfiguration() *cobra.Command {
createWifConfigCmd := &cobra.Command{
Use: "wif-config",
Short: "Create workload identity configuration",
Run: createWorkloadIdentityConfigurationCmd,
PersistentPreRun: validationForCreateWorkloadIdentityConfigurationCmd,
Use: "wif-config",
Short: "Create workload identity configuration",
RunE: createWorkloadIdentityConfigurationCmd,
PreRunE: validationForCreateWorkloadIdentityConfigurationCmd,
}

createWifConfigCmd.PersistentFlags().StringVar(&CreateWifConfigOpts.Name, "name", "",
Expand All @@ -61,87 +61,87 @@ func NewCreateWorkloadIdentityConfiguration() *cobra.Command {
return createWifConfigCmd
}

func createWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) {
func createWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) error {
ctx := context.Background()

gcpClient, err := gcp.NewGcpClient(ctx)
if err != nil {
log.Fatalf("failed to initiate GCP client: %v", err)
return errors.Wrapf(err, "failed to initiate GCP client")
}

log.Println("Creating workload identity configuration...")
wifConfig, err := createWorkloadIdentityConfiguration(CreateWifConfigOpts.Name, CreateWifConfigOpts.Project)
if err != nil {
log.Fatalf("failed to create WIF config: %v", err)
return errors.Wrapf(err, "failed to create WIF config")
}

if CreateWifConfigOpts.DryRun {
log.Printf("Writing script files to %s", CreateWifConfigOpts.TargetDir)

projectNum, err := gcpClient.ProjectNumberFromId(wifConfig.Gcp().ProjectId())
if err != nil {
log.Fatalf("failed to get project number from id: %v", err)
return errors.Wrapf(err, "failed to get project number from id")
}
err = createScript(CreateWifConfigOpts.TargetDir, wifConfig, projectNum)
if err != nil {
log.Fatalf("Failed to create script files: %s", err)
return errors.Wrapf(err, "Failed to create script files")
}
return
return nil
}

if err = createWorkloadIdentityPool(ctx, gcpClient, wifConfig); err != nil {
log.Printf("Failed to create workload identity pool: %s", err)
log.Fatalf("To clean up, run the following command: ocm gcp delete wif-config %s", wifConfig.ID())
return fmt.Errorf("To clean up, run the following command: ocm gcp delete wif-config %s", wifConfig.ID())
}

if err = createWorkloadIdentityProvider(ctx, gcpClient, wifConfig); err != nil {
log.Printf("Failed to create workload identity provider: %s", err)
log.Fatalf("To clean up, run the following command: ocm gcp delete wif-config %s", wifConfig.ID())
return fmt.Errorf("To clean up, run the following command: ocm gcp delete wif-config %s", wifConfig.ID())
}

if err = createServiceAccounts(ctx, gcpClient, wifConfig); err != nil {
log.Printf("Failed to create IAM service accounts: %s", err)
log.Fatalf("To clean up, run the following command: ocm gcp delete wif-config %s", wifConfig.ID())
return fmt.Errorf("To clean up, run the following command: ocm gcp delete wif-config %s", wifConfig.ID())
}

return nil
}

func validationForCreateWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) {
func validationForCreateWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) error {
if CreateWifConfigOpts.Name == "" {
log.Fatal("Name is required")
return fmt.Errorf("Name is required")
}
if CreateWifConfigOpts.Project == "" {
log.Fatal("Project is required")
return fmt.Errorf("Project is required")
}

if CreateWifConfigOpts.TargetDir == "" {
pwd, err := os.Getwd()
if err != nil {
log.Fatalf("Failed to get current directory: %s", err)
return errors.Wrapf(err, "failed to get current directory")
}

CreateWifConfigOpts.TargetDir = pwd
}

fPath, err := filepath.Abs(CreateWifConfigOpts.TargetDir)
if err != nil {
log.Fatalf("Failed to resolve full path: %s", err)
return errors.Wrapf(err, "failed to resolve full path")
}

sResult, err := os.Stat(fPath)
if os.IsNotExist(err) {
log.Fatalf("Directory %s does not exist", fPath)
return fmt.Errorf("directory %s does not exist", fPath)
}
if !sResult.IsDir() {
log.Fatalf("file %s exists and is not a directory", fPath)
return fmt.Errorf("file %s exists and is not a directory", fPath)
}

return nil
}

func createWorkloadIdentityConfiguration(displayName, projectId string) (*cmv1.WifConfig, error) {
connection, err := ocm.NewConnection().Build()
if err != nil {
log.Fatal(err)
return nil, errors.Wrapf(err, "Failed to create OCM connection")
}
defer connection.Close()

Expand Down
46 changes: 24 additions & 22 deletions cmd/ocm/gcp/delete-wif-config.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ var (
// NewDeleteWorkloadIdentityConfiguration provides the "gcp delete wif-config" subcommand
func NewDeleteWorkloadIdentityConfiguration() *cobra.Command {
deleteWifConfigCmd := &cobra.Command{
Use: "wif-config [ID]",
Short: "Delete workload identity configuration",
Run: deleteWorkloadIdentityConfigurationCmd,
PersistentPreRun: validationForDeleteWorkloadIdentityConfigurationCmd,
Use: "wif-config [ID]",
Short: "Delete workload identity configuration",
RunE: deleteWorkloadIdentityConfigurationCmd,
PreRunE: validationForDeleteWorkloadIdentityConfigurationCmd,
}

deleteWifConfigCmd.PersistentFlags().BoolVar(&DeleteWifConfigOpts.DryRun, "dry-run", false,
Expand All @@ -41,33 +41,34 @@ func NewDeleteWorkloadIdentityConfiguration() *cobra.Command {
return deleteWifConfigCmd
}

func validationForDeleteWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) {
func validationForDeleteWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) error {
if len(argv) != 1 {
log.Fatal(
"Expected exactly one command line parameters containing the id " +
"of the WIF config.",
return fmt.Errorf(
"expected exactly one command line parameters containing the id " +
"of the WIF config",
)
}
return nil
}

func deleteWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) {
func deleteWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) error {
ctx := context.Background()

wifConfigId := argv[0]
if wifConfigId == "" {
log.Fatal("WIF config ID is required")
return fmt.Errorf("WIF config ID is required")
}

// Create the client for the OCM API:
connection, err := ocm.NewConnection().Build()
if err != nil {
log.Fatal(err)
return errors.Wrapf(err, "Failed to create OCM connection")
}
defer connection.Close()

response, err := connection.ClustersMgmt().V1().GCP().WifConfigs().WifConfig(wifConfigId).Get().Send()
if err != nil {
log.Fatalf("failed to get wif-config: %v", err)
return errors.Wrapf(err, "failed to get wif-config")
}
wifConfig := response.Body()

Expand All @@ -76,31 +77,32 @@ func deleteWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) {

err := createDeleteScript(DeleteWifConfigOpts.TargetDir, wifConfig)
if err != nil {
log.Fatalf("Failed to create script files: %s", err)
return errors.Wrapf(err, "failed to create script files")
}
return
return nil
}

gcpClient, err := gcp.NewGcpClient(context.Background())
if err != nil {
log.Fatal(err)
return err
}

if err := deleteServiceAccounts(ctx, gcpClient, wifConfig, true); err != nil {
log.Fatal(err)
return err
}

if err := deleteWorkloadIdentityPool(ctx, gcpClient, wifConfig, true); err != nil {
log.Fatal(err)
return err
}

_, err = connection.ClustersMgmt().V1().GCP().WifConfigs().
WifConfig(wifConfigId).
Delete().
Send()
if err != nil {
log.Fatalf("failed to delete wif config %q: %v", wifConfigId, err)
return errors.Wrapf(err, "failed to delete wif config %q", wifConfigId)
}
return nil
}

func deleteServiceAccounts(ctx context.Context, gcpClient gcp.GcpClient,
Expand All @@ -113,7 +115,7 @@ func deleteServiceAccounts(ctx context.Context, gcpClient gcp.GcpClient,
log.Println("Deleting service account", serviceAccountID)
err := gcpClient.DeleteServiceAccount(serviceAccountID, projectId, allowMissing)
if err != nil {
return errors.Wrapf(err, "Failed to delete service account %s", serviceAccountID)
return errors.Wrapf(err, "Failed to delete service account %q", serviceAccountID)
}
}

Expand All @@ -131,12 +133,12 @@ func deleteWorkloadIdentityPool(ctx context.Context, gcpClient gcp.GcpClient,
if err != nil {
if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 &&
strings.Contains(gerr.Message, "Requested entity was not found") && allowMissing {
log.Printf("Workload identity pool %s not found", poolName)
log.Printf("Workload identity pool %q not found", poolName)
return nil
}
return errors.Wrapf(err, "Failed to delete workload identity pool %s", poolName)
return errors.Wrapf(err, "Failed to delete workload identity pool %q", poolName)
}

log.Printf("Workload identity pool %s deleted", poolName)
log.Printf("Workload identity pool %q deleted", poolName)
return nil
}
25 changes: 13 additions & 12 deletions cmd/ocm/gcp/describe-wif-config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,43 +2,43 @@ package gcp

import (
"fmt"
"log"
"os"
"text/tabwriter"

"github.com/openshift-online/ocm-cli/pkg/ocm"
"github.com/openshift-online/ocm-cli/pkg/urls"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)

// NewDescribeWorkloadIdentityConfiguration provides the "gcp describe wif-config" subcommand
func NewDescribeWorkloadIdentityConfiguration() *cobra.Command {
describeWorkloadIdentityPoolCmd := &cobra.Command{
Use: "wif-config [ID]",
Short: "Show details of a wif-config.",
Run: describeWorkloadIdentityConfigurationCmd,
PersistentPreRun: validationForDescribeWorkloadIdentityConfigurationCmd,
Use: "wif-config [ID]",
Short: "Show details of a wif-config.",
RunE: describeWorkloadIdentityConfigurationCmd,
PreRunE: validationForDescribeWorkloadIdentityConfigurationCmd,
}

return describeWorkloadIdentityPoolCmd
}

func describeWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) {
func describeWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) error {
id, err := urls.Expand(argv)
if err != nil {
log.Fatalf("could not create URI: %v", err)
return errors.Wrapf(err, "could not create URI")
}

// Create the client for the OCM API:
connection, err := ocm.NewConnection().Build()
if err != nil {
log.Fatal(err)
return errors.Wrapf(err, "Failed to create OCM connection")
}
defer connection.Close()

response, err := connection.ClustersMgmt().V1().GCP().WifConfigs().WifConfig(id).Get().Send()
if err != nil {
log.Fatalf("failed to get wif-config: %v", err)
return errors.Wrapf(err, "failed to get wif-config")
}
wifConfig := response.Body()

Expand All @@ -50,11 +50,12 @@ func describeWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string)
fmt.Fprintf(w, "Project:\t%s\n", wifConfig.Gcp().ProjectId())
fmt.Fprintf(w, "Issuer URL:\t%s\n", wifConfig.Gcp().WorkloadIdentityPool().IdentityProvider().IssuerUrl())

w.Flush()
return w.Flush()
}

func validationForDescribeWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) {
func validationForDescribeWorkloadIdentityConfigurationCmd(cmd *cobra.Command, argv []string) error {
if len(argv) != 1 {
log.Fatalf("Expected exactly one command line parameters containing the id of the WIF config.")
return fmt.Errorf("Expected exactly one command line parameters containing the id of the WIF config")
}
return nil
}
Loading

0 comments on commit 1f2641a

Please sign in to comment.