update.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. // ImageTagOverride is the image tag to use for the app revision
  31. ImageTagOverride string
  32. // PreviewApply is true when Update should create a new deployment target matching current git branch and apply to that target
  33. PreviewApply bool
  34. // WaitForSuccessfulDeployment is true when Update should wait for the revision deployment to complete (all services deployed successfully)
  35. WaitForSuccessfulDeployment bool
  36. // PullImageBeforeBuild will attempt to pull the image before building if true
  37. PullImageBeforeBuild bool
  38. }
  39. // Update implements the functionality of the `porter apply` command for validate apply v2 projects
  40. func Update(ctx context.Context, inp UpdateInput) error {
  41. ctx, cancel := context.WithCancel(ctx)
  42. defer cancel()
  43. go func() {
  44. termChan := make(chan os.Signal, 1)
  45. signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)
  46. select {
  47. case <-termChan:
  48. color.New(color.FgYellow).Printf("Shutdown signal received, cancelling processes\n") // nolint:errcheck,gosec
  49. cancel()
  50. case <-ctx.Done():
  51. }
  52. }()
  53. cliConf := inp.CLIConfig
  54. client := inp.Client
  55. deploymentTargetID, err := deploymentTargetFromConfig(ctx, client, cliConf.Project, cliConf.Cluster, inp.PreviewApply)
  56. if err != nil {
  57. return fmt.Errorf("error getting deployment target from config: %w", err)
  58. }
  59. var prNumber int
  60. prNumberEnv := os.Getenv("PORTER_PR_NUMBER")
  61. if prNumberEnv != "" {
  62. prNumber, err = strconv.Atoi(prNumberEnv)
  63. if err != nil {
  64. return fmt.Errorf("error parsing PORTER_PR_NUMBER to int: %w", err)
  65. }
  66. }
  67. porterYamlExists := len(inp.PorterYamlPath) != 0
  68. if porterYamlExists {
  69. _, err := os.Stat(filepath.Clean(inp.PorterYamlPath))
  70. if err != nil {
  71. if !os.IsNotExist(err) {
  72. return fmt.Errorf("error checking if porter yaml exists at path %s: %w", inp.PorterYamlPath, err)
  73. }
  74. // If a path was specified but the file does not exist, we will not immediately error out.
  75. // This supports users migrated from v1 who use a workflow file that always specifies a porter yaml path
  76. // in the apply command.
  77. porterYamlExists = false
  78. }
  79. }
  80. var b64YAML string
  81. if porterYamlExists {
  82. porterYaml, err := os.ReadFile(filepath.Clean(inp.PorterYamlPath))
  83. if err != nil {
  84. return fmt.Errorf("could not read porter yaml file: %w", err)
  85. }
  86. b64YAML = base64.StdEncoding.EncodeToString(porterYaml)
  87. color.New(color.FgGreen).Printf("Using Porter YAML at path: %s\n", inp.PorterYamlPath) // nolint:errcheck,gosec
  88. }
  89. commitSHA := commitSHAFromEnv()
  90. gitSource, err := gitSourceFromEnv()
  91. if err != nil {
  92. return fmt.Errorf("error getting git source from env: %w", err)
  93. }
  94. updateInput := api.UpdateAppInput{
  95. ProjectID: cliConf.Project,
  96. ClusterID: cliConf.Cluster,
  97. Name: inp.AppName,
  98. ImageTagOverride: inp.ImageTagOverride,
  99. GitSource: gitSource,
  100. DeploymentTargetId: deploymentTargetID,
  101. CommitSHA: commitSHA,
  102. Base64PorterYAML: b64YAML,
  103. }
  104. updateResp, err := client.UpdateApp(ctx, updateInput)
  105. if err != nil {
  106. return fmt.Errorf("error calling update app endpoint: %w", err)
  107. }
  108. if updateResp.AppRevisionId == "" {
  109. return errors.New("app revision id is empty")
  110. }
  111. appName := updateResp.AppName
  112. buildSettings, err := client.GetBuildFromRevision(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId)
  113. if err != nil {
  114. return fmt.Errorf("error getting build from revision: %w", err)
  115. }
  116. if buildSettings != nil && buildSettings.Build.Method != "" {
  117. eventID, _ := createBuildEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, commitSHA)
  118. var buildFinished bool
  119. var buildError error
  120. var buildLogs string
  121. defer func() {
  122. if buildError != nil && !errors.Is(buildError, context.Canceled) {
  123. reportBuildFailureInput := reportBuildFailureInput{
  124. client: client,
  125. appName: appName,
  126. cliConf: cliConf,
  127. deploymentTargetID: deploymentTargetID,
  128. appRevisionID: updateResp.AppRevisionId,
  129. eventID: eventID,
  130. commitSHA: commitSHA,
  131. prNumber: prNumber,
  132. buildError: buildError,
  133. buildLogs: buildLogs,
  134. }
  135. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  136. return
  137. }
  138. if !buildFinished {
  139. buildMetadata := make(map[string]interface{})
  140. buildMetadata["end_time"] = time.Now().UTC()
  141. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_Build, eventID, types.PorterAppEventStatus_Canceled, buildMetadata)
  142. return
  143. }
  144. }()
  145. if commitSHA == "" {
  146. 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")
  147. }
  148. color.New(color.FgGreen).Printf("Building new image with tag %s...\n", commitSHA) // nolint:errcheck,gosec
  149. buildInput, err := buildInputFromBuildSettings(buildInputFromBuildSettingsInput{
  150. projectID: cliConf.Project,
  151. appName: appName,
  152. commitSHA: commitSHA,
  153. image: buildSettings.Image,
  154. build: buildSettings.Build,
  155. buildEnv: buildSettings.BuildEnvVariables,
  156. pullImageBeforeBuild: inp.PullImageBeforeBuild,
  157. })
  158. if err != nil {
  159. buildError = fmt.Errorf("error creating build input from build settings: %w", err)
  160. return buildError
  161. }
  162. buildOutput := build(ctx, client, buildInput)
  163. if buildOutput.Error != nil {
  164. buildError = fmt.Errorf("error building app: %w", buildOutput.Error)
  165. buildLogs = buildOutput.Logs
  166. return buildError
  167. }
  168. _, err = client.UpdateRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId, models.AppRevisionStatus_BuildSuccessful)
  169. if err != nil {
  170. buildError = fmt.Errorf("error updating revision status post build: %w", err)
  171. return buildError
  172. }
  173. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", commitSHA) // nolint:errcheck,gosec
  174. buildMetadata := make(map[string]interface{})
  175. buildMetadata["end_time"] = time.Now().UTC()
  176. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_Build, eventID, types.PorterAppEventStatus_Success, buildMetadata)
  177. buildFinished = true
  178. }
  179. color.New(color.FgGreen).Printf("Deploying new revision %s for app %s...\n", updateResp.AppRevisionId, appName) // nolint:errcheck,gosec
  180. now := time.Now().UTC()
  181. for {
  182. if time.Since(now) > checkDeployTimeout {
  183. return errors.New("timed out waiting for app to deploy")
  184. }
  185. status, err := client.GetRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId)
  186. if err != nil {
  187. return fmt.Errorf("error getting app revision status: %w", err)
  188. }
  189. if status == nil {
  190. return errors.New("unable to determine status of app revision")
  191. }
  192. if status.AppRevisionStatus.IsInTerminalStatus {
  193. break
  194. }
  195. if status.AppRevisionStatus.PredeployStarted {
  196. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  197. }
  198. if status.AppRevisionStatus.InstallStarted {
  199. color.New(color.FgGreen).Printf("Waiting for deploy to complete...\n") // nolint:errcheck,gosec
  200. }
  201. time.Sleep(checkDeployFrequency)
  202. }
  203. _, _ = client.ReportRevisionStatus(ctx, api.ReportRevisionStatusInput{
  204. ProjectID: cliConf.Project,
  205. ClusterID: cliConf.Cluster,
  206. AppName: appName,
  207. AppRevisionID: updateResp.AppRevisionId,
  208. PRNumber: prNumber,
  209. CommitSHA: commitSHA,
  210. })
  211. status, err := client.GetRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId)
  212. if err != nil {
  213. return fmt.Errorf("error getting app revision status: %w", err)
  214. }
  215. if status == nil {
  216. return errors.New("unable to determine status of app revision")
  217. }
  218. if status.AppRevisionStatus.InstallFailed {
  219. return errors.New("app failed to deploy")
  220. }
  221. if status.AppRevisionStatus.PredeployFailed {
  222. return errors.New("predeploy failed for new revision")
  223. }
  224. color.New(color.FgGreen).Printf("Successfully applied new revision %s\n", updateResp.AppRevisionId) // nolint:errcheck,gosec
  225. if inp.WaitForSuccessfulDeployment {
  226. return waitForAppRevisionStatus(ctx, waitForAppRevisionStatusInput{
  227. ProjectID: cliConf.Project,
  228. ClusterID: cliConf.Cluster,
  229. AppName: appName,
  230. RevisionID: updateResp.AppRevisionId,
  231. Client: client,
  232. })
  233. }
  234. return nil
  235. }
  236. // checkDeployTimeout is the timeout for checking if an app has been deployed
  237. const checkDeployTimeout = 15 * time.Minute
  238. // checkDeployFrequency is the frequency for checking if an app has been deployed
  239. const checkDeployFrequency = 10 * time.Second
  240. func gitSourceFromEnv() (porter_app.GitSource, error) {
  241. var source porter_app.GitSource
  242. var repoID uint
  243. if os.Getenv("GITHUB_REPOSITORY_ID") != "" {
  244. id, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  245. if err != nil {
  246. return source, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  247. }
  248. repoID = uint(id)
  249. }
  250. return porter_app.GitSource{
  251. GitBranch: os.Getenv("GITHUB_REF_NAME"),
  252. GitRepoID: repoID,
  253. GitRepoName: os.Getenv("GITHUB_REPOSITORY"),
  254. }, nil
  255. }
  256. type buildInputFromBuildSettingsInput struct {
  257. projectID uint
  258. appName string
  259. commitSHA string
  260. image porter_app.Image
  261. build porter_app.BuildSettings
  262. buildEnv map[string]string
  263. pullImageBeforeBuild bool
  264. }
  265. func buildInputFromBuildSettings(inp buildInputFromBuildSettingsInput) (buildInput, error) {
  266. var buildSettings buildInput
  267. if inp.appName == "" {
  268. return buildSettings, errors.New("app name is empty")
  269. }
  270. if inp.image.Repository == "" {
  271. return buildSettings, errors.New("image repository is empty")
  272. }
  273. if inp.build.Method == "" {
  274. return buildSettings, errors.New("build method is empty")
  275. }
  276. if inp.commitSHA == "" {
  277. return buildSettings, errors.New("commit SHA is empty")
  278. }
  279. return buildInput{
  280. ProjectID: inp.projectID,
  281. AppName: inp.appName,
  282. BuildContext: inp.build.Context,
  283. Dockerfile: inp.build.Dockerfile,
  284. BuildMethod: inp.build.Method,
  285. Builder: inp.build.Builder,
  286. BuildPacks: inp.build.Buildpacks,
  287. ImageTag: inp.commitSHA,
  288. RepositoryURL: inp.image.Repository,
  289. CurrentImageTag: inp.image.Tag,
  290. Env: inp.buildEnv,
  291. PullImageBeforeBuild: inp.pullImageBeforeBuild,
  292. }, nil
  293. }