apply.go 21 KB

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