update.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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(buildInputFromBuildSettingsInput{
  143. projectID: cliConf.Project,
  144. appName: appName,
  145. commitSHA: commitSHA,
  146. image: buildSettings.Image,
  147. build: buildSettings.Build,
  148. buildEnv: buildSettings.BuildEnvVariables,
  149. })
  150. if err != nil {
  151. buildError = fmt.Errorf("error creating build input from build settings: %w", err)
  152. return buildError
  153. }
  154. buildOutput := build(ctx, client, buildInput)
  155. if buildOutput.Error != nil {
  156. buildError = fmt.Errorf("error building app: %w", buildOutput.Error)
  157. buildLogs = buildOutput.Logs
  158. return buildError
  159. }
  160. _, err = client.UpdateRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId, models.AppRevisionStatus_BuildSuccessful)
  161. if err != nil {
  162. buildError = fmt.Errorf("error updating revision status post build: %w", err)
  163. return buildError
  164. }
  165. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", commitSHA) // nolint:errcheck,gosec
  166. buildMetadata := make(map[string]interface{})
  167. buildMetadata["end_time"] = time.Now().UTC()
  168. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_Build, eventID, types.PorterAppEventStatus_Success, buildMetadata)
  169. buildFinished = true
  170. }
  171. color.New(color.FgGreen).Printf("Deploying new revision %s for app %s...\n", updateResp.AppRevisionId, appName) // nolint:errcheck,gosec
  172. now := time.Now().UTC()
  173. var status models.AppRevisionStatus
  174. for {
  175. if time.Since(now) > checkDeployTimeout {
  176. return errors.New("timed out waiting for app to deploy")
  177. }
  178. revision, err := client.GetRevision(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId)
  179. if err != nil {
  180. return fmt.Errorf("error getting app revision status: %w", err)
  181. }
  182. status = revision.AppRevision.Status
  183. if status == models.AppRevisionStatus_DeployFailed || status == models.AppRevisionStatus_PredeployFailed || status == models.AppRevisionStatus_Deployed {
  184. break
  185. }
  186. if status == models.AppRevisionStatus_AwaitingPredeploy {
  187. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  188. }
  189. time.Sleep(checkDeployFrequency)
  190. }
  191. _, _ = client.ReportRevisionStatus(ctx, api.ReportRevisionStatusInput{
  192. ProjectID: cliConf.Project,
  193. ClusterID: cliConf.Cluster,
  194. AppName: appName,
  195. AppRevisionID: updateResp.AppRevisionId,
  196. PRNumber: prNumber,
  197. CommitSHA: commitSHA,
  198. })
  199. if status == models.AppRevisionStatus_DeployFailed {
  200. return errors.New("app failed to deploy")
  201. }
  202. if status == models.AppRevisionStatus_PredeployFailed {
  203. return errors.New("predeploy failed for new revision")
  204. }
  205. color.New(color.FgGreen).Printf("Successfully applied new revision %s\n", updateResp.AppRevisionId) // nolint:errcheck,gosec
  206. return nil
  207. }
  208. // checkDeployTimeout is the timeout for checking if an app has been deployed
  209. const checkDeployTimeout = 15 * time.Minute
  210. // checkDeployFrequency is the frequency for checking if an app has been deployed
  211. const checkDeployFrequency = 10 * time.Second
  212. func gitSourceFromEnv() (porter_app.GitSource, error) {
  213. var source porter_app.GitSource
  214. var repoID uint
  215. if os.Getenv("GITHUB_REPOSITORY_ID") != "" {
  216. id, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  217. if err != nil {
  218. return source, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  219. }
  220. repoID = uint(id)
  221. }
  222. return porter_app.GitSource{
  223. GitBranch: os.Getenv("GITHUB_REF_NAME"),
  224. GitRepoID: repoID,
  225. GitRepoName: os.Getenv("GITHUB_REPOSITORY"),
  226. }, nil
  227. }
  228. type buildInputFromBuildSettingsInput struct {
  229. projectID uint
  230. appName string
  231. commitSHA string
  232. image porter_app.Image
  233. build porter_app.BuildSettings
  234. buildEnv map[string]string
  235. }
  236. func buildInputFromBuildSettings(inp buildInputFromBuildSettingsInput) (buildInput, error) {
  237. var buildSettings buildInput
  238. if inp.appName == "" {
  239. return buildSettings, errors.New("app name is empty")
  240. }
  241. if inp.image.Repository == "" {
  242. return buildSettings, errors.New("image repository is empty")
  243. }
  244. if inp.build.Method == "" {
  245. return buildSettings, errors.New("build method is empty")
  246. }
  247. if inp.commitSHA == "" {
  248. return buildSettings, errors.New("commit SHA is empty")
  249. }
  250. return buildInput{
  251. ProjectID: inp.projectID,
  252. AppName: inp.appName,
  253. BuildContext: inp.build.Context,
  254. Dockerfile: inp.build.Dockerfile,
  255. BuildMethod: inp.build.Method,
  256. Builder: inp.build.Builder,
  257. BuildPacks: inp.build.Buildpacks,
  258. ImageTag: inp.commitSHA,
  259. RepositoryURL: inp.image.Repository,
  260. CurrentImageTag: inp.image.Tag,
  261. Env: inp.buildEnv,
  262. }, nil
  263. }