update.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 *porter_app.GetAppRevisionStatusResponse
  174. for {
  175. if time.Since(now) > checkDeployTimeout {
  176. return errors.New("timed out waiting for app to deploy")
  177. }
  178. status, err := client.GetRevisionStatus(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. if status == nil {
  183. return errors.New("unable to determine status of app revision")
  184. }
  185. if status.AppRevisionStatus.PredeployStarted {
  186. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  187. }
  188. if status.AppRevisionStatus.InstallStarted {
  189. color.New(color.FgGreen).Printf("Waiting for deploy to complete...\n") // nolint:errcheck,gosec
  190. }
  191. if status.AppRevisionStatus.IsInTerminalStatus {
  192. break
  193. }
  194. time.Sleep(checkDeployFrequency)
  195. }
  196. _, _ = client.ReportRevisionStatus(ctx, api.ReportRevisionStatusInput{
  197. ProjectID: cliConf.Project,
  198. ClusterID: cliConf.Cluster,
  199. AppName: appName,
  200. AppRevisionID: updateResp.AppRevisionId,
  201. PRNumber: prNumber,
  202. CommitSHA: commitSHA,
  203. })
  204. if status.AppRevisionStatus.InstallFailed {
  205. return errors.New("app failed to deploy")
  206. }
  207. if status.AppRevisionStatus.PredeployFailed {
  208. return errors.New("predeploy failed for new revision")
  209. }
  210. color.New(color.FgGreen).Printf("Successfully applied new revision %s\n", updateResp.AppRevisionId) // nolint:errcheck,gosec
  211. return nil
  212. }
  213. // checkDeployTimeout is the timeout for checking if an app has been deployed
  214. const checkDeployTimeout = 15 * time.Minute
  215. // checkDeployFrequency is the frequency for checking if an app has been deployed
  216. const checkDeployFrequency = 10 * time.Second
  217. func gitSourceFromEnv() (porter_app.GitSource, error) {
  218. var source porter_app.GitSource
  219. var repoID uint
  220. if os.Getenv("GITHUB_REPOSITORY_ID") != "" {
  221. id, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  222. if err != nil {
  223. return source, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  224. }
  225. repoID = uint(id)
  226. }
  227. return porter_app.GitSource{
  228. GitBranch: os.Getenv("GITHUB_REF_NAME"),
  229. GitRepoID: repoID,
  230. GitRepoName: os.Getenv("GITHUB_REPOSITORY"),
  231. }, nil
  232. }
  233. type buildInputFromBuildSettingsInput struct {
  234. projectID uint
  235. appName string
  236. commitSHA string
  237. image porter_app.Image
  238. build porter_app.BuildSettings
  239. buildEnv map[string]string
  240. }
  241. func buildInputFromBuildSettings(inp buildInputFromBuildSettingsInput) (buildInput, error) {
  242. var buildSettings buildInput
  243. if inp.appName == "" {
  244. return buildSettings, errors.New("app name is empty")
  245. }
  246. if inp.image.Repository == "" {
  247. return buildSettings, errors.New("image repository is empty")
  248. }
  249. if inp.build.Method == "" {
  250. return buildSettings, errors.New("build method is empty")
  251. }
  252. if inp.commitSHA == "" {
  253. return buildSettings, errors.New("commit SHA is empty")
  254. }
  255. return buildInput{
  256. ProjectID: inp.projectID,
  257. AppName: inp.appName,
  258. BuildContext: inp.build.Context,
  259. Dockerfile: inp.build.Dockerfile,
  260. BuildMethod: inp.build.Method,
  261. Builder: inp.build.Builder,
  262. BuildPacks: inp.build.Buildpacks,
  263. ImageTag: inp.commitSHA,
  264. RepositoryURL: inp.image.Repository,
  265. CurrentImageTag: inp.image.Tag,
  266. Env: inp.buildEnv,
  267. }, nil
  268. }