apply.go 21 KB

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