apply.go 17 KB

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