apply.go 16 KB

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