apply.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. package v2
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "time"
  11. "github.com/porter-dev/porter/api/server/handlers/porter_app"
  12. "github.com/porter-dev/porter/api/types"
  13. "github.com/porter-dev/porter/internal/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. err = client.CreatePorterAppDBEntry(ctx, cliConf.Project, cliConf.Cluster, createPorterAppDBEntryInp)
  101. if err != nil {
  102. if err.Error() == porter_app.ErrMissingSourceType.Error() {
  103. return fmt.Errorf("cannot find existing Porter app with name %s and no build or image settings were specified in porter.yaml", appName)
  104. }
  105. return fmt.Errorf("unable to create porter app from yaml: %w", err)
  106. }
  107. color.New(color.FgGreen).Printf("Successfully parsed Porter YAML: applying app \"%s\"\n", appName) // nolint:errcheck,gosec
  108. }
  109. // b64AppOverrides is the base64-encoded app proto with preview environment specific overrides and env groups
  110. var b64AppOverrides string
  111. if inp.PreviewApply && overrides != nil {
  112. b64AppOverrides = overrides.B64AppProto
  113. previewEnvVariables := overrides.EnvVariables
  114. envVariables = mergeEnvVariables(envVariables, previewEnvVariables)
  115. }
  116. if appName == "" {
  117. 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.")
  118. }
  119. commitSHA := commitSHAFromEnv()
  120. validateResp, err := client.ValidatePorterApp(ctx, api.ValidatePorterAppInput{
  121. ProjectID: cliConf.Project,
  122. ClusterID: cliConf.Cluster,
  123. AppName: appName,
  124. Base64AppProto: b64AppProto,
  125. Base64AppOverrides: b64AppOverrides,
  126. DeploymentTarget: deploymentTargetID,
  127. CommitSHA: commitSHA,
  128. })
  129. if err != nil {
  130. return fmt.Errorf("error calling validate endpoint: %w", err)
  131. }
  132. if validateResp.ValidatedBase64AppProto == "" {
  133. return errors.New("validated b64 app proto is empty")
  134. }
  135. base64AppProto := validateResp.ValidatedBase64AppProto
  136. applyInput := api.ApplyPorterAppInput{
  137. ProjectID: cliConf.Project,
  138. ClusterID: cliConf.Cluster,
  139. Base64AppProto: base64AppProto,
  140. DeploymentTarget: deploymentTargetID,
  141. ForceBuild: forceBuild,
  142. Variables: envVariables,
  143. Secrets: envSecrets,
  144. }
  145. applyResp, err := client.ApplyPorterApp(ctx, applyInput)
  146. if err != nil {
  147. return fmt.Errorf("error calling apply endpoint: %w", err)
  148. }
  149. if applyResp.AppRevisionId == "" {
  150. return errors.New("app revision id is empty")
  151. }
  152. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_BUILD {
  153. color.New(color.FgGreen).Printf("Building new image...\n") // nolint:errcheck,gosec
  154. eventID, _ := createBuildEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, commitSHA)
  155. reportBuildFailureInput := reportBuildFailureInput{
  156. client: client,
  157. appName: appName,
  158. cliConf: cliConf,
  159. deploymentTargetID: deploymentTargetID,
  160. appRevisionID: applyResp.AppRevisionId,
  161. eventID: eventID,
  162. commitSHA: commitSHA,
  163. prNumber: prNumber,
  164. }
  165. if commitSHA == "" {
  166. 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.")
  167. reportBuildFailureInput.buildError = err
  168. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  169. return err
  170. }
  171. buildSettings, err := buildSettingsFromBase64AppProto(base64AppProto)
  172. if err != nil {
  173. err := fmt.Errorf("error getting build settings from base64 app proto: %w", err)
  174. reportBuildFailureInput.buildError = err
  175. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  176. return err
  177. }
  178. currentAppRevisionResp, err := client.CurrentAppRevision(ctx, cliConf.Project, cliConf.Cluster, appName, deploymentTargetID)
  179. if err != nil {
  180. err := fmt.Errorf("error getting current app revision: %w", err)
  181. reportBuildFailureInput.buildError = err
  182. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  183. return err
  184. }
  185. if currentAppRevisionResp == nil {
  186. err := errors.New("current app revision is nil")
  187. reportBuildFailureInput.buildError = err
  188. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  189. return err
  190. }
  191. appRevision := currentAppRevisionResp.AppRevision
  192. if appRevision.B64AppProto == "" {
  193. err := errors.New("current app revision b64 app proto is empty")
  194. reportBuildFailureInput.buildError = err
  195. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  196. return err
  197. }
  198. currentImageTag, err := imageTagFromBase64AppProto(appRevision.B64AppProto)
  199. if err != nil {
  200. err := fmt.Errorf("error getting image tag from current app revision: %w", err)
  201. reportBuildFailureInput.buildError = err
  202. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  203. return err
  204. }
  205. buildSettings.CurrentImageTag = currentImageTag
  206. buildSettings.ProjectID = cliConf.Project
  207. buildEnv, err := client.GetBuildEnv(ctx, cliConf.Project, cliConf.Cluster, appName, appRevision.ID)
  208. if err != nil {
  209. err := fmt.Errorf("error getting build env: %w", err)
  210. reportBuildFailureInput.buildError = err
  211. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  212. return err
  213. }
  214. buildSettings.Env = buildEnv.BuildEnvVariables
  215. buildOutput := build(ctx, client, buildSettings)
  216. if buildOutput.Error != nil {
  217. err := fmt.Errorf("error building app: %w", buildOutput.Error)
  218. reportBuildFailureInput.buildLogs = buildOutput.Logs
  219. reportBuildFailureInput.buildError = buildOutput.Error
  220. _ = reportBuildFailure(ctx, reportBuildFailureInput)
  221. return err
  222. }
  223. color.New(color.FgGreen).Printf("Successfully built image (tag: %s)\n", buildSettings.ImageTag) // nolint:errcheck,gosec
  224. buildMetadata := make(map[string]interface{})
  225. buildMetadata["end_time"] = time.Now().UTC()
  226. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_Build, eventID, types.PorterAppEventStatus_Success, buildMetadata)
  227. applyInput = api.ApplyPorterAppInput{
  228. ProjectID: cliConf.Project,
  229. ClusterID: cliConf.Cluster,
  230. AppRevisionID: applyResp.AppRevisionId,
  231. ForceBuild: !forceBuild,
  232. }
  233. applyResp, err = client.ApplyPorterApp(ctx, applyInput)
  234. if err != nil {
  235. return fmt.Errorf("apply error post-build: %w", err)
  236. }
  237. }
  238. color.New(color.FgGreen).Printf("Image tag exists in repository\n") // nolint:errcheck,gosec
  239. if applyResp.CLIAction == porterv1.EnumCLIAction_ENUM_CLI_ACTION_TRACK_PREDEPLOY {
  240. color.New(color.FgGreen).Printf("Waiting for predeploy to complete...\n") // nolint:errcheck,gosec
  241. now := time.Now().UTC()
  242. eventID, _ := createPredeployEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, now, applyResp.AppRevisionId, commitSHA)
  243. metadata := make(map[string]interface{})
  244. eventStatus := types.PorterAppEventStatus_Success
  245. for {
  246. if time.Since(now) > checkPredeployTimeout {
  247. eventStatus = types.PorterAppEventStatus_Failed
  248. metadata["end_time"] = time.Now().UTC()
  249. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_PreDeploy, eventID, eventStatus, metadata)
  250. return errors.New("timed out waiting for predeploy to complete")
  251. }
  252. predeployStatusResp, err := client.PredeployStatus(ctx, cliConf.Project, cliConf.Cluster, appName, applyResp.AppRevisionId)
  253. if err != nil {
  254. eventStatus = types.PorterAppEventStatus_Failed
  255. metadata["end_time"] = time.Now().UTC()
  256. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_PreDeploy, eventID, eventStatus, metadata)
  257. return fmt.Errorf("error calling predeploy status endpoint: %w", err)
  258. }
  259. if predeployStatusResp.Status == porter_app.PredeployStatus_Failed {
  260. eventStatus = types.PorterAppEventStatus_Failed
  261. break
  262. }
  263. if predeployStatusResp.Status == porter_app.PredeployStatus_Successful {
  264. break
  265. }
  266. time.Sleep(checkPredeployFrequency)
  267. }
  268. metadata["end_time"] = time.Now().UTC()
  269. _ = updateExistingEvent(ctx, client, appName, cliConf.Project, cliConf.Cluster, deploymentTargetID, types.PorterAppEventType_PreDeploy, eventID, eventStatus, metadata)
  270. applyInput = api.ApplyPorterAppInput{
  271. ProjectID: cliConf.Project,
  272. ClusterID: cliConf.Cluster,
  273. AppRevisionID: applyResp.AppRevisionId,
  274. ForceBuild: !forceBuild,
  275. }
  276. applyResp, err = client.ApplyPorterApp(ctx, applyInput)
  277. if err != nil {
  278. return fmt.Errorf("apply error post-predeploy: %w", err)
  279. }
  280. }
  281. if applyResp.CLIAction != porterv1.EnumCLIAction_ENUM_CLI_ACTION_NONE {
  282. return fmt.Errorf("unexpected CLI action: %s", applyResp.CLIAction)
  283. }
  284. _, _ = client.ReportRevisionStatus(ctx, api.ReportRevisionStatusInput{
  285. ProjectID: cliConf.Project,
  286. ClusterID: cliConf.Cluster,
  287. AppName: appName,
  288. AppRevisionID: applyResp.AppRevisionId,
  289. PRNumber: prNumber,
  290. CommitSHA: commitSHA,
  291. })
  292. color.New(color.FgGreen).Printf("Successfully applied new revision %s for app %s\n", applyResp.AppRevisionId, appName) // nolint:errcheck,gosec
  293. return nil
  294. }
  295. func commitSHAFromEnv() string {
  296. var commitSHA string
  297. if os.Getenv("PORTER_COMMIT_SHA") != "" {
  298. commitSHA = os.Getenv("PORTER_COMMIT_SHA")
  299. } else if os.Getenv("GITHUB_SHA") != "" {
  300. commitSHA = os.Getenv("GITHUB_SHA")
  301. } else if commit, err := git.LastCommit(); err == nil && commit != nil {
  302. commitSHA = commit.Sha
  303. }
  304. return commitSHA
  305. }
  306. // checkPredeployTimeout is the maximum amount of time the CLI will wait for a predeploy to complete before calling apply again
  307. const checkPredeployTimeout = 60 * time.Minute
  308. // checkPredeployFrequency is the frequency at which the CLI will check the status of a predeploy
  309. const checkPredeployFrequency = 10 * time.Second
  310. func appNameFromB64AppProto(base64AppProto string) (string, error) {
  311. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  312. if err != nil {
  313. return "", fmt.Errorf("unable to decode base64 app for revision: %w", err)
  314. }
  315. app := &porterv1.PorterApp{}
  316. err = helpers.UnmarshalContractObject(decoded, app)
  317. if err != nil {
  318. return "", fmt.Errorf("unable to unmarshal app for revision: %w", err)
  319. }
  320. if app.Name == "" {
  321. return "", fmt.Errorf("app does not contain name")
  322. }
  323. return app.Name, nil
  324. }
  325. func createPorterAppDbEntryInputFromProtoAndEnv(base64AppProto string) (api.CreatePorterAppDBEntryInput, error) {
  326. var input api.CreatePorterAppDBEntryInput
  327. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  328. if err != nil {
  329. return input, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  330. }
  331. app := &porterv1.PorterApp{}
  332. err = helpers.UnmarshalContractObject(decoded, app)
  333. if err != nil {
  334. return input, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  335. }
  336. if app.Name == "" {
  337. return input, fmt.Errorf("app does not contain name")
  338. }
  339. input.AppName = app.Name
  340. if app.Build != nil {
  341. if os.Getenv("GITHUB_REPOSITORY_ID") == "" {
  342. input.Local = true
  343. return input, nil
  344. }
  345. gitRepoId, err := strconv.Atoi(os.Getenv("GITHUB_REPOSITORY_ID"))
  346. if err != nil {
  347. return input, fmt.Errorf("unable to parse GITHUB_REPOSITORY_ID to int: %w", err)
  348. }
  349. input.GitRepoID = uint(gitRepoId)
  350. input.GitRepoName = os.Getenv("GITHUB_REPOSITORY")
  351. input.GitBranch = os.Getenv("GITHUB_REF_NAME")
  352. input.PorterYamlPath = "porter.yaml"
  353. return input, nil
  354. }
  355. if app.Image != nil {
  356. input.ImageRepository = app.Image.Repository
  357. input.ImageTag = app.Image.Tag
  358. return input, nil
  359. }
  360. return input, nil
  361. }
  362. func buildSettingsFromBase64AppProto(base64AppProto string) (buildInput, error) {
  363. var buildSettings buildInput
  364. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  365. if err != nil {
  366. return buildSettings, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  367. }
  368. app := &porterv1.PorterApp{}
  369. err = helpers.UnmarshalContractObject(decoded, app)
  370. if err != nil {
  371. return buildSettings, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  372. }
  373. if app.Name == "" {
  374. return buildSettings, fmt.Errorf("app does not contain name")
  375. }
  376. if app.Build == nil {
  377. return buildSettings, fmt.Errorf("app does not contain build settings")
  378. }
  379. if app.Image == nil {
  380. return buildSettings, fmt.Errorf("app does not contain image settings")
  381. }
  382. return buildInput{
  383. AppName: app.Name,
  384. BuildContext: app.Build.Context,
  385. Dockerfile: app.Build.Dockerfile,
  386. BuildMethod: app.Build.Method,
  387. Builder: app.Build.Builder,
  388. BuildPacks: app.Build.Buildpacks,
  389. ImageTag: app.Image.Tag,
  390. RepositoryURL: app.Image.Repository,
  391. }, nil
  392. }
  393. func deploymentTargetFromConfig(ctx context.Context, client api.Client, projectID, clusterID uint, previewApply bool) (string, error) {
  394. var deploymentTargetID string
  395. targetResp, err := client.DefaultDeploymentTarget(ctx, projectID, clusterID)
  396. if err != nil {
  397. return deploymentTargetID, fmt.Errorf("error calling default deployment target endpoint: %w", err)
  398. }
  399. deploymentTargetID = targetResp.DeploymentTargetID
  400. if previewApply {
  401. var branchName string
  402. // branch name is set to different values in the GH env, depending on whether or not the workflow is triggered by a PR
  403. // issue is being tracked here: https://github.com/github/docs/issues/15319
  404. if os.Getenv("GITHUB_HEAD_REF") != "" {
  405. branchName = os.Getenv("GITHUB_HEAD_REF")
  406. } else if os.Getenv("GITHUB_REF_NAME") != "" {
  407. branchName = os.Getenv("GITHUB_REF_NAME")
  408. } else if branch, err := git.CurrentBranch(); err == nil {
  409. branchName = branch
  410. }
  411. if branchName == "" {
  412. return deploymentTargetID, errors.New("Branch name is empty. Please run apply in a git repository with access to the git CLI.")
  413. }
  414. targetResp, err := client.CreateDeploymentTarget(ctx, projectID, clusterID, branchName, true)
  415. if err != nil {
  416. return deploymentTargetID, fmt.Errorf("error calling create deployment target endpoint: %w", err)
  417. }
  418. deploymentTargetID = targetResp.DeploymentTargetID
  419. }
  420. if deploymentTargetID == "" {
  421. return deploymentTargetID, errors.New("deployment target id is empty")
  422. }
  423. return deploymentTargetID, nil
  424. }
  425. func imageTagFromBase64AppProto(base64AppProto string) (string, error) {
  426. var image string
  427. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  428. if err != nil {
  429. return image, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  430. }
  431. app := &porterv1.PorterApp{}
  432. err = helpers.UnmarshalContractObject(decoded, app)
  433. if err != nil {
  434. return image, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  435. }
  436. if app.Image == nil {
  437. return image, fmt.Errorf("app does not contain image settings")
  438. }
  439. if app.Image.Tag == "" {
  440. return image, fmt.Errorf("app does not contain image tag")
  441. }
  442. return app.Image.Tag, nil
  443. }
  444. func mergeEnvVariables(currentEnv, previousEnv map[string]string) map[string]string {
  445. env := make(map[string]string)
  446. for k, v := range previousEnv {
  447. env[k] = v
  448. }
  449. for k, v := range currentEnv {
  450. env[k] = v
  451. }
  452. return env
  453. }
  454. func updateEnvGroupsInProto(ctx context.Context, base64AppProto string, envGroups []environment_groups.EnvironmentGroup) (string, error) {
  455. var editedB64AppProto string
  456. decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
  457. if err != nil {
  458. return editedB64AppProto, fmt.Errorf("unable to decode base64 app for revision: %w", err)
  459. }
  460. app := &porterv1.PorterApp{}
  461. err = helpers.UnmarshalContractObject(decoded, app)
  462. if err != nil {
  463. return editedB64AppProto, fmt.Errorf("unable to unmarshal app for revision: %w", err)
  464. }
  465. egs := make([]*porterv1.EnvGroup, 0)
  466. for _, envGroup := range envGroups {
  467. egs = append(egs, &porterv1.EnvGroup{
  468. Name: envGroup.Name,
  469. Version: int64(envGroup.Version),
  470. })
  471. }
  472. app.EnvGroups = egs
  473. marshalled, err := helpers.MarshalContractObject(ctx, app)
  474. if err != nil {
  475. return editedB64AppProto, fmt.Errorf("unable to marshal app back to json: %w", err)
  476. }
  477. editedB64AppProto = base64.StdEncoding.EncodeToString(marshalled)
  478. return editedB64AppProto, nil
  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. }