update.go 11 KB

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