apply.go 21 KB

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