apply.go 21 KB

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