finalize_deployment_with_errors.go 5.6 KB

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