finalize_deployment.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. workflowRun, err := commonutils.GetLatestWorkflowRun(client, depl.RepoOwner, depl.RepoName,
  86. fmt.Sprintf("porter_%s_env.yml", env.Name), depl.PRBranchFrom)
  87. if err != nil {
  88. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  89. return
  90. }
  91. if depl.Subdomain == "" {
  92. depl.Subdomain = "*Ingress is disabled for this deployment*"
  93. }
  94. // write comment in PR
  95. commentBody := fmt.Sprintf(
  96. "## Porter Preview Environments\n"+
  97. "✅ All changes deployed successfully\n"+
  98. "||Deployment Information|\n"+
  99. "|-|-|\n"+
  100. "| Latest SHA | [`%s`](https://github.com/%s/%s/commit/%s) |\n"+
  101. "| Live URL | %s |\n"+
  102. "| Build Logs | %s |\n"+
  103. "| Porter Deployments URL | %s/preview-environments/details/%s?environment_id=%d |",
  104. depl.CommitSHA, depl.RepoOwner, depl.RepoName, depl.CommitSHA, depl.Subdomain, workflowRun.GetHTMLURL(),
  105. c.Config().ServerConf.ServerURL, depl.Namespace, depl.EnvironmentID,
  106. )
  107. if len(request.SuccessfulResources) > 0 {
  108. commentBody += "\n#### Successfully deployed resources\n"
  109. for _, res := range request.SuccessfulResources {
  110. if res.ReleaseType == "job" {
  111. commentBody += fmt.Sprintf("- [`%s`](%s/jobs/%s/%s/%s?project_id=%d)\n",
  112. res.ReleaseName, c.Config().ServerConf.ServerURL, cluster.Name, depl.Namespace,
  113. res.ReleaseName, project.ID)
  114. } else {
  115. commentBody += fmt.Sprintf("- [`%s`](%s/applications/%s/%s/%s?project_id=%d)\n",
  116. res.ReleaseName, c.Config().ServerConf.ServerURL, cluster.Name, depl.Namespace,
  117. res.ReleaseName, project.ID)
  118. }
  119. }
  120. }
  121. err = createOrUpdateComment(client, c.Repo(), env.NewCommentsDisabled, depl, github.String(commentBody))
  122. if err != nil {
  123. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  124. return
  125. }
  126. c.WriteResult(w, r, depl.ToDeploymentType())
  127. }
  128. func createOrUpdateComment(
  129. client *github.Client,
  130. repo repository.Repository,
  131. newCommentsDisabled bool,
  132. depl *models.Deployment,
  133. commentBody *string,
  134. ) error {
  135. // when updating a PR comment, we have to handle several cases:
  136. // 1. when a Porter environment has deployment status repeat-comments enabled
  137. // - nothing special here, simply create a new comment in the PR
  138. // 2. when a Porter environment has deployment status repeat-comments disabled
  139. // - when a Porter deployment has Github comment ID saved in the DB
  140. // - try to update the comment using the Github comment ID
  141. // - if the above fails, try creating a new comment and save the new comment ID in the DB
  142. // - when a Porter deployment does not have a Github comment ID saved in the DB
  143. // - create a new comment and save the Github comment ID in the DB
  144. if newCommentsDisabled {
  145. if depl.GHPRCommentID == 0 {
  146. // create a new comment
  147. err := createGithubComment(client, repo, depl, commentBody)
  148. if err != nil {
  149. return err
  150. }
  151. } else {
  152. err := updateGithubComment(
  153. client, depl.RepoOwner, depl.RepoName, depl.GHPRCommentID, commentBody,
  154. )
  155. if err != nil {
  156. if strings.Contains(err.Error(), "404") {
  157. // perhaps a deleted comment?
  158. // create a new comment
  159. err := createGithubComment(client, repo, depl, commentBody)
  160. if err != nil {
  161. return fmt.Errorf("invalid github comment ID for deployment with ID: %d. Error creating "+
  162. "new comment: %w", depl.ID, err)
  163. }
  164. }
  165. return err
  166. }
  167. }
  168. } else {
  169. err := createGithubComment(client, repo, depl, commentBody)
  170. if err != nil {
  171. return err
  172. }
  173. }
  174. return nil
  175. }
  176. func createGithubComment(
  177. client *github.Client,
  178. repo repository.Repository,
  179. depl *models.Deployment,
  180. body *string,
  181. ) error {
  182. ghResp, _, err := client.Issues.CreateComment(
  183. context.Background(),
  184. depl.RepoOwner,
  185. depl.RepoName,
  186. int(depl.PullRequestID),
  187. &github.IssueComment{
  188. Body: body,
  189. },
  190. )
  191. if err != nil {
  192. return fmt.Errorf("error creating new github comment for owner: %s repo %s prNumber: %d. Error: %w",
  193. depl.RepoOwner, depl.RepoName, depl.PullRequestID, err)
  194. }
  195. depl.GHPRCommentID = ghResp.GetID()
  196. _, err = repo.Environment().UpdateDeployment(depl)
  197. if err != nil {
  198. return fmt.Errorf("error updating deployment with ID: %d. Error: %w", depl.ID, err)
  199. }
  200. return nil
  201. }
  202. func updateGithubComment(
  203. client *github.Client,
  204. owner, repo string,
  205. commentID int64,
  206. body *string,
  207. ) error {
  208. _, _, err := client.Issues.EditComment(
  209. context.Background(),
  210. owner,
  211. repo,
  212. commentID,
  213. &github.IssueComment{
  214. Body: body,
  215. },
  216. )
  217. return err
  218. }