finalize_deployment_with_errors.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. package environment
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "github.com/google/go-github/v41/github"
  8. "github.com/porter-dev/porter/api/server/handlers"
  9. "github.com/porter-dev/porter/api/server/shared"
  10. "github.com/porter-dev/porter/api/server/shared/apierrors"
  11. "github.com/porter-dev/porter/api/server/shared/commonutils"
  12. "github.com/porter-dev/porter/api/server/shared/config"
  13. "github.com/porter-dev/porter/api/types"
  14. "github.com/porter-dev/porter/internal/models"
  15. "github.com/porter-dev/porter/internal/models/integrations"
  16. "gorm.io/gorm"
  17. )
  18. type FinalizeDeploymentWithErrorsHandler struct {
  19. handlers.PorterHandlerReadWriter
  20. }
  21. func NewFinalizeDeploymentWithErrorsHandler(
  22. config *config.Config,
  23. decoderValidator shared.RequestDecoderValidator,
  24. writer shared.ResultWriter,
  25. ) *FinalizeDeploymentWithErrorsHandler {
  26. return &FinalizeDeploymentWithErrorsHandler{
  27. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  28. }
  29. }
  30. func (c *FinalizeDeploymentWithErrorsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  31. ga, _ := r.Context().Value(types.GitInstallationScope).(*integrations.GithubAppInstallation)
  32. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  33. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  34. owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
  35. if !ok {
  36. return
  37. }
  38. request := &types.FinalizeDeploymentWithErrorsRequest{}
  39. if ok := c.DecodeAndValidate(w, r, request); !ok {
  40. return
  41. }
  42. if len(request.Errors) == 0 {
  43. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  44. fmt.Errorf("at least one error is required to report"), http.StatusPreconditionFailed,
  45. ))
  46. return
  47. }
  48. // read the environment to get the environment id
  49. env, err := c.Repo().Environment().ReadEnvironment(project.ID, cluster.ID, uint(ga.InstallationID), owner, name)
  50. if err != nil {
  51. if errors.Is(err, gorm.ErrRecordNotFound) {
  52. c.HandleAPIError(w, r, apierrors.NewErrNotFound(fmt.Errorf("no environment found")))
  53. return
  54. }
  55. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  56. return
  57. }
  58. // read the deployment
  59. depl, err := c.Repo().Environment().ReadDeployment(env.ID, request.Namespace)
  60. if err != nil {
  61. if errors.Is(err, gorm.ErrRecordNotFound) {
  62. c.HandleAPIError(w, r, apierrors.NewErrNotFound(fmt.Errorf("no deployment found for environment ID: %d, namespace: %s", env.ID, request.Namespace)))
  63. return
  64. }
  65. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  66. return
  67. }
  68. depl.Status = types.DeploymentStatusFailed
  69. // we do not care of the error in this case because the list deployments endpoint
  70. // talks to the github API to fetch the deployment status correctly
  71. c.Repo().Environment().UpdateDeployment(depl)
  72. client, err := getGithubClientFromEnvironment(c.Config(), env)
  73. if err != nil {
  74. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  75. fmt.Errorf("unable to get github client: %w", err), http.StatusConflict,
  76. ))
  77. return
  78. }
  79. // FIXME: ignore the status of thie API call for now
  80. client.Repositories.CreateDeploymentStatus(
  81. context.Background(), owner, name, depl.GHDeploymentID, &github.DeploymentStatusRequest{
  82. State: github.String("failure"),
  83. Description: github.String("one or more resources failed to build"),
  84. },
  85. )
  86. workflowRun, err := commonutils.GetLatestWorkflowRun(client, depl.RepoOwner, depl.RepoName,
  87. fmt.Sprintf("porter_%s_env.yml", env.Name), depl.PRBranchFrom)
  88. if err != nil {
  89. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  90. return
  91. }
  92. commentBody := fmt.Sprintf(
  93. "## ❌ Porter Preview Environments\n"+
  94. "||Deployment Information|\n"+
  95. "|-|-|\n"+
  96. "| Latest SHA | [`%s`](https://github.com/%s/%s/commit/%s) |\n"+
  97. "| Github Action | %s |\n",
  98. depl.CommitSHA, depl.RepoOwner, depl.RepoName, depl.CommitSHA, workflowRun.GetHTMLURL(),
  99. )
  100. if len(request.SuccessfulResources) > 0 {
  101. commentBody += "#### Successfully deployed resources\n"
  102. for _, res := range request.SuccessfulResources {
  103. commentBody += fmt.Sprintf("- `%s`\n", res)
  104. }
  105. }
  106. commentBody += "#### Failed resources\n"
  107. for res, err := range request.Errors {
  108. commentBody += fmt.Sprintf("<details>\n <summary><code>%s</code></summary>\n\n **Error:** %s\n</details>\n", res, err)
  109. }
  110. _, _, err = client.Issues.CreateComment(
  111. context.Background(),
  112. env.GitRepoOwner,
  113. env.GitRepoName,
  114. int(depl.PullRequestID),
  115. &github.IssueComment{
  116. Body: github.String(commentBody),
  117. },
  118. )
  119. if err != nil {
  120. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  121. fmt.Errorf("error creating github comment: %w", err), http.StatusConflict,
  122. ))
  123. return
  124. }
  125. c.WriteResult(w, r, depl.ToDeploymentType())
  126. }