finalize_deployment_with_errors.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. if !project.PreviewEnvsEnabled {
  35. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(errPreviewProjectDisabled, http.StatusForbidden))
  36. return
  37. } else if !cluster.PreviewEnvsEnabled {
  38. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(errPreviewClusterDisabled, http.StatusForbidden))
  39. return
  40. }
  41. owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
  42. if !ok {
  43. return
  44. }
  45. request := &types.FinalizeDeploymentWithErrorsRequest{}
  46. if ok := c.DecodeAndValidate(w, r, request); !ok {
  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. // read the environment to get the environment id
  56. env, err := c.Repo().Environment().ReadEnvironment(project.ID, cluster.ID, uint(ga.InstallationID), owner, name)
  57. if err != nil {
  58. if errors.Is(err, gorm.ErrRecordNotFound) {
  59. c.HandleAPIError(w, r, apierrors.NewErrNotFound(fmt.Errorf("environment not found in cluster and project")))
  60. return
  61. }
  62. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  63. return
  64. }
  65. // read the deployment
  66. depl, err := c.Repo().Environment().ReadDeployment(env.ID, request.Namespace)
  67. if err != nil {
  68. if errors.Is(err, gorm.ErrRecordNotFound) {
  69. c.HandleAPIError(w, r, apierrors.NewErrNotFound(fmt.Errorf("no deployment found for environment ID: %d, namespace: %s", env.ID, request.Namespace)))
  70. return
  71. }
  72. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  73. return
  74. }
  75. client, err := getGithubClientFromEnvironment(c.Config(), env)
  76. if err != nil {
  77. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  78. return
  79. }
  80. // add a check for the PR to be open before creating a comment
  81. prClosed, err := isGithubPRClosed(client, owner, name, int(depl.PullRequestID))
  82. if err != nil {
  83. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
  84. return
  85. }
  86. if prClosed {
  87. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("github PR has been closed"),
  88. http.StatusConflict))
  89. return
  90. }
  91. depl.Status = types.DeploymentStatusFailed
  92. // we do not care of the error in this case because the list deployments endpoint
  93. // talks to the github API to fetch the deployment status correctly
  94. c.Repo().Environment().UpdateDeployment(depl)
  95. // FIXME: ignore the status of this API call for now
  96. client.Repositories.CreateDeploymentStatus(
  97. context.Background(), owner, name, depl.GHDeploymentID, &github.DeploymentStatusRequest{
  98. State: github.String("failure"),
  99. Description: github.String("one or more resources failed to build"),
  100. },
  101. )
  102. workflowRun, err := commonutils.GetLatestWorkflowRun(client, depl.RepoOwner, depl.RepoName,
  103. fmt.Sprintf("porter_%s_env.yml", env.Name), depl.PRBranchFrom)
  104. if err != nil {
  105. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  106. return
  107. }
  108. commentBody := fmt.Sprintf(
  109. "## Porter Preview Environments\n"+
  110. "❌ Errors encountered while deploying the changes\n"+
  111. "||Deployment Information|\n"+
  112. "|-|-|\n"+
  113. "| Latest SHA | [`%s`](https://github.com/%s/%s/commit/%s) |\n"+
  114. "| Build Logs | %s |\n",
  115. depl.CommitSHA, depl.RepoOwner, depl.RepoName, depl.CommitSHA, workflowRun.GetHTMLURL(),
  116. )
  117. if len(request.SuccessfulResources) > 0 {
  118. commentBody += "#### Successfully deployed resources\n"
  119. for _, res := range request.SuccessfulResources {
  120. if res.ReleaseType == "job" {
  121. commentBody += fmt.Sprintf("- [`%s`](%s/jobs/%s/%s/%s?project_id=%d)\n",
  122. res.ReleaseName, c.Config().ServerConf.ServerURL, cluster.Name, depl.Namespace,
  123. res.ReleaseName, project.ID)
  124. } else {
  125. commentBody += fmt.Sprintf("- [`%s`](%s/applications/%s/%s/%s?project_id=%d)\n",
  126. res.ReleaseName, c.Config().ServerConf.ServerURL, cluster.Name, depl.Namespace,
  127. res.ReleaseName, project.ID)
  128. }
  129. }
  130. }
  131. commentBody += "#### Failed resources\n"
  132. for res, err := range request.Errors {
  133. commentBody += fmt.Sprintf("<details>\n <summary><code>%s</code></summary>\n\n **Error:** %s\n</details>\n", res, err)
  134. }
  135. err = createOrUpdateComment(client, c.Repo(), env.NewCommentsDisabled, depl, github.String(commentBody))
  136. if err != nil {
  137. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  138. return
  139. }
  140. c.WriteResult(w, r, depl.ToDeploymentType())
  141. }