finalize_deployment.go 8.0 KB

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