finalize_deployment_with_errors.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package environment
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. "github.com/google/go-github/v41/github"
  9. "github.com/porter-dev/porter/api/server/handlers"
  10. "github.com/porter-dev/porter/api/server/shared"
  11. "github.com/porter-dev/porter/api/server/shared/apierrors"
  12. "github.com/porter-dev/porter/api/server/shared/commonutils"
  13. "github.com/porter-dev/porter/api/server/shared/config"
  14. "github.com/porter-dev/porter/api/types"
  15. "github.com/porter-dev/porter/internal/models"
  16. "github.com/porter-dev/porter/internal/models/integrations"
  17. "gorm.io/gorm"
  18. )
  19. type FinalizeDeploymentWithErrorsHandler struct {
  20. handlers.PorterHandlerReadWriter
  21. }
  22. func NewFinalizeDeploymentWithErrorsHandler(
  23. config *config.Config,
  24. decoderValidator shared.RequestDecoderValidator,
  25. writer shared.ResultWriter,
  26. ) *FinalizeDeploymentWithErrorsHandler {
  27. return &FinalizeDeploymentWithErrorsHandler{
  28. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  29. }
  30. }
  31. func (c *FinalizeDeploymentWithErrorsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  32. ga, _ := r.Context().Value(types.GitInstallationScope).(*integrations.GithubAppInstallation)
  33. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  34. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  35. owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
  36. if !ok {
  37. return
  38. }
  39. request := &types.FinalizeDeploymentWithErrorsRequest{}
  40. if ok := c.DecodeAndValidate(w, r, request); !ok {
  41. return
  42. }
  43. if request.Namespace == "" && request.PRNumber == 0 {
  44. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  45. fmt.Errorf("either namespace or pr_number must be present in request body"), http.StatusBadRequest,
  46. ))
  47. return
  48. }
  49. if len(request.Errors) == 0 {
  50. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  51. fmt.Errorf("at least one error is required to report"), http.StatusPreconditionFailed,
  52. ))
  53. return
  54. }
  55. var err error
  56. // read the environment to get the environment id
  57. env, err := c.Repo().Environment().ReadEnvironment(project.ID, cluster.ID, uint(ga.InstallationID), owner, name)
  58. if err != nil {
  59. if errors.Is(err, gorm.ErrRecordNotFound) {
  60. c.HandleAPIError(w, r, apierrors.NewErrNotFound(errEnvironmentNotFound))
  61. return
  62. }
  63. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  64. return
  65. }
  66. var depl *models.Deployment
  67. // read the deployment
  68. if request.PRNumber != 0 {
  69. depl, err = c.Repo().Environment().ReadDeploymentByGitDetails(env.ID, owner, name, request.PRNumber)
  70. if err != nil {
  71. if errors.Is(err, gorm.ErrRecordNotFound) {
  72. c.HandleAPIError(w, r, apierrors.NewErrNotFound(errDeploymentNotFound))
  73. return
  74. }
  75. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  76. return
  77. }
  78. } else if request.Namespace != "" {
  79. depl, err = c.Repo().Environment().ReadDeployment(env.ID, request.Namespace)
  80. if err != nil {
  81. if errors.Is(err, gorm.ErrRecordNotFound) {
  82. c.HandleAPIError(w, r, apierrors.NewErrNotFound(errDeploymentNotFound))
  83. return
  84. }
  85. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  86. return
  87. }
  88. }
  89. if depl == nil {
  90. c.HandleAPIError(w, r, apierrors.NewErrNotFound(errDeploymentNotFound))
  91. return
  92. }
  93. client, err := getGithubClientFromEnvironment(c.Config(), env)
  94. if err != nil {
  95. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  96. return
  97. }
  98. depl.Status = types.DeploymentStatusFailed
  99. var lastErrors []string
  100. for resName, errString := range request.Errors {
  101. lastErrors = append(lastErrors, fmt.Sprintf("%s: %s", resName, errString))
  102. }
  103. depl.LastErrors = strings.Join(lastErrors, ",")
  104. // we do not care of the error in this case because the list deployments endpoint
  105. // talks to the github API to fetch the deployment status correctly
  106. c.Repo().Environment().UpdateDeployment(depl)
  107. // FIXME: ignore the status of this API call for now
  108. client.Repositories.CreateDeploymentStatus(
  109. context.Background(), owner, name, depl.GHDeploymentID, &github.DeploymentStatusRequest{
  110. State: github.String("failure"),
  111. Description: github.String("one or more resources failed to build"),
  112. },
  113. )
  114. if !depl.IsBranchDeploy() {
  115. // add a check for the PR to be open before creating a comment
  116. prClosed, err := isGithubPRClosed(client, owner, name, int(depl.PullRequestID))
  117. if err != nil {
  118. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
  119. return
  120. }
  121. if prClosed {
  122. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("github PR has been closed"),
  123. http.StatusConflict))
  124. return
  125. }
  126. workflowRun, err := commonutils.GetLatestWorkflowRun(client, depl.RepoOwner, depl.RepoName,
  127. fmt.Sprintf("porter_%s_env.yml", env.Name), depl.PRBranchFrom)
  128. if err != nil {
  129. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  130. return
  131. }
  132. commentBody := fmt.Sprintf(
  133. "## Porter Preview Environments\n"+
  134. "❌ Errors encountered while deploying the changes\n"+
  135. "||Deployment Information|\n"+
  136. "|-|-|\n"+
  137. "| Latest SHA | [`%s`](https://github.com/%s/%s/commit/%s) |\n"+
  138. "| Build Logs | %s |\n",
  139. depl.CommitSHA, depl.RepoOwner, depl.RepoName, depl.CommitSHA, workflowRun.GetHTMLURL(),
  140. )
  141. if len(request.SuccessfulResources) > 0 {
  142. commentBody += "#### Successfully deployed resources\n"
  143. for _, res := range request.SuccessfulResources {
  144. if res.ReleaseType == "job" {
  145. commentBody += fmt.Sprintf("- [`%s`](%s/jobs/%s/%s/%s?project_id=%d)\n",
  146. res.ReleaseName, c.Config().ServerConf.ServerURL, cluster.Name, depl.Namespace,
  147. res.ReleaseName, project.ID)
  148. } else {
  149. commentBody += fmt.Sprintf("- [`%s`](%s/applications/%s/%s/%s?project_id=%d)\n",
  150. res.ReleaseName, c.Config().ServerConf.ServerURL, cluster.Name, depl.Namespace,
  151. res.ReleaseName, project.ID)
  152. }
  153. }
  154. }
  155. commentBody += "#### Failed resources\n"
  156. for res, err := range request.Errors {
  157. commentBody += fmt.Sprintf("<details>\n <summary><code>%s</code></summary>\n\n **Error:** %s\n</details>\n", res, err)
  158. }
  159. err = createOrUpdateComment(client, c.Repo(), env.NewCommentsDisabled, depl, github.String(commentBody))
  160. if err != nil {
  161. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  162. return
  163. }
  164. }
  165. c.WriteResult(w, r, depl.ToDeploymentType())
  166. }