apply.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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/fatih/color"
  14. "github.com/porter-dev/porter/api/server/handlers/porter_app"
  15. "github.com/porter-dev/porter/api/types"
  16. "github.com/porter-dev/porter/internal/models"
  17. "github.com/cli/cli/git"
  18. api "github.com/porter-dev/porter/api/client"
  19. "github.com/porter-dev/porter/cli/cmd/config"
  20. )
  21. // ApplyInput is the input for the Apply function
  22. type ApplyInput struct {
  23. // CLIConfig is the CLI configuration
  24. CLIConfig config.CLIConfig
  25. // Client is the Porter API client
  26. Client api.Client
  27. // PorterYamlPath is the path to the porter.yaml file
  28. PorterYamlPath string
  29. // AppName is the name of the app
  30. AppName string
  31. // ImageTagOverride is the image tag to use for the app
  32. ImageTagOverride string
  33. // PreviewApply is true when Apply should create a new deployment target matching current git branch and apply to that target
  34. PreviewApply bool
  35. // WaitForSuccessfulDeployment is true when Apply should wait for the update to complete before returning
  36. WaitForSuccessfulDeployment bool
  37. // PullImageBeforeBuild will attempt to pull the image before building if true
  38. PullImageBeforeBuild bool
  39. // WithPredeploy is true when Apply should run the predeploy step
  40. WithPredeploy bool
  41. // Description is the description for the image update
  42. Description string
  43. }
  44. // Apply implements the functionality of the `porter apply` command for validate apply v2 projects
  45. func Apply(ctx context.Context, inp ApplyInput) error {
  46. ctx, cancel := context.WithCancel(ctx)
  47. defer cancel()
  48. go func() {
  49. termChan := make(chan os.Signal, 1)
  50. signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)
  51. select {
  52. case <-termChan:
  53. color.New(color.FgYellow).Printf("Shutdown signal received, cancelling processes\n") // nolint:errcheck,gosec
  54. cancel()
  55. case <-ctx.Done():
  56. }
  57. }()
  58. cliConf := inp.CLIConfig
  59. client := inp.Client
  60. deploymentTargetID, err := deploymentTargetFromConfig(ctx, client, cliConf.Project, cliConf.Cluster, inp.PreviewApply)
  61. if err != nil {
  62. return fmt.Errorf("error getting deployment target from config: %w", err)
  63. }
  64. var prNumber int
  65. prNumberEnv := os.Getenv("PORTER_PR_NUMBER")
  66. if prNumberEnv != "" {
  67. prNumber, err = strconv.Atoi(prNumberEnv)
  68. if err != nil {
  69. return fmt.Errorf("error parsing PORTER_PR_NUMBER to int: %w", err)
  70. }
  71. }
  72. porterYamlExists := len(inp.PorterYamlPath) != 0
  73. if porterYamlExists {
  74. _, err := os.Stat(filepath.Clean(inp.PorterYamlPath))
  75. if err != nil {
  76. if !os.IsNotExist(err) {
  77. return fmt.Errorf("error checking if porter yaml exists at path %s: %w", inp.PorterYamlPath, err)
  78. }
  79. // If a path was specified but the file does not exist, we will not immediately error out.
  80. // This supports users migrated from v1 who use a workflow file that always specifies a porter yaml path
  81. // in the apply command.
  82. porterYamlExists = false
  83. }
  84. }
  85. var b64YAML string
  86. if porterYamlExists {
  87. porterYaml, err := os.ReadFile(filepath.Clean(inp.PorterYamlPath))
  88. if err != nil {
  89. return fmt.Errorf("could not read porter yaml file: %w", err)
  90. }
  91. b64YAML = base64.StdEncoding.EncodeToString(porterYaml)
  92. color.New(color.FgGreen).Printf("Using Porter YAML at path: %s\n", inp.PorterYamlPath) // nolint:errcheck,gosec
  93. }
  94. commitSHA := commitSHAFromEnv()
  95. gitSource, err := gitSourceFromEnv()
  96. if err != nil {
  97. return fmt.Errorf("error getting git source from env: %w", err)
  98. }
  99. var base64Description string
  100. if inp.Description != "" {
  101. base64Description = base64.StdEncoding.EncodeToString([]byte(inp.Description))
  102. }
  103. updateInput := api.UpdateAppInput{
  104. ProjectID: cliConf.Project,
  105. ClusterID: cliConf.Cluster,
  106. Name: inp.AppName,
  107. ImageTagOverride: inp.ImageTagOverride,
  108. GitSource: gitSource,
  109. DeploymentTargetId: deploymentTargetID,
  110. CommitSHA: commitSHA,
  111. Base64PorterYAML: b64YAML,
  112. WithPredeploy: inp.WithPredeploy,
  113. Base64Description: base64Description,
  114. }
  115. updateResp, err := client.UpdateApp(ctx, updateInput)
  116. if err != nil {
  117. return fmt.Errorf("error calling update app endpoint: %w", err)
  118. }
  119. if updateResp.AppRevisionId == "" {
  120. return errors.New("app revision id is empty")
  121. }
  122. appName := updateResp.AppName
  123. buildSettings, err := client.GetBuildFromRevision(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId)
  124. if err != nil {
  125. return fmt.Errorf("error getting build from revision: %w", err)
  126. }
  127. if buildSettings != nil && buildSettings.Build.Method != "" {
  128. eventID, _ := createBuildEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, commitSHA)
  129. var buildFinished bool
  130. var buildError error
  131. var buildLogs string
  132. defer func() {
  133. if buildError != nil && !errors.Is(buildError, context.Canceled) {
  134. reportBuildFailureInput := reportBuildFailureInput{
  135. client: client,
  136. appName: appName,
  137. cliConf: cliConf,
  138. deploymentTargetID: deploymentTargetID,
  139. appRevisionID: updateResp.AppRevisionId,
  140. eventID: eventID,
  141. commitSHA: commitSHA,
  142. prNumber: prNumber,
  143. buildError: buildError,
  144. buildLogs: buildLogs,
  145. }
  146. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  147. return
  148. }
  149. if !buildFinished {
  150. buildMetadata := make(map[string]interface{})
  151. buildMetadata["end_time"] = time.Now().UTC()
  152. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_Build, eventID, types.PorterAppEventStatus_Canceled, buildMetadata)
  153. return
  154. }
  155. }()
  156. if commitSHA == "" {
  157. 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")
  158. }
  159. color.New(color.FgGreen).Printf("Building new image with tag %s...\n", commitSHA) // nolint:errcheck,gosec
  160. buildInput, err := buildInputFromBuildSettings(buildInputFromBuildSettingsInput{
  161. projectID: cliConf.Project,
  162. appName: appName,
  163. commitSHA: commitSHA,
  164. image: buildSettings.Image,
  165. build: buildSettings.Build,
  166. buildEnv: buildSettings.BuildEnvVariables,
  167. pullImageBeforeBuild: inp.PullImageBeforeBuild,
  168. })
  169. if err != nil {
  170. buildError = fmt.Errorf("error creating build input from build settings: %w", err)
  171. return buildError
  172. }
  173. buildOutput := build(ctx, client, buildInput)
  174. if buildOutput.Error != nil {
  175. buildError = fmt.Errorf("error building app: %w", buildOutput.Error)
  176. buildLogs = buildOutput.Logs
  177. return buildError
  178. }
  179. _, err = client.UpdateRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId, models.AppRevisionStatus_BuildSuccessful)
  180. if err != nil {
  181. buildError = fmt.Errorf("error updating revision status post build: %w", err)
  182. return buildError
  183. }
  184. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", commitSHA) // nolint:errcheck,gosec
  185. buildMetadata := make(map[string]interface{})
  186. buildMetadata["end_time"] = time.Now().UTC()
  187. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_Build, eventID, types.PorterAppEventStatus_Success, buildMetadata)
  188. buildFinished = true
  189. }
  190. color.New(color.FgGreen).Printf("Deploying new revision %s for app %s...\n", updateResp.AppRevisionId, appName) // nolint:errcheck,gosec
  191. now := time.Now().UTC()
  192. for {
  193. if time.Since(now) > checkDeployTimeout {
  194. return errors.New("timed out waiting for app to deploy")
  195. }
  196. status, err := client.GetRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId)
  197. if err != nil {
  198. return fmt.Errorf("error getting app revision status: %w", err)
  199. }
  200. if status == nil {
  201. return errors.New("unable to determine status of app revision")
  202. }
  203. if status.AppRevisionStatus.IsInTerminalStatus {
  204. break
  205. }
  206. if status.AppRevisionStatus.PredeployStarted {
  207. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  208. }
  209. if status.AppRevisionStatus.InstallStarted {
  210. color.New(color.FgGreen).Printf("Waiting for deploy to complete...\n") // nolint:errcheck,gosec
  211. }
  212. time.Sleep(checkDeployFrequency)
  213. }
  214. _, _ = client.ReportRevisionStatus(ctx, api.ReportRevisionStatusInput{
  215. ProjectID: cliConf.Project,
  216. ClusterID: cliConf.Cluster,
  217. AppName: appName,
  218. AppRevisionID: updateResp.AppRevisionId,
  219. PRNumber: prNumber,
  220. CommitSHA: commitSHA,
  221. })
  222. status, err := client.GetRevisionStatus(ctx, cliConf.Project, cliConf.Cluster, appName, updateResp.AppRevisionId)
  223. if err != nil {
  224. return fmt.Errorf("error getting app revision status: %w", err)
  225. }
  226. if status == nil {
  227. return errors.New("unable to determine status of app revision")
  228. }
  229. if status.AppRevisionStatus.InstallFailed {
  230. return errors.New("app failed to deploy")
  231. }
  232. if status.AppRevisionStatus.PredeployFailed {
  233. return errors.New("predeploy failed for new revision")
  234. }
  235. color.New(color.FgGreen).Printf("Successfully applied new revision %s\n", updateResp.AppRevisionId) // nolint:errcheck,gosec
  236. if inp.WaitForSuccessfulDeployment {
  237. return waitForAppRevisionStatus(ctx, waitForAppRevisionStatusInput{
  238. ProjectID: cliConf.Project,
  239. ClusterID: cliConf.Cluster,
  240. AppName: appName,
  241. RevisionID: updateResp.AppRevisionId,
  242. Client: client,
  243. })
  244. }
  245. return nil
  246. }
  247. func commitSHAFromEnv() string {
  248. var commitSHA string
  249. if os.Getenv("PORTER_COMMIT_SHA") != "" {
  250. commitSHA = os.Getenv("PORTER_COMMIT_SHA")
  251. } else if os.Getenv("GITHUB_SHA") != "" {
  252. commitSHA = os.Getenv("GITHUB_SHA")
  253. } else if commit, err := git.LastCommit(); err == nil && commit != nil {
  254. commitSHA = commit.Sha
  255. }
  256. return commitSHA
  257. }
  258. func deploymentTargetFromConfig(ctx context.Context, client api.Client, projectID, clusterID uint, previewApply bool) (string, error) {
  259. var deploymentTargetID string
  260. if os.Getenv("PORTER_DEPLOYMENT_TARGET_ID") != "" {
  261. deploymentTargetID = os.Getenv("PORTER_DEPLOYMENT_TARGET_ID")
  262. }
  263. if deploymentTargetID == "" {
  264. targetResp, err := client.DefaultDeploymentTarget(ctx, projectID, clusterID)
  265. if err != nil {
  266. return deploymentTargetID, fmt.Errorf("error calling default deployment target endpoint: %w", err)
  267. }
  268. deploymentTargetID = targetResp.DeploymentTargetID
  269. }
  270. if previewApply {
  271. var branchName string
  272. // branch name is set to different values in the GH env, depending on whether or not the workflow is triggered by a PR
  273. // issue is being tracked here: https://github.com/github/docs/issues/15319
  274. if os.Getenv("GITHUB_HEAD_REF") != "" {
  275. branchName = os.Getenv("GITHUB_HEAD_REF")
  276. } else if os.Getenv("GITHUB_REF_NAME") != "" {
  277. branchName = os.Getenv("GITHUB_REF_NAME")
  278. } else if branch, err := git.CurrentBranch(); err == nil {
  279. branchName = branch
  280. }
  281. if branchName == "" {
  282. return deploymentTargetID, errors.New("branch name is empty. Please run apply in a git repository with access to the git CLI")
  283. }
  284. targetResp, err := client.CreateDeploymentTarget(ctx, projectID, clusterID, branchName, true)
  285. if err != nil {
  286. return deploymentTargetID, fmt.Errorf("error calling create deployment target endpoint: %w", err)
  287. }
  288. deploymentTargetID = targetResp.DeploymentTargetID
  289. }
  290. if deploymentTargetID == "" {
  291. return deploymentTargetID, errors.New("deployment target id is empty")
  292. }
  293. return deploymentTargetID, nil
  294. }
  295. type reportBuildFailureInput struct {
  296. client api.Client
  297. appName string
  298. cliConf config.CLIConfig
  299. deploymentTargetID string
  300. appRevisionID string
  301. eventID string
  302. buildError error
  303. buildLogs string
  304. commitSHA string
  305. prNumber int
  306. }
  307. func reportBuildFailure(ctx context.Context, inp reportBuildFailureInput) error {
  308. _, err := inp.client.UpdateRevisionStatus(ctx, inp.cliConf.Project, inp.cliConf.Cluster, inp.appName, inp.appRevisionID, models.AppRevisionStatus_BuildFailed)
  309. if err != nil {
  310. return err
  311. }
  312. buildMetadata := make(map[string]interface{})
  313. buildMetadata["end_time"] = time.Now().UTC()
  314. // the below is a temporary solution until we can report build errors via telemetry from the CLI
  315. errorStringMap := make(map[string]string)
  316. errorStringMap["build-error"] = fmt.Sprintf("%+v", inp.buildError)
  317. b64BuildLogs := base64.StdEncoding.EncodeToString([]byte(inp.buildLogs))
  318. // the key name below must be kept the same so that reportBuildStatus in the CreateOrUpdatePorterAppEvent handler reports logs correctly
  319. errorStringMap["b64-build-logs"] = b64BuildLogs
  320. buildMetadata["errors"] = errorStringMap
  321. err = updateExistingEvent(ctx, inp.client, inp.appName, inp.cliConf.Project, inp.cliConf.Cluster, inp.deploymentTargetID, types.PorterAppEventType_Build, inp.eventID, types.PorterAppEventStatus_Failed, buildMetadata)
  322. if err != nil {
  323. return err
  324. }
  325. _, err = inp.client.ReportRevisionStatus(ctx, api.ReportRevisionStatusInput{
  326. ProjectID: inp.cliConf.Project,
  327. ClusterID: inp.cliConf.Cluster,
  328. AppName: inp.appName,
  329. AppRevisionID: inp.appRevisionID,
  330. PRNumber: inp.prNumber,
  331. CommitSHA: inp.commitSHA,
  332. })
  333. if err != nil {
  334. return err
  335. }
  336. return nil
  337. }
  338. // checkDeployTimeout is the timeout for checking if an app has been deployed
  339. const checkDeployTimeout = 15 * time.Minute
  340. // checkDeployFrequency is the frequency for checking if an app has been deployed
  341. const checkDeployFrequency = 10 * time.Second
  342. func gitSourceFromEnv() (porter_app.GitSource, error) {
  343. var source porter_app.GitSource
  344. var repoID uint
  345. if os.Getenv("GITHUB_REPOSITORY_ID") != "" {
  346. id, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  347. if err != nil {
  348. return source, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  349. }
  350. repoID = uint(id)
  351. }
  352. return porter_app.GitSource{
  353. GitBranch: os.Getenv("GITHUB_REF_NAME"),
  354. GitRepoID: repoID,
  355. GitRepoName: os.Getenv("GITHUB_REPOSITORY"),
  356. }, nil
  357. }
  358. type buildInputFromBuildSettingsInput struct {
  359. projectID uint
  360. appName string
  361. commitSHA string
  362. image porter_app.Image
  363. build porter_app.BuildSettings
  364. buildEnv map[string]string
  365. pullImageBeforeBuild bool
  366. }
  367. func buildInputFromBuildSettings(inp buildInputFromBuildSettingsInput) (buildInput, error) {
  368. var buildSettings buildInput
  369. if inp.appName == "" {
  370. return buildSettings, errors.New("app name is empty")
  371. }
  372. if inp.image.Repository == "" {
  373. return buildSettings, errors.New("image repository is empty")
  374. }
  375. if inp.build.Method == "" {
  376. return buildSettings, errors.New("build method is empty")
  377. }
  378. if inp.commitSHA == "" {
  379. return buildSettings, errors.New("commit SHA is empty")
  380. }
  381. return buildInput{
  382. ProjectID: inp.projectID,
  383. AppName: inp.appName,
  384. BuildContext: inp.build.Context,
  385. Dockerfile: inp.build.Dockerfile,
  386. BuildMethod: inp.build.Method,
  387. Builder: inp.build.Builder,
  388. BuildPacks: inp.build.Buildpacks,
  389. ImageTag: inp.commitSHA,
  390. RepositoryURL: inp.image.Repository,
  391. CurrentImageTag: inp.image.Tag,
  392. Env: inp.buildEnv,
  393. PullImageBeforeBuild: inp.pullImageBeforeBuild,
  394. }, nil
  395. }