apply.go 15 KB

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