apply.go 21 KB

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