apply.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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, api.CurrentAppRevisionInput{
  193. ProjectID: cliConf.Project,
  194. ClusterID: cliConf.Cluster,
  195. AppName: appName,
  196. DeploymentTargetName: "",
  197. DeploymentTargetID: deploymentTargetID,
  198. })
  199. if err != nil {
  200. err := fmt.Errorf("error getting current app revision: %w", err)
  201. reportBuildFailureInput.buildError = err
  202. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  203. return err
  204. }
  205. if currentAppRevisionResp == nil {
  206. err := errors.New("current app revision is nil")
  207. reportBuildFailureInput.buildError = err
  208. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  209. return err
  210. }
  211. appRevision := currentAppRevisionResp.AppRevision
  212. if appRevision.B64AppProto == "" {
  213. err := errors.New("current app revision b64 app proto is empty")
  214. reportBuildFailureInput.buildError = err
  215. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  216. return err
  217. }
  218. currentImageTag, err := imageTagFromBase64AppProto(appRevision.B64AppProto)
  219. if err != nil {
  220. err := fmt.Errorf("error getting image tag from current app revision: %w", err)
  221. reportBuildFailureInput.buildError = err
  222. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  223. return err
  224. }
  225. buildSettings.CurrentImageTag = currentImageTag
  226. buildSettings.ProjectID = cliConf.Project
  227. buildEnv, err := client.GetBuildEnv(ctx, cliConf.Project, cliConf.Cluster, appName, appRevision.ID)
  228. if err != nil {
  229. err := fmt.Errorf("error getting build env: %w", err)
  230. reportBuildFailureInput.buildError = err
  231. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  232. return err
  233. }
  234. buildSettings.Env = buildEnv.BuildEnvVariables
  235. buildOutput := build(ctx, client, buildSettings)
  236. if buildOutput.Error != nil {
  237. err := fmt.Errorf("error building app: %w", buildOutput.Error)
  238. reportBuildFailureInput.buildLogs = buildOutput.Logs
  239. reportBuildFailureInput.buildError = buildOutput.Error
  240. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  241. return err
  242. }
  243. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", buildSettings.ImageTag) // nolint:errcheck,gosec
  244. buildMetadata := make(map[string]interface{})
  245. buildMetadata["end_time"] = time.Now().UTC()
  246. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_Build, eventID, types.PorterAppEventStatus_Success, buildMetadata)
  247. applyInput = api.ApplyPorterAppInput{
  248. ProjectID: cliConf.Project,
  249. ClusterID: cliConf.Cluster,
  250. AppRevisionID: applyResp.AppRevisionId,
  251. ForceBuild: !forceBuild,
  252. }
  253. applyResp, err = client.ApplyPorterApp(ctx, applyInput)
  254. if err != nil {
  255. return fmt.Errorf("apply error post-build: %w", err)
  256. }
  257. }
  258. color.New(color.FgGreen).Printf("Image tag exists in repository\n") // nolint:errcheck,gosec
  259. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_TRACK_PREDEPLOY {
  260. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  261. now := time.Now().UTC()
  262. eventID, _ := createPredeployEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, now, applyResp.AppRevisionId, commitSHA)
  263. metadata := make(map[string]interface{})
  264. eventStatus := types.PorterAppEventStatus_Success
  265. for {
  266. if time.Since(now) > checkPredeployTimeout {
  267. eventStatus = types.PorterAppEventStatus_Failed
  268. metadata["end_time"] = time.Now().UTC()
  269. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_PreDeploy, eventID, eventStatus, metadata)
  270. return errors.New("timed out waiting for predeploy to complete")
  271. }
  272. predeployStatusResp, err := client.PredeployStatus(ctx, cliConf.Project, cliConf.Cluster, appName, applyResp.AppRevisionId)
  273. if err != nil {
  274. eventStatus = types.PorterAppEventStatus_Failed
  275. metadata["end_time"] = time.Now().UTC()
  276. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_PreDeploy, eventID, eventStatus, metadata)
  277. return fmt.Errorf("error calling predeploy status endpoint: %w", err)
  278. }
  279. if predeployStatusResp.Status == porter_app.PredeployStatus_Failed {
  280. eventStatus = types.PorterAppEventStatus_Failed
  281. break
  282. }
  283. if predeployStatusResp.Status == porter_app.PredeployStatus_Successful {
  284. break
  285. }
  286. time.Sleep(checkPredeployFrequency)
  287. }
  288. metadata["end_time"] = time.Now().UTC()
  289. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_PreDeploy, eventID, eventStatus, metadata)
  290. applyInput = api.ApplyPorterAppInput{
  291. ProjectID: cliConf.Project,
  292. ClusterID: cliConf.Cluster,
  293. AppRevisionID: applyResp.AppRevisionId,
  294. ForceBuild: !forceBuild,
  295. }
  296. applyResp, err = client.ApplyPorterApp(ctx, applyInput)
  297. if err != nil {
  298. return fmt.Errorf("apply error post-predeploy: %w", err)
  299. }
  300. }
  301. if applyResp.CLIAction != porterv1.EnumCLIAction_ENUM_CLI_ACTION_NONE {
  302. return fmt.Errorf("unexpected CLI action: %s", applyResp.CLIAction)
  303. }
  304. _, _ = client.ReportRevisionStatus(ctx, api.ReportRevisionStatusInput{
  305. ProjectID: cliConf.Project,
  306. ClusterID: cliConf.Cluster,
  307. AppName: appName,
  308. AppRevisionID: applyResp.AppRevisionId,
  309. PRNumber: prNumber,
  310. CommitSHA: commitSHA,
  311. })
  312. color.New(color.FgGreen).Printf("Successfully applied new revision %s for app %s\n", applyResp.AppRevisionId, appName) // nolint:errcheck,gosec
  313. if inp.WaitForSuccessfulDeployment {
  314. return waitForAppRevisionStatus(ctx, waitForAppRevisionStatusInput{
  315. ProjectID: cliConf.Project,
  316. ClusterID: cliConf.Cluster,
  317. AppName: appName,
  318. RevisionID: applyResp.AppRevisionId,
  319. Client: client,
  320. })
  321. }
  322. return nil
  323. }
  324. func commitSHAFromEnv() string {
  325. var commitSHA string
  326. if os.Getenv("PORTER_COMMIT_SHA") != "" {
  327. commitSHA = os.Getenv("PORTER_COMMIT_SHA")
  328. } else if os.Getenv("GITHUB_SHA") != "" {
  329. commitSHA = os.Getenv("GITHUB_SHA")
  330. } else if commit, err := git.LastCommit(); err == nil && commit != nil {
  331. commitSHA = commit.Sha
  332. }
  333. return commitSHA
  334. }
  335. // checkPredeployTimeout is the maximum amount of time the CLI will wait for a predeploy to complete before calling apply again
  336. const checkPredeployTimeout = 60 * time.Minute
  337. // checkPredeployFrequency is the frequency at which the CLI will check the status of a predeploy
  338. const checkPredeployFrequency = 10 * time.Second
  339. func appNameFromB64AppProto(base64AppProto string) (string, error) {
  340. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  341. if err != nil {
  342. return "", fmt.Errorf("unable to decode base64 app for revision: %w", err)
  343. }
  344. app := &porterv1.PorterApp{}
  345. err = helpers.UnmarshalContractObject(decoded, app)
  346. if err != nil {
  347. return "", fmt.Errorf("unable to unmarshal app for revision: %w", err)
  348. }
  349. if app.Name == "" {
  350. return "", fmt.Errorf("app does not contain name")
  351. }
  352. return app.Name, nil
  353. }
  354. func createPorterAppDbEntryInputFromProtoAndEnv(base64AppProto string) (api.CreatePorterAppDBEntryInput, error) {
  355. var input api.CreatePorterAppDBEntryInput
  356. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  357. if err != nil {
  358. return input, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  359. }
  360. app := &porterv1.PorterApp{}
  361. err = helpers.UnmarshalContractObject(decoded, app)
  362. if err != nil {
  363. return input, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  364. }
  365. if app.Name == "" {
  366. return input, fmt.Errorf("app does not contain name")
  367. }
  368. input.AppName = app.Name
  369. if app.Build != nil {
  370. if os.Getenv("GITHUB_REPOSITORY_ID") == "" {
  371. input.Local = true
  372. return input, nil
  373. }
  374. gitRepoId, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  375. if err != nil {
  376. return input, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  377. }
  378. input.GitRepoID = uint(gitRepoId)
  379. input.GitRepoName = os.Getenv("GITHUB_REPOSITORY")
  380. input.GitBranch = os.Getenv("GITHUB_REF_NAME")
  381. input.PorterYamlPath = "porter.yaml"
  382. return input, nil
  383. }
  384. if app.Image != nil {
  385. input.ImageRepository = app.Image.Repository
  386. input.ImageTag = app.Image.Tag
  387. return input, nil
  388. }
  389. return input, nil
  390. }
  391. func buildSettingsFromBase64AppProto(base64AppProto string) (buildInput, error) {
  392. var buildSettings buildInput
  393. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  394. if err != nil {
  395. return buildSettings, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  396. }
  397. app := &porterv1.PorterApp{}
  398. err = helpers.UnmarshalContractObject(decoded, app)
  399. if err != nil {
  400. return buildSettings, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  401. }
  402. if app.Name == "" {
  403. return buildSettings, fmt.Errorf("app does not contain name")
  404. }
  405. if app.Build == nil {
  406. return buildSettings, fmt.Errorf("app does not contain build settings")
  407. }
  408. if app.Image == nil {
  409. return buildSettings, fmt.Errorf("app does not contain image settings")
  410. }
  411. return buildInput{
  412. AppName: app.Name,
  413. BuildContext: app.Build.Context,
  414. Dockerfile: app.Build.Dockerfile,
  415. BuildMethod: app.Build.Method,
  416. Builder: app.Build.Builder,
  417. BuildPacks: app.Build.Buildpacks,
  418. ImageTag: app.Image.Tag,
  419. RepositoryURL: app.Image.Repository,
  420. }, nil
  421. }
  422. func deploymentTargetFromConfig(ctx context.Context, client api.Client, projectID, clusterID uint, previewApply bool) (string, error) {
  423. var deploymentTargetID string
  424. if os.Getenv("PORTER_DEPLOYMENT_TARGET_ID") != "" {
  425. deploymentTargetID = os.Getenv("PORTER_DEPLOYMENT_TARGET_ID")
  426. }
  427. if deploymentTargetID == "" {
  428. targetResp, err := client.DefaultDeploymentTarget(ctx, projectID, clusterID)
  429. if err != nil {
  430. return deploymentTargetID, fmt.Errorf("error calling default deployment target endpoint: %w", err)
  431. }
  432. deploymentTargetID = targetResp.DeploymentTargetID
  433. }
  434. if previewApply {
  435. var branchName string
  436. // branch name is set to different values in the GH env, depending on whether or not the workflow is triggered by a PR
  437. // issue is being tracked here: https://github.com/github/docs/issues/15319
  438. if os.Getenv("GITHUB_HEAD_REF") != "" {
  439. branchName = os.Getenv("GITHUB_HEAD_REF")
  440. } else if os.Getenv("GITHUB_REF_NAME") != "" {
  441. branchName = os.Getenv("GITHUB_REF_NAME")
  442. } else if branch, err := git.CurrentBranch(); err == nil {
  443. branchName = branch
  444. }
  445. if branchName == "" {
  446. return deploymentTargetID, errors.New("branch name is empty. Please run apply in a git repository with access to the git CLI")
  447. }
  448. targetResp, err := client.CreateDeploymentTarget(ctx, projectID, clusterID, branchName, true)
  449. if err != nil {
  450. return deploymentTargetID, fmt.Errorf("error calling create deployment target endpoint: %w", err)
  451. }
  452. deploymentTargetID = targetResp.DeploymentTargetID
  453. }
  454. if deploymentTargetID == "" {
  455. return deploymentTargetID, errors.New("deployment target id is empty")
  456. }
  457. return deploymentTargetID, nil
  458. }
  459. func imageTagFromBase64AppProto(base64AppProto string) (string, error) {
  460. var image string
  461. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  462. if err != nil {
  463. return image, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  464. }
  465. app := &porterv1.PorterApp{}
  466. err = helpers.UnmarshalContractObject(decoded, app)
  467. if err != nil {
  468. return image, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  469. }
  470. if app.Image == nil {
  471. return image, fmt.Errorf("app does not contain image settings")
  472. }
  473. if app.Image.Tag == "" {
  474. return image, fmt.Errorf("app does not contain image tag")
  475. }
  476. return app.Image.Tag, nil
  477. }
  478. func mergeEnvVariables(currentEnv, previousEnv map[string]string) map[string]string {
  479. env := make(map[string]string)
  480. for k, v := range previousEnv {
  481. env[k] = v
  482. }
  483. for k, v := range currentEnv {
  484. env[k] = v
  485. }
  486. return env
  487. }
  488. type reportBuildFailureInput struct {
  489. client api.Client
  490. appName string
  491. cliConf config.CLIConfig
  492. deploymentTargetID string
  493. appRevisionID string
  494. eventID string
  495. buildError error
  496. buildLogs string
  497. commitSHA string
  498. prNumber int
  499. }
  500. func reportBuildFailure(ctx context.Context, inp reportBuildFailureInput) error {
  501. _, err := inp.client.UpdateRevisionStatus(ctx, inp.cliConf.Project, inp.cliConf.Cluster, inp.appName, inp.appRevisionID, models.AppRevisionStatus_BuildFailed)
  502. if err != nil {
  503. return err
  504. }
  505. buildMetadata := make(map[string]interface{})
  506. buildMetadata["end_time"] = time.Now().UTC()
  507. // the below is a temporary solution until we can report build errors via telemetry from the CLI
  508. errorStringMap := make(map[string]string)
  509. errorStringMap["build-error"] = fmt.Sprintf("%+v", inp.buildError)
  510. b64BuildLogs := base64.StdEncoding.EncodeToString([]byte(inp.buildLogs))
  511. // the key name below must be kept the same so that reportBuildStatus in the CreateOrUpdatePorterAppEvent handler reports logs correctly
  512. errorStringMap["b64-build-logs"] = b64BuildLogs
  513. buildMetadata["errors"] = errorStringMap
  514. err = updateExistingEvent(ctx, inp.client, inp.appName, inp.cliConf.Project, inp.cliConf.Cluster, inp.deploymentTargetID, types.PorterAppEventType_Build, inp.eventID, types.PorterAppEventStatus_Failed, buildMetadata)
  515. if err != nil {
  516. return err
  517. }
  518. _, err = inp.client.ReportRevisionStatus(ctx, api.ReportRevisionStatusInput{
  519. ProjectID: inp.cliConf.Project,
  520. ClusterID: inp.cliConf.Cluster,
  521. AppName: inp.appName,
  522. AppRevisionID: inp.appRevisionID,
  523. PRNumber: inp.prNumber,
  524. CommitSHA: inp.commitSHA,
  525. })
  526. if err != nil {
  527. return err
  528. }
  529. return nil
  530. }