apply.go 21 KB

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