update.go 11 KB

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