apply.go 17 KB

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