finalize_deployment.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. depl.LastErrors = ""
  91. // update the deployment
  92. depl, err = c.Repo().Environment().UpdateDeployment(depl)
  93. if err != nil {
  94. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  95. return
  96. }
  97. client, err := getGithubClientFromEnvironment(c.Config(), env)
  98. if err != nil {
  99. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  100. return
  101. }
  102. // Create new deployment status to indicate deployment is ready
  103. state := "success"
  104. env_url := depl.Subdomain
  105. deploymentStatusRequest := github.DeploymentStatusRequest{
  106. State: &state,
  107. EnvironmentURL: &env_url,
  108. }
  109. _, _, err = client.Repositories.CreateDeploymentStatus(
  110. context.Background(),
  111. env.GitRepoOwner,
  112. env.GitRepoName,
  113. depl.GHDeploymentID,
  114. &deploymentStatusRequest,
  115. )
  116. if err != nil {
  117. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  118. return
  119. }
  120. if !depl.IsBranchDeploy() {
  121. // add a check for the PR to be open before creating a comment
  122. prClosed, err := isGithubPRClosed(client, owner, name, int(depl.PullRequestID))
  123. if err != nil {
  124. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  125. fmt.Errorf("error fetching details of github PR for deployment ID: %d. Error: %w",
  126. depl.ID, err), http.StatusConflict,
  127. ))
  128. return
  129. }
  130. if prClosed {
  131. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("Github PR has been closed"),
  132. http.StatusConflict))
  133. return
  134. }
  135. commentBody := "## Porter Preview Environments\n"
  136. if depl.Subdomain == "" {
  137. commentBody += fmt.Sprintf(
  138. "✅ The latest SHA ([`%s`](https://github.com/%s/%s/commit/%s)) has been successfully deployed.",
  139. depl.CommitSHA, depl.RepoOwner, depl.RepoName, depl.CommitSHA,
  140. )
  141. } else {
  142. commentBody += fmt.Sprintf(
  143. "✅ The latest SHA ([`%s`](https://github.com/%s/%s/commit/%s)) has been successfully deployed to %s",
  144. depl.CommitSHA, depl.RepoOwner, depl.RepoName, depl.CommitSHA, depl.Subdomain,
  145. )
  146. }
  147. err = createOrUpdateComment(client, c.Repo(), env.NewCommentsDisabled, depl, github.String(commentBody))
  148. if err != nil {
  149. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  150. return
  151. }
  152. }
  153. c.WriteResult(w, r, depl.ToDeploymentType())
  154. }
  155. func createOrUpdateComment(
  156. client *github.Client,
  157. repo repository.Repository,
  158. newCommentsDisabled bool,
  159. depl *models.Deployment,
  160. commentBody *string,
  161. ) error {
  162. // when updating a PR comment, we have to handle several cases:
  163. // 1. when a Porter environment has deployment status repeat-comments enabled
  164. // - nothing special here, simply create a new comment in the PR
  165. // 2. when a Porter environment has deployment status repeat-comments disabled
  166. // - when a Porter deployment has Github comment ID saved in the DB
  167. // - try to update the comment using the Github comment ID
  168. // - if the above fails, try creating a new comment and save the new comment ID in the DB
  169. // - when a Porter deployment does not have a Github comment ID saved in the DB
  170. // - create a new comment and save the Github comment ID in the DB
  171. if newCommentsDisabled {
  172. if depl.GHPRCommentID == 0 {
  173. // create a new comment
  174. err := createGithubComment(client, repo, depl, commentBody)
  175. if err != nil {
  176. return err
  177. }
  178. } else {
  179. err := updateGithubComment(
  180. client, depl.RepoOwner, depl.RepoName, depl.GHPRCommentID, commentBody,
  181. )
  182. if err != nil {
  183. if strings.Contains(err.Error(), "404") {
  184. // perhaps a deleted comment?
  185. // create a new comment
  186. err := createGithubComment(client, repo, depl, commentBody)
  187. if err != nil {
  188. return fmt.Errorf("invalid github comment ID for deployment with ID: %d. Error creating "+
  189. "new comment: %w", depl.ID, err)
  190. }
  191. }
  192. return err
  193. }
  194. }
  195. } else {
  196. err := createGithubComment(client, repo, depl, commentBody)
  197. if err != nil {
  198. return err
  199. }
  200. }
  201. return nil
  202. }
  203. func createGithubComment(
  204. client *github.Client,
  205. repo repository.Repository,
  206. depl *models.Deployment,
  207. body *string,
  208. ) error {
  209. ghResp, _, err := client.Issues.CreateComment(
  210. context.Background(),
  211. depl.RepoOwner,
  212. depl.RepoName,
  213. int(depl.PullRequestID),
  214. &github.IssueComment{
  215. Body: body,
  216. },
  217. )
  218. if err != nil {
  219. return fmt.Errorf("error creating new github comment for owner: %s repo %s prNumber: %d. Error: %w",
  220. depl.RepoOwner, depl.RepoName, depl.PullRequestID, err)
  221. }
  222. depl.GHPRCommentID = ghResp.GetID()
  223. _, err = repo.Environment().UpdateDeployment(depl)
  224. if err != nil {
  225. return fmt.Errorf("error updating deployment with ID: %d. Error: %w", depl.ID, err)
  226. }
  227. return nil
  228. }
  229. func updateGithubComment(
  230. client *github.Client,
  231. owner, repo string,
  232. commentID int64,
  233. body *string,
  234. ) error {
  235. _, _, err := client.Issues.EditComment(
  236. context.Background(),
  237. owner,
  238. repo,
  239. commentID,
  240. &github.IssueComment{
  241. Body: body,
  242. },
  243. )
  244. return err
  245. }