apply.go 15 KB

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