apply.go 16 KB

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