apply.go 17 KB

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