apply.go 22 KB

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