apply.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. package v2
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "time"
  11. "github.com/porter-dev/porter/api/server/handlers/porter_app"
  12. "github.com/porter-dev/porter/api/types"
  13. "github.com/porter-dev/porter/internal/models"
  14. "github.com/cli/cli/git"
  15. "github.com/fatih/color"
  16. "github.com/porter-dev/api-contracts/generated/go/helpers"
  17. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  18. api "github.com/porter-dev/porter/api/client"
  19. "github.com/porter-dev/porter/cli/cmd/config"
  20. )
  21. // ApplyInput is the input for the Apply function
  22. type ApplyInput struct {
  23. // CLIConfig is the CLI configuration
  24. CLIConfig config.CLIConfig
  25. // Client is the Porter API client
  26. Client api.Client
  27. // PorterYamlPath is the path to the porter.yaml file
  28. PorterYamlPath string
  29. // AppName is the name of the app
  30. AppName string
  31. // ImageTagOverride is the image tag to use for the app
  32. ImageTagOverride string
  33. // PreviewApply is true when Apply should create a new deployment target matching current git branch and apply to that target
  34. PreviewApply bool
  35. // WaitForSuccessfulDeployment is true when Apply should wait for the update to complete before returning
  36. WaitForSuccessfulDeployment bool
  37. // PullImageBeforeBuild will attempt to pull the image before building if true
  38. PullImageBeforeBuild bool
  39. }
  40. // Apply implements the functionality of the `porter apply` command for validate apply v2 projects
  41. func Apply(ctx context.Context, inp ApplyInput) error {
  42. const forceBuild = true
  43. var b64AppProto string
  44. cliConf := inp.CLIConfig
  45. client := inp.Client
  46. useNewApplyResp, err := client.UseNewApplyLogic(ctx, cliConf.Project, cliConf.Cluster)
  47. if err != nil {
  48. return fmt.Errorf("error checking if project uses new apply logic: %w", err)
  49. }
  50. if useNewApplyResp.UseNewApplyLogic {
  51. return Update(ctx, UpdateInput(inp))
  52. }
  53. deploymentTargetID, err := deploymentTargetFromConfig(ctx, client, cliConf.Project, cliConf.Cluster, inp.PreviewApply)
  54. if err != nil {
  55. return fmt.Errorf("error getting deployment target from config: %w", err)
  56. }
  57. var prNumber int
  58. prNumberEnv := os.Getenv("PORTER_PR_NUMBER")
  59. if prNumberEnv != "" {
  60. prNumber, err = strconv.Atoi(prNumberEnv)
  61. if err != nil {
  62. return fmt.Errorf("error parsing PORTER_PR_NUMBER to int: %w", err)
  63. }
  64. }
  65. porterYamlExists := len(inp.PorterYamlPath) != 0
  66. if porterYamlExists {
  67. _, err := os.Stat(filepath.Clean(inp.PorterYamlPath))
  68. if err != nil {
  69. if !os.IsNotExist(err) {
  70. return fmt.Errorf("error checking if porter yaml exists at path %s: %w", inp.PorterYamlPath, err)
  71. }
  72. // If a path was specified but the file does not exist, we will not immediately error out.
  73. // This supports users migrated from v1 who use a workflow file that always specifies a porter yaml path
  74. // in the apply command.
  75. porterYamlExists = false
  76. }
  77. }
  78. // overrides incorporated into the app contract baed on the deployment target
  79. var overrides *porter_app.EncodedAppWithEnv
  80. // env variables and secrets to be passed to the apply endpoint
  81. var envVariables map[string]string
  82. var envSecrets map[string]string
  83. appName := inp.AppName
  84. if porterYamlExists {
  85. porterYaml, err := os.ReadFile(filepath.Clean(inp.PorterYamlPath))
  86. if err != nil {
  87. return fmt.Errorf("could not read porter yaml file: %w", err)
  88. }
  89. b64YAML := base64.StdEncoding.EncodeToString(porterYaml)
  90. // last argument is passed to accommodate users with v1 porter yamls
  91. parseResp, err := client.ParseYAML(ctx, cliConf.Project, cliConf.Cluster, b64YAML, appName)
  92. if err != nil {
  93. return fmt.Errorf("error calling parse yaml endpoint: %w", err)
  94. }
  95. if parseResp.B64AppProto == "" {
  96. return errors.New("b64 app proto is empty")
  97. }
  98. b64AppProto = parseResp.B64AppProto
  99. overrides = parseResp.PreviewApp
  100. envVariables = parseResp.EnvVariables
  101. envSecrets = parseResp.EnvSecrets
  102. // override app name if provided
  103. appName, err = appNameFromB64AppProto(parseResp.B64AppProto)
  104. if err != nil {
  105. return fmt.Errorf("error getting app name from porter.yaml: %w", err)
  106. }
  107. // we only need to create the app if a porter yaml is provided (otherwise it must already exist)
  108. createPorterAppDBEntryInp, err := createPorterAppDbEntryInputFromProtoAndEnv(parseResp.B64AppProto)
  109. if err != nil {
  110. return fmt.Errorf("unable to form porter app creation input from yaml: %w", err)
  111. }
  112. createPorterAppDBEntryInp.DeploymentTargetID = deploymentTargetID
  113. err = client.CreatePorterAppDBEntry(ctx, cliConf.Project, cliConf.Cluster, createPorterAppDBEntryInp)
  114. if err != nil {
  115. if err.Error() == porter_app.ErrMissingSourceType.Error() {
  116. return fmt.Errorf("cannot find existing Porter app with name %s and no build or image settings were specified in porter.yaml", appName)
  117. }
  118. return fmt.Errorf("unable to create porter app from yaml: %w", err)
  119. }
  120. color.New(color.FgGreen).Printf("Successfully parsed Porter YAML: applying app \"%s\"\n", appName) // nolint:errcheck,gosec
  121. }
  122. // b64AppOverrides is the base64-encoded app proto with preview environment specific overrides and env groups
  123. var b64AppOverrides string
  124. if inp.PreviewApply && overrides != nil {
  125. b64AppOverrides = overrides.B64AppProto
  126. previewEnvVariables := overrides.EnvVariables
  127. envVariables = mergeEnvVariables(envVariables, previewEnvVariables)
  128. }
  129. if appName == "" {
  130. return errors.New("App name is empty. Please provide a Porter YAML file specifying the name of the app or set the PORTER_APP_NAME environment variable.")
  131. }
  132. commitSHA := commitSHAFromEnv()
  133. validateResp, err := client.ValidatePorterApp(ctx, api.ValidatePorterAppInput{
  134. ProjectID: cliConf.Project,
  135. ClusterID: cliConf.Cluster,
  136. AppName: appName,
  137. Base64AppProto: b64AppProto,
  138. Base64AppOverrides: b64AppOverrides,
  139. DeploymentTarget: deploymentTargetID,
  140. CommitSHA: commitSHA,
  141. ImageTagOverride: inp.ImageTagOverride,
  142. })
  143. if err != nil {
  144. return fmt.Errorf("error calling validate endpoint: %w", err)
  145. }
  146. if validateResp.ValidatedBase64AppProto == "" {
  147. return errors.New("validated b64 app proto is empty")
  148. }
  149. base64AppProto := validateResp.ValidatedBase64AppProto
  150. applyInput := api.ApplyPorterAppInput{
  151. ProjectID: cliConf.Project,
  152. ClusterID: cliConf.Cluster,
  153. Base64AppProto: base64AppProto,
  154. DeploymentTarget: deploymentTargetID,
  155. ForceBuild: forceBuild,
  156. Variables: envVariables,
  157. Secrets: envSecrets,
  158. }
  159. applyResp, err := client.ApplyPorterApp(ctx, applyInput)
  160. if err != nil {
  161. return fmt.Errorf("error calling apply endpoint: %w", err)
  162. }
  163. if applyResp.AppRevisionId == "" {
  164. return errors.New("app revision id is empty")
  165. }
  166. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_BUILD {
  167. color.New(color.FgGreen).Printf("Building new image...\n") // nolint:errcheck,gosec
  168. eventID, _ := createBuildEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, commitSHA)
  169. reportBuildFailureInput := reportBuildFailureInput{
  170. client: client,
  171. appName: appName,
  172. cliConf: cliConf,
  173. deploymentTargetID: deploymentTargetID,
  174. appRevisionID: applyResp.AppRevisionId,
  175. eventID: eventID,
  176. commitSHA: commitSHA,
  177. prNumber: prNumber,
  178. }
  179. if commitSHA == "" {
  180. err := 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.")
  181. reportBuildFailureInput.buildError = err
  182. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  183. return err
  184. }
  185. buildSettings, err := buildSettingsFromBase64AppProto(base64AppProto)
  186. if err != nil {
  187. err := fmt.Errorf("error getting build settings from base64 app proto: %w", err)
  188. reportBuildFailureInput.buildError = err
  189. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  190. return err
  191. }
  192. currentAppRevisionResp, err := client.CurrentAppRevision(ctx, cliConf.Project, cliConf.Cluster, appName, deploymentTargetID)
  193. if err != nil {
  194. err := fmt.Errorf("error getting current app revision: %w", err)
  195. reportBuildFailureInput.buildError = err
  196. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  197. return err
  198. }
  199. if currentAppRevisionResp == nil {
  200. err := errors.New("current app revision is nil")
  201. reportBuildFailureInput.buildError = err
  202. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  203. return err
  204. }
  205. appRevision := currentAppRevisionResp.AppRevision
  206. if appRevision.B64AppProto == "" {
  207. err := errors.New("current app revision b64 app proto is empty")
  208. reportBuildFailureInput.buildError = err
  209. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  210. return err
  211. }
  212. currentImageTag, err := imageTagFromBase64AppProto(appRevision.B64AppProto)
  213. if err != nil {
  214. err := fmt.Errorf("error getting image tag from current app revision: %w", err)
  215. reportBuildFailureInput.buildError = err
  216. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  217. return err
  218. }
  219. buildSettings.CurrentImageTag = currentImageTag
  220. buildSettings.ProjectID = cliConf.Project
  221. buildEnv, err := client.GetBuildEnv(ctx, cliConf.Project, cliConf.Cluster, appName, appRevision.ID)
  222. if err != nil {
  223. err := fmt.Errorf("error getting build env: %w", err)
  224. reportBuildFailureInput.buildError = err
  225. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  226. return err
  227. }
  228. buildSettings.Env = buildEnv.BuildEnvVariables
  229. buildOutput := build(ctx, client, buildSettings)
  230. if buildOutput.Error != nil {
  231. err := fmt.Errorf("error building app: %w", buildOutput.Error)
  232. reportBuildFailureInput.buildLogs = buildOutput.Logs
  233. reportBuildFailureInput.buildError = buildOutput.Error
  234. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  235. return err
  236. }
  237. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", buildSettings.ImageTag) // nolint:errcheck,gosec
  238. buildMetadata := make(map[string]interface{})
  239. buildMetadata["end_time"] = time.Now().UTC()
  240. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_Build, eventID, types.PorterAppEventStatus_Success, buildMetadata)
  241. applyInput = api.ApplyPorterAppInput{
  242. ProjectID: cliConf.Project,
  243. ClusterID: cliConf.Cluster,
  244. AppRevisionID: applyResp.AppRevisionId,
  245. ForceBuild: !forceBuild,
  246. }
  247. applyResp, err = client.ApplyPorterApp(ctx, applyInput)
  248. if err != nil {
  249. return fmt.Errorf("apply error post-build: %w", err)
  250. }
  251. }
  252. color.New(color.FgGreen).Printf("Image tag exists in repository\n") // nolint:errcheck,gosec
  253. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_TRACK_PREDEPLOY {
  254. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  255. now := time.Now().UTC()
  256. eventID, _ := createPredeployEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, now, applyResp.AppRevisionId, commitSHA)
  257. metadata := make(map[string]interface{})
  258. eventStatus := types.PorterAppEventStatus_Success
  259. for {
  260. if time.Since(now) > checkPredeployTimeout {
  261. eventStatus = types.PorterAppEventStatus_Failed
  262. metadata["end_time"] = time.Now().UTC()
  263. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_PreDeploy, eventID, eventStatus, metadata)
  264. return errors.New("timed out waiting for predeploy to complete")
  265. }
  266. predeployStatusResp, err := client.PredeployStatus(ctx, cliConf.Project, cliConf.Cluster, appName, applyResp.AppRevisionId)
  267. if err != nil {
  268. eventStatus = types.PorterAppEventStatus_Failed
  269. metadata["end_time"] = time.Now().UTC()
  270. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_PreDeploy, eventID, eventStatus, metadata)
  271. return fmt.Errorf("error calling predeploy status endpoint: %w", err)
  272. }
  273. if predeployStatusResp.Status == porter_app.PredeployStatus_Failed {
  274. eventStatus = types.PorterAppEventStatus_Failed
  275. break
  276. }
  277. if predeployStatusResp.Status == porter_app.PredeployStatus_Successful {
  278. break
  279. }
  280. time.Sleep(checkPredeployFrequency)
  281. }
  282. metadata["end_time"] = time.Now().UTC()
  283. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_PreDeploy, eventID, eventStatus, metadata)
  284. applyInput = api.ApplyPorterAppInput{
  285. ProjectID: cliConf.Project,
  286. ClusterID: cliConf.Cluster,
  287. AppRevisionID: applyResp.AppRevisionId,
  288. ForceBuild: !forceBuild,
  289. }
  290. applyResp, err = client.ApplyPorterApp(ctx, applyInput)
  291. if err != nil {
  292. return fmt.Errorf("apply error post-predeploy: %w", err)
  293. }
  294. }
  295. if applyResp.CLIAction != porterv1.EnumCLIAction_ENUM_CLI_ACTION_NONE {
  296. return fmt.Errorf("unexpected CLI action: %s", applyResp.CLIAction)
  297. }
  298. _, _ = client.ReportRevisionStatus(ctx, api.ReportRevisionStatusInput{
  299. ProjectID: cliConf.Project,
  300. ClusterID: cliConf.Cluster,
  301. AppName: appName,
  302. AppRevisionID: applyResp.AppRevisionId,
  303. PRNumber: prNumber,
  304. CommitSHA: commitSHA,
  305. })
  306. color.New(color.FgGreen).Printf("Successfully applied new revision %s for app %s\n", applyResp.AppRevisionId, appName) // nolint:errcheck,gosec
  307. if inp.WaitForSuccessfulDeployment {
  308. return waitForAppRevisionStatus(ctx, waitForAppRevisionStatusInput{
  309. ProjectID: cliConf.Project,
  310. ClusterID: cliConf.Cluster,
  311. AppName: appName,
  312. RevisionID: applyResp.AppRevisionId,
  313. Client: client,
  314. })
  315. }
  316. return nil
  317. }
  318. func commitSHAFromEnv() string {
  319. var commitSHA string
  320. if os.Getenv("PORTER_COMMIT_SHA") != "" {
  321. commitSHA = os.Getenv("PORTER_COMMIT_SHA")
  322. } else if os.Getenv("GITHUB_SHA") != "" {
  323. commitSHA = os.Getenv("GITHUB_SHA")
  324. } else if commit, err := git.LastCommit(); err == nil && commit != nil {
  325. commitSHA = commit.Sha
  326. }
  327. return commitSHA
  328. }
  329. // checkPredeployTimeout is the maximum amount of time the CLI will wait for a predeploy to complete before calling apply again
  330. const checkPredeployTimeout = 60 * time.Minute
  331. // checkPredeployFrequency is the frequency at which the CLI will check the status of a predeploy
  332. const checkPredeployFrequency = 10 * time.Second
  333. func appNameFromB64AppProto(base64AppProto string) (string, error) {
  334. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  335. if err != nil {
  336. return "", fmt.Errorf("unable to decode base64 app for revision: %w", err)
  337. }
  338. app := &porterv1.PorterApp{}
  339. err = helpers.UnmarshalContractObject(decoded, app)
  340. if err != nil {
  341. return "", fmt.Errorf("unable to unmarshal app for revision: %w", err)
  342. }
  343. if app.Name == "" {
  344. return "", fmt.Errorf("app does not contain name")
  345. }
  346. return app.Name, nil
  347. }
  348. func createPorterAppDbEntryInputFromProtoAndEnv(base64AppProto string) (api.CreatePorterAppDBEntryInput, error) {
  349. var input api.CreatePorterAppDBEntryInput
  350. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  351. if err != nil {
  352. return input, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  353. }
  354. app := &porterv1.PorterApp{}
  355. err = helpers.UnmarshalContractObject(decoded, app)
  356. if err != nil {
  357. return input, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  358. }
  359. if app.Name == "" {
  360. return input, fmt.Errorf("app does not contain name")
  361. }
  362. input.AppName = app.Name
  363. if app.Build != nil {
  364. if os.Getenv("GITHUB_REPOSITORY_ID") == "" {
  365. input.Local = true
  366. return input, nil
  367. }
  368. gitRepoId, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  369. if err != nil {
  370. return input, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  371. }
  372. input.GitRepoID = uint(gitRepoId)
  373. input.GitRepoName = os.Getenv("GITHUB_REPOSITORY")
  374. input.GitBranch = os.Getenv("GITHUB_REF_NAME")
  375. input.PorterYamlPath = "porter.yaml"
  376. return input, nil
  377. }
  378. if app.Image != nil {
  379. input.ImageRepository = app.Image.Repository
  380. input.ImageTag = app.Image.Tag
  381. return input, nil
  382. }
  383. return input, nil
  384. }
  385. func buildSettingsFromBase64AppProto(base64AppProto string) (buildInput, error) {
  386. var buildSettings buildInput
  387. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  388. if err != nil {
  389. return buildSettings, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  390. }
  391. app := &porterv1.PorterApp{}
  392. err = helpers.UnmarshalContractObject(decoded, app)
  393. if err != nil {
  394. return buildSettings, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  395. }
  396. if app.Name == "" {
  397. return buildSettings, fmt.Errorf("app does not contain name")
  398. }
  399. if app.Build == nil {
  400. return buildSettings, fmt.Errorf("app does not contain build settings")
  401. }
  402. if app.Image == nil {
  403. return buildSettings, fmt.Errorf("app does not contain image settings")
  404. }
  405. return buildInput{
  406. AppName: app.Name,
  407. BuildContext: app.Build.Context,
  408. Dockerfile: app.Build.Dockerfile,
  409. BuildMethod: app.Build.Method,
  410. Builder: app.Build.Builder,
  411. BuildPacks: app.Build.Buildpacks,
  412. ImageTag: app.Image.Tag,
  413. RepositoryURL: app.Image.Repository,
  414. }, nil
  415. }
  416. func deploymentTargetFromConfig(ctx context.Context, client api.Client, projectID, clusterID uint, previewApply bool) (string, error) {
  417. var deploymentTargetID string
  418. if os.Getenv("PORTER_DEPLOYMENT_TARGET_ID") != "" {
  419. deploymentTargetID = os.Getenv("PORTER_DEPLOYMENT_TARGET_ID")
  420. }
  421. if deploymentTargetID == "" {
  422. targetResp, err := client.DefaultDeploymentTarget(ctx, projectID, clusterID)
  423. if err != nil {
  424. return deploymentTargetID, fmt.Errorf("error calling default deployment target endpoint: %w", err)
  425. }
  426. deploymentTargetID = targetResp.DeploymentTargetID
  427. }
  428. if previewApply {
  429. var branchName string
  430. // branch name is set to different values in the GH env, depending on whether or not the workflow is triggered by a PR
  431. // issue is being tracked here: https://github.com/github/docs/issues/15319
  432. if os.Getenv("GITHUB_HEAD_REF") != "" {
  433. branchName = os.Getenv("GITHUB_HEAD_REF")
  434. } else if os.Getenv("GITHUB_REF_NAME") != "" {
  435. branchName = os.Getenv("GITHUB_REF_NAME")
  436. } else if branch, err := git.CurrentBranch(); err == nil {
  437. branchName = branch
  438. }
  439. if branchName == "" {
  440. return deploymentTargetID, errors.New("branch name is empty. Please run apply in a git repository with access to the git CLI")
  441. }
  442. targetResp, err := client.CreateDeploymentTarget(ctx, projectID, clusterID, branchName, true)
  443. if err != nil {
  444. return deploymentTargetID, fmt.Errorf("error calling create deployment target endpoint: %w", err)
  445. }
  446. deploymentTargetID = targetResp.DeploymentTargetID
  447. }
  448. if deploymentTargetID == "" {
  449. return deploymentTargetID, errors.New("deployment target id is empty")
  450. }
  451. return deploymentTargetID, nil
  452. }
  453. func imageTagFromBase64AppProto(base64AppProto string) (string, error) {
  454. var image string
  455. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  456. if err != nil {
  457. return image, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  458. }
  459. app := &porterv1.PorterApp{}
  460. err = helpers.UnmarshalContractObject(decoded, app)
  461. if err != nil {
  462. return image, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  463. }
  464. if app.Image == nil {
  465. return image, fmt.Errorf("app does not contain image settings")
  466. }
  467. if app.Image.Tag == "" {
  468. return image, fmt.Errorf("app does not contain image tag")
  469. }
  470. return app.Image.Tag, nil
  471. }
  472. func mergeEnvVariables(currentEnv, previousEnv map[string]string) map[string]string {
  473. env := make(map[string]string)
  474. for k, v := range previousEnv {
  475. env[k] = v
  476. }
  477. for k, v := range currentEnv {
  478. env[k] = v
  479. }
  480. return env
  481. }
  482. type reportBuildFailureInput struct {
  483. client api.Client
  484. appName string
  485. cliConf config.CLIConfig
  486. deploymentTargetID string
  487. appRevisionID string
  488. eventID string
  489. buildError error
  490. buildLogs string
  491. commitSHA string
  492. prNumber int
  493. }
  494. func reportBuildFailure(ctx context.Context, inp reportBuildFailureInput) error {
  495. _, err := inp.client.UpdateRevisionStatus(ctx, inp.cliConf.Project, inp.cliConf.Cluster, inp.appName, inp.appRevisionID, models.AppRevisionStatus_BuildFailed)
  496. if err != nil {
  497. return err
  498. }
  499. buildMetadata := make(map[string]interface{})
  500. buildMetadata["end_time"] = time.Now().UTC()
  501. // the below is a temporary solution until we can report build errors via telemetry from the CLI
  502. errorStringMap := make(map[string]string)
  503. errorStringMap["build-error"] = fmt.Sprintf("%+v", inp.buildError)
  504. b64BuildLogs := base64.StdEncoding.EncodeToString([]byte(inp.buildLogs))
  505. // the key name below must be kept the same so that reportBuildStatus in the CreateOrUpdatePorterAppEvent handler reports logs correctly
  506. errorStringMap["b64-build-logs"] = b64BuildLogs
  507. buildMetadata["errors"] = errorStringMap
  508. err = updateExistingEvent(ctx, inp.client, inp.appName, inp.cliConf.Project, inp.cliConf.Cluster, inp.deploymentTargetID, types.PorterAppEventType_Build, inp.eventID, types.PorterAppEventStatus_Failed, buildMetadata)
  509. if err != nil {
  510. return err
  511. }
  512. _, err = inp.client.ReportRevisionStatus(ctx, api.ReportRevisionStatusInput{
  513. ProjectID: inp.cliConf.Project,
  514. ClusterID: inp.cliConf.Cluster,
  515. AppName: inp.appName,
  516. AppRevisionID: inp.appRevisionID,
  517. PRNumber: inp.prNumber,
  518. CommitSHA: inp.commitSHA,
  519. })
  520. if err != nil {
  521. return err
  522. }
  523. return nil
  524. }