rollback.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package v2
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/fatih/color"
  6. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  7. api "github.com/porter-dev/porter/api/client"
  8. "github.com/porter-dev/porter/cli/cmd/config"
  9. "github.com/porter-dev/porter/internal/models"
  10. "github.com/porter-dev/porter/internal/porter_app"
  11. )
  12. // RollbackInput is the input for the Rollback function
  13. type RollbackInput struct {
  14. // CLIConfig is the CLI configuration
  15. CLIConfig config.CLIConfig
  16. // Client is the Porter API client
  17. Client api.Client
  18. // AppName is the name of the app to rollback
  19. AppName string
  20. }
  21. // Rollback deploys the previous successful revision of an app
  22. func Rollback(ctx context.Context, inp RollbackInput) error {
  23. targetResp, err := inp.Client.DefaultDeploymentTarget(ctx, inp.CLIConfig.Project, inp.CLIConfig.Cluster)
  24. if err != nil {
  25. return fmt.Errorf("error calling default deployment target endpoint: %w", err)
  26. }
  27. deploymentTargetID := targetResp.DeploymentTargetID
  28. listResp, err := inp.Client.ListAppRevisions(ctx, inp.CLIConfig.Project, inp.CLIConfig.Cluster, inp.AppName, deploymentTargetID)
  29. if err != nil {
  30. return fmt.Errorf("error calling current app revision endpoint: %w", err)
  31. }
  32. if len(listResp.AppRevisions) <= 1 {
  33. return fmt.Errorf("no previous successful revisions found for app %s", inp.AppName)
  34. }
  35. revisions := listResp.AppRevisions
  36. var rollbackTarget porter_app.Revision
  37. for _, rev := range revisions[1:] {
  38. if rev.RevisionNumber != 0 && rev.Status == models.AppRevisionStatus_Deployed {
  39. rollbackTarget = rev
  40. break
  41. }
  42. }
  43. if rollbackTarget.ID == "" {
  44. return fmt.Errorf("no previous successful revisions found for app %s", inp.AppName)
  45. }
  46. color.New(color.FgGreen).Printf("Rolling back to revision %d...\n", rollbackTarget.RevisionNumber) // nolint:errcheck,gosec
  47. applyResp, err := inp.Client.ApplyPorterApp(ctx, inp.CLIConfig.Project, inp.CLIConfig.Cluster, rollbackTarget.B64AppProto, deploymentTargetID, "", false)
  48. if err != nil {
  49. return fmt.Errorf("error calling apply endpoint: %w", err)
  50. }
  51. if applyResp.CLIAction != porterv1.EnumCLIAction_ENUM_CLI_ACTION_NONE {
  52. return fmt.Errorf("unexpected CLI action: %s", applyResp.CLIAction)
  53. }
  54. color.New(color.FgGreen).Printf("Successfully rolled back to revision %d\n", rollbackTarget.RevisionNumber) // nolint:errcheck,gosec
  55. return nil
  56. }