update.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. package v2
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "os"
  8. "os/signal"
  9. "path/filepath"
  10. "strconv"
  11. "syscall"
  12. "time"
  13. "github.com/porter-dev/porter/api/server/handlers/porter_app"
  14. "github.com/porter-dev/porter/api/types"
  15. "github.com/porter-dev/porter/internal/models"
  16. "github.com/fatih/color"
  17. api "github.com/porter-dev/porter/api/client"
  18. "github.com/porter-dev/porter/cli/cmd/config"
  19. )
  20. // UpdateInput is the input for the Update function
  21. type UpdateInput struct {
  22. // CLIConfig is the CLI configuration
  23. CLIConfig config.CLIConfig
  24. // Client is the Porter API client
  25. Client api.Client
  26. // PorterYamlPath is the path to the porter.yaml file
  27. PorterYamlPath string
  28. // AppName is the name of the app
  29. AppName string
  30. // PreviewApply is true when Update should create a new deployment target matching current git branch and apply to that target
  31. PreviewApply bool
  32. }
  33. // Update implements the functionality of the `porter apply` command for validate apply v2 projects
  34. func Update(ctx context.Context, inp UpdateInput) error {
  35. ctx, cancel := context.WithCancel(ctx)
  36. defer cancel()
  37. go func() {
  38. termChan := make(chan os.Signal, 1)
  39. signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)
  40. select {
  41. case <-termChan:
  42. color.New(color.FgYellow).Printf("Shutdown signal received, cancelling processes\n") // nolint:errcheck,gosec
  43. cancel()
  44. case <-ctx.Done():
  45. }
  46. }()
  47. cliConf := inp.CLIConfig
  48. client := inp.Client
  49. deploymentTargetID, err := deploymentTargetFromConfig(ctx, client, cliConf.Project, cliConf.Cluster, inp.PreviewApply)
  50. if err != nil {
  51. return fmt.Errorf("error getting deployment target from config: %w", err)
  52. }
  53. var prNumber int
  54. prNumberEnv := os.Getenv("PORTER_PR_NUMBER")
  55. if prNumberEnv != "" {
  56. prNumber, err = strconv.Atoi(prNumberEnv)
  57. if err != nil {
  58. return fmt.Errorf("error parsing PORTER_PR_NUMBER to int: %w", err)
  59. }
  60. }
  61. porterYamlExists := len(inp.PorterYamlPath) != 0
  62. if porterYamlExists {
  63. _, err := os.Stat(filepath.Clean(inp.PorterYamlPath))
  64. if err != nil {
  65. if !os.IsNotExist(err) {
  66. return fmt.Errorf("error checking if porter yaml exists at path %s: %w", inp.PorterYamlPath, err)
  67. }
  68. // If a path was specified but the file does not exist, we will not immediately error out.
  69. // This supports users migrated from v1 who use a workflow file that always specifies a porter yaml path
  70. // in the apply command.
  71. porterYamlExists = false
  72. }
  73. }
  74. var b64YAML string
  75. if porterYamlExists {
  76. porterYaml, err := os.ReadFile(filepath.Clean(inp.PorterYamlPath))
  77. if err != nil {
  78. return fmt.Errorf("could not read porter yaml file: %w", err)
  79. }
  80. b64YAML = base64.StdEncoding.EncodeToString(porterYaml)
  81. color.New(color.FgGreen).Printf("Using Porter YAML at path: %s\n", inp.PorterYamlPath) // nolint:errcheck,gosec
  82. }
  83. commitSHA := commitSHAFromEnv()
  84. gitSource, err := gitSourceFromEnv()
  85. if err != nil {
  86. return fmt.Errorf("error getting git source from env: %w", err)
  87. }
  88. updateInput := api.UpdateAppInput{
  89. ProjectID: cliConf.Project,
  90. ClusterID: cliConf.Cluster,
  91. Name: inp.AppName,
  92. GitSource: gitSource,
  93. DeploymentTargetId: deploymentTargetID,
  94. Base64PorterYAML: b64YAML,
  95. CommitSHA: commitSHA,
  96. }
  97. updateResp, err := client.UpdateApp(ctx, updateInput)
  98. if err != nil {
  99. return fmt.Errorf("error calling update app endpoint: %w", err)
  100. }
  101. if updateResp.AppRevisionId == "" {
  102. return errors.New("app revision id is empty")
  103. }
  104. appName := updateResp.AppName
  105. buildSettings, err := client.GetBuildFromRevision(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId)
  106. if err != nil {
  107. return fmt.Errorf("error getting build from revision: %w", err)
  108. }
  109. if buildSettings != nil && buildSettings.Build.Method != "" {
  110. eventID, _ := createBuildEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, commitSHA)
  111. var buildFinished bool
  112. var buildError error
  113. var buildLogs string
  114. defer func() {
  115. if buildError != nil && !errors.Is(buildError, context.Canceled) {
  116. reportBuildFailureInput := reportBuildFailureInput{
  117. client: client,
  118. appName: appName,
  119. cliConf: cliConf,
  120. deploymentTargetID: deploymentTargetID,
  121. appRevisionID: updateResp.AppRevisionId,
  122. eventID: eventID,
  123. commitSHA: commitSHA,
  124. prNumber: prNumber,
  125. buildError: buildError,
  126. buildLogs: buildLogs,
  127. }
  128. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  129. return
  130. }
  131. if !buildFinished {
  132. buildMetadata := make(map[string]interface{})
  133. buildMetadata["end_time"] = time.Now().UTC()
  134. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_Build, eventID, types.PorterAppEventStatus_Canceled, buildMetadata)
  135. return
  136. }
  137. }()
  138. if commitSHA == "" {
  139. return errors.New("build is required but commit SHA cannot be identified. Please set the PORTER_COMMIT_SHA environment variable or run apply in git repository with access to the git CLI")
  140. }
  141. color.New(color.FgGreen).Printf("Building new image with tag %s...\n", commitSHA) // nolint:errcheck,gosec
  142. buildInput, err := buildInputFromBuildSettings(cliConf.Project, appName, commitSHA, buildSettings.Image, buildSettings.Build)
  143. if err != nil {
  144. buildError = fmt.Errorf("error creating build input from build settings: %w", err)
  145. return buildError
  146. }
  147. buildOutput := build(ctx, client, buildInput)
  148. if buildOutput.Error != nil {
  149. buildError = fmt.Errorf("error building app: %w", buildOutput.Error)
  150. buildLogs = buildOutput.Logs
  151. return buildError
  152. }
  153. _, err = client.UpdateRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId, models.AppRevisionStatus_BuildSuccessful)
  154. if err != nil {
  155. buildError = fmt.Errorf("error updating revision status post build: %w", err)
  156. return buildError
  157. }
  158. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", commitSHA) // nolint:errcheck,gosec
  159. buildMetadata := make(map[string]interface{})
  160. buildMetadata["end_time"] = time.Now().UTC()
  161. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_Build, eventID, types.PorterAppEventStatus_Success, buildMetadata)
  162. buildFinished = true
  163. }
  164. color.New(color.FgGreen).Printf("Deploying new revision %s for app %s...\n", updateResp.AppRevisionId, appName) // nolint:errcheck,gosec
  165. now := time.Now().UTC()
  166. var status models.AppRevisionStatus
  167. for {
  168. if time.Since(now) > checkDeployTimeout {
  169. return errors.New("timed out waiting for app to deploy")
  170. }
  171. revision, err := client.GetRevision(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId)
  172. if err != nil {
  173. return fmt.Errorf("error getting app revision status: %w", err)
  174. }
  175. status = revision.AppRevision.Status
  176. if status == models.AppRevisionStatus_DeployFailed || status == models.AppRevisionStatus_PredeployFailed || status == models.AppRevisionStatus_Deployed {
  177. break
  178. }
  179. if status == models.AppRevisionStatus_AwaitingPredeploy {
  180. color.New(color.FgGreen).Printf("Waiting for predeploy to complete..\n") // nolint:errcheck,gosec
  181. }
  182. time.Sleep(checkDeployFrequency)
  183. }
  184. _, _ = client.ReportRevisionStatus(ctx, api.ReportRevisionStatusInput{
  185. ProjectID: cliConf.Project,
  186. ClusterID: cliConf.Cluster,
  187. AppName: appName,
  188. AppRevisionID: updateResp.AppRevisionId,
  189. PRNumber: prNumber,
  190. CommitSHA: commitSHA,
  191. })
  192. if status == models.AppRevisionStatus_DeployFailed {
  193. return errors.New("app failed to deploy")
  194. }
  195. if status == models.AppRevisionStatus_PredeployFailed {
  196. return errors.New("predeploy failed for new revision")
  197. }
  198. color.New(color.FgGreen).Printf("Successfully applied new revision %s\n", updateResp.AppRevisionId) // nolint:errcheck,gosec
  199. return nil
  200. }
  201. // checkDeployTimeout is the timeout for checking if an app has been deployed
  202. const checkDeployTimeout = 15 * time.Minute
  203. // checkDeployFrequency is the frequency for checking if an app has been deployed
  204. const checkDeployFrequency = 10 * time.Second
  205. func gitSourceFromEnv() (porter_app.GitSource, error) {
  206. var source porter_app.GitSource
  207. var repoID uint
  208. if os.Getenv("GITHUB_REPOSITORY_ID") != "" {
  209. id, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  210. if err != nil {
  211. return source, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  212. }
  213. repoID = uint(id)
  214. }
  215. return porter_app.GitSource{
  216. GitBranch: os.Getenv("GITHUB_REF_NAME"),
  217. GitRepoID: repoID,
  218. GitRepoName: os.Getenv("GITHUB_REPOSITORY"),
  219. }, nil
  220. }
  221. func buildInputFromBuildSettings(projectID uint, appName string, commitSHA string, image porter_app.Image, build porter_app.BuildSettings) (buildInput, error) {
  222. var buildSettings buildInput
  223. if appName == "" {
  224. return buildSettings, errors.New("app name is empty")
  225. }
  226. if image.Repository == "" {
  227. return buildSettings, errors.New("image repository is empty")
  228. }
  229. if build.Method == "" {
  230. return buildSettings, errors.New("build method is empty")
  231. }
  232. if commitSHA == "" {
  233. return buildSettings, errors.New("commit SHA is empty")
  234. }
  235. return buildInput{
  236. ProjectID: projectID,
  237. AppName: appName,
  238. BuildContext: build.Context,
  239. Dockerfile: build.Dockerfile,
  240. BuildMethod: build.Method,
  241. Builder: build.Builder,
  242. BuildPacks: build.Buildpacks,
  243. ImageTag: commitSHA,
  244. RepositoryURL: image.Repository,
  245. CurrentImageTag: image.Tag,
  246. }, nil
  247. }