apply.go 15 KB

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