apply.go 22 KB

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