create_deployment.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. package environment
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "github.com/google/go-github/v41/github"
  8. "github.com/porter-dev/porter/api/server/authz"
  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. "gorm.io/gorm"
  18. )
  19. type CreateDeploymentHandler struct {
  20. handlers.PorterHandlerReadWriter
  21. authz.KubernetesAgentGetter
  22. }
  23. func NewCreateDeploymentHandler(
  24. config *config.Config,
  25. decoderValidator shared.RequestDecoderValidator,
  26. writer shared.ResultWriter,
  27. ) *CreateDeploymentHandler {
  28. return &CreateDeploymentHandler{
  29. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  30. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  31. }
  32. }
  33. func (c *CreateDeploymentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  34. ga, _ := r.Context().Value(types.GitInstallationScope).(*integrations.GithubAppInstallation)
  35. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  36. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  37. if !project.PreviewEnvsEnabled {
  38. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(errPreviewProjectDisabled, http.StatusForbidden))
  39. return
  40. } else if !cluster.PreviewEnvsEnabled {
  41. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(errPreviewClusterDisabled, http.StatusForbidden))
  42. return
  43. }
  44. owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
  45. if !ok {
  46. return
  47. }
  48. request := &types.CreateDeploymentRequest{}
  49. if ok := c.DecodeAndValidate(w, r, request); !ok {
  50. return
  51. }
  52. // read the environment to get the environment id
  53. env, err := c.Repo().Environment().ReadEnvironment(project.ID, cluster.ID, uint(ga.InstallationID), owner, name)
  54. if err != nil {
  55. if errors.Is(err, gorm.ErrRecordNotFound) {
  56. c.HandleAPIError(w, r, apierrors.NewErrNotFound(
  57. fmt.Errorf("error creating deployment: %w", errEnvironmentNotFound)),
  58. )
  59. return
  60. }
  61. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  62. return
  63. }
  64. // create deployment on GitHub API
  65. client, err := getGithubClientFromEnvironment(c.Config(), env)
  66. if err != nil {
  67. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  68. return
  69. }
  70. // add a check for Github PR status
  71. prClosed, err := isGithubPRClosed(client, owner, name, int(request.PullRequestID))
  72. if err != nil {
  73. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
  74. return
  75. }
  76. if prClosed {
  77. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  78. fmt.Errorf("attempting to create deployment for a closed github PR"), http.StatusConflict,
  79. ))
  80. return
  81. }
  82. ghDeployment, err := createGithubDeployment(client, env, request.PRBranchFrom, request.ActionID)
  83. if err != nil {
  84. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
  85. return
  86. }
  87. // create the deployment
  88. depl, err := c.Repo().Environment().CreateDeployment(&models.Deployment{
  89. EnvironmentID: env.ID,
  90. Namespace: request.Namespace,
  91. Status: types.DeploymentStatusCreating,
  92. PullRequestID: request.PullRequestID,
  93. GHDeploymentID: ghDeployment.GetID(),
  94. RepoOwner: request.GitHubMetadata.RepoOwner,
  95. RepoName: request.GitHubMetadata.RepoName,
  96. PRName: request.GitHubMetadata.PRName,
  97. CommitSHA: request.GitHubMetadata.CommitSHA,
  98. PRBranchFrom: request.GitHubMetadata.PRBranchFrom,
  99. PRBranchInto: request.GitHubMetadata.PRBranchInto,
  100. })
  101. if err != nil {
  102. // try to delete the GitHub deployment
  103. _, err = client.Repositories.DeleteDeployment(
  104. context.Background(),
  105. env.GitRepoOwner,
  106. env.GitRepoName,
  107. ghDeployment.GetID(),
  108. )
  109. if err != nil {
  110. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("%v: %w", errGithubAPI, err),
  111. http.StatusConflict))
  112. return
  113. }
  114. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error creating deployment: %w", err)))
  115. return
  116. }
  117. c.WriteResult(w, r, depl.ToDeploymentType())
  118. }
  119. func createGithubDeployment(
  120. client *github.Client,
  121. env *models.Environment,
  122. branchFrom string,
  123. actionID uint,
  124. ) (*github.Deployment, error) {
  125. requiredContexts := []string{}
  126. deployment, _, err := client.Repositories.CreateDeployment(
  127. context.Background(),
  128. env.GitRepoOwner,
  129. env.GitRepoName,
  130. &github.DeploymentRequest{
  131. Ref: github.String(branchFrom),
  132. Environment: github.String(env.Name),
  133. AutoMerge: github.Bool(false),
  134. RequiredContexts: &requiredContexts,
  135. },
  136. )
  137. if err != nil {
  138. return nil, fmt.Errorf("%v: %w", errGithubAPI, err)
  139. }
  140. depID := deployment.GetID()
  141. // Create Deployment Status to indicate it's in progress
  142. _, _, err = client.Repositories.CreateDeploymentStatus(
  143. context.Background(),
  144. env.GitRepoOwner,
  145. env.GitRepoName,
  146. depID,
  147. &github.DeploymentStatusRequest{
  148. State: github.String("in_progress"),
  149. LogURL: github.String(fmt.Sprintf("https://github.com/%s/%s/actions/runs/%d",
  150. env.GitRepoOwner, env.GitRepoName, actionID)), // link to actions tab
  151. },
  152. )
  153. if err != nil {
  154. return nil, fmt.Errorf("%v: %w", errGithubAPI, err)
  155. }
  156. return deployment, nil
  157. }