apply.go 20 KB

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