2
0

apply.go 17 KB

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