finalize_deployment.go 7.7 KB

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