finalize_deployment_with_errors.go 5.2 KB

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