finalize_deployment.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package environment
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strings"
  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. "github.com/porter-dev/porter/internal/repository"
  17. )
  18. type FinalizeDeploymentHandler struct {
  19. handlers.PorterHandlerReadWriter
  20. }
  21. func NewFinalizeDeploymentHandler(
  22. config *config.Config,
  23. decoderValidator shared.RequestDecoderValidator,
  24. writer shared.ResultWriter,
  25. ) *FinalizeDeploymentHandler {
  26. return &FinalizeDeploymentHandler{
  27. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  28. }
  29. }
  30. func (c *FinalizeDeploymentHandler) 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.FinalizeDeploymentRequest{}
  39. if ok := c.DecodeAndValidate(w, r, request); !ok {
  40. return
  41. }
  42. // read the environment to get the environment id
  43. env, err := c.Repo().Environment().ReadEnvironment(project.ID, cluster.ID, uint(ga.InstallationID), owner, name)
  44. if err != nil {
  45. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  46. return
  47. }
  48. // read the deployment
  49. depl, err := c.Repo().Environment().ReadDeployment(env.ID, request.Namespace)
  50. if err != nil {
  51. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  52. return
  53. }
  54. depl.Subdomain = request.Subdomain
  55. depl.Status = types.DeploymentStatusCreated
  56. // update the deployment
  57. depl, err = c.Repo().Environment().UpdateDeployment(depl)
  58. if err != nil {
  59. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  60. return
  61. }
  62. client, err := getGithubClientFromEnvironment(c.Config(), env)
  63. if err != nil {
  64. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  65. return
  66. }
  67. // Create new deployment status to indicate deployment is ready
  68. state := "success"
  69. env_url := depl.Subdomain
  70. deploymentStatusRequest := github.DeploymentStatusRequest{
  71. State: &state,
  72. EnvironmentURL: &env_url,
  73. }
  74. _, _, err = client.Repositories.CreateDeploymentStatus(
  75. context.Background(),
  76. env.GitRepoOwner,
  77. env.GitRepoName,
  78. depl.GHDeploymentID,
  79. &deploymentStatusRequest,
  80. )
  81. if err != nil {
  82. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  83. return
  84. }
  85. // add a check for the PR to be open before creating a comment
  86. prClosed, err := isGithubPRClosed(client, owner, name, int(depl.PullRequestID))
  87. if err != nil {
  88. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  89. fmt.Errorf("error fetching details of github PR for deployment ID: %d. Error: %w",
  90. depl.ID, err), http.StatusConflict,
  91. ))
  92. return
  93. }
  94. if prClosed {
  95. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("Github PR has been closed"),
  96. http.StatusConflict))
  97. return
  98. }
  99. commentBody := "## Porter Preview Environments\n"
  100. if depl.Subdomain == "" {
  101. commentBody += fmt.Sprintf(
  102. "✅ The latest SHA ([`%s`](https://github.com/%s/%s/commit/%s)) has been successfully deployed.",
  103. depl.CommitSHA, depl.RepoOwner, depl.RepoName, depl.CommitSHA,
  104. )
  105. } else {
  106. commentBody += fmt.Sprintf(
  107. "✅ The latest SHA ([`%s`](https://github.com/%s/%s/commit/%s)) has been successfully deployed to %s",
  108. depl.CommitSHA, depl.RepoOwner, depl.RepoName, depl.CommitSHA, depl.Subdomain,
  109. )
  110. }
  111. err = createOrUpdateComment(client, c.Repo(), env.NewCommentsDisabled, depl, github.String(commentBody))
  112. if err != nil {
  113. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  114. return
  115. }
  116. c.WriteResult(w, r, depl.ToDeploymentType())
  117. }
  118. func createOrUpdateComment(
  119. client *github.Client,
  120. repo repository.Repository,
  121. newCommentsDisabled bool,
  122. depl *models.Deployment,
  123. commentBody *string,
  124. ) error {
  125. // when updating a PR comment, we have to handle several cases:
  126. // 1. when a Porter environment has deployment status repeat-comments enabled
  127. // - nothing special here, simply create a new comment in the PR
  128. // 2. when a Porter environment has deployment status repeat-comments disabled
  129. // - when a Porter deployment has Github comment ID saved in the DB
  130. // - try to update the comment using the Github comment ID
  131. // - if the above fails, try creating a new comment and save the new comment ID in the DB
  132. // - when a Porter deployment does not have a Github comment ID saved in the DB
  133. // - create a new comment and save the Github comment ID in the DB
  134. if newCommentsDisabled {
  135. if depl.GHPRCommentID == 0 {
  136. // create a new comment
  137. err := createGithubComment(client, repo, depl, commentBody)
  138. if err != nil {
  139. return err
  140. }
  141. } else {
  142. err := updateGithubComment(
  143. client, depl.RepoOwner, depl.RepoName, depl.GHPRCommentID, commentBody,
  144. )
  145. if err != nil {
  146. if strings.Contains(err.Error(), "404") {
  147. // perhaps a deleted comment?
  148. // create a new comment
  149. err := createGithubComment(client, repo, depl, commentBody)
  150. if err != nil {
  151. return fmt.Errorf("invalid github comment ID for deployment with ID: %d. Error creating "+
  152. "new comment: %w", depl.ID, err)
  153. }
  154. }
  155. return err
  156. }
  157. }
  158. } else {
  159. err := createGithubComment(client, repo, depl, commentBody)
  160. if err != nil {
  161. return err
  162. }
  163. }
  164. return nil
  165. }
  166. func createGithubComment(
  167. client *github.Client,
  168. repo repository.Repository,
  169. depl *models.Deployment,
  170. body *string,
  171. ) error {
  172. ghResp, _, err := client.Issues.CreateComment(
  173. context.Background(),
  174. depl.RepoOwner,
  175. depl.RepoName,
  176. int(depl.PullRequestID),
  177. &github.IssueComment{
  178. Body: body,
  179. },
  180. )
  181. if err != nil {
  182. return fmt.Errorf("error creating new github comment for owner: %s repo %s prNumber: %d. Error: %w",
  183. depl.RepoOwner, depl.RepoName, depl.PullRequestID, err)
  184. }
  185. depl.GHPRCommentID = ghResp.GetID()
  186. _, err = repo.Environment().UpdateDeployment(depl)
  187. if err != nil {
  188. return fmt.Errorf("error updating deployment with ID: %d. Error: %w", depl.ID, err)
  189. }
  190. return nil
  191. }
  192. func updateGithubComment(
  193. client *github.Client,
  194. owner, repo string,
  195. commentID int64,
  196. body *string,
  197. ) error {
  198. _, _, err := client.Issues.EditComment(
  199. context.Background(),
  200. owner,
  201. repo,
  202. commentID,
  203. &github.IssueComment{
  204. Body: body,
  205. },
  206. )
  207. return err
  208. }
  209. func isGithubPRClosed(
  210. client *github.Client,
  211. owner, name string,
  212. prNumber int,
  213. ) (bool, error) {
  214. ghPR, _, err := client.PullRequests.Get(
  215. context.Background(), owner, name, prNumber,
  216. )
  217. if err != nil {
  218. return false, fmt.Errorf("%v: %w", errGithubAPI, err)
  219. }
  220. return ghPR.GetState() == "closed", nil
  221. }