create_deployment.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
  38. if !ok {
  39. return
  40. }
  41. request := &types.CreateDeploymentRequest{}
  42. if ok := c.DecodeAndValidate(w, r, request); !ok {
  43. return
  44. }
  45. // read the environment to get the environment id
  46. env, err := c.Repo().Environment().ReadEnvironment(project.ID, cluster.ID, uint(ga.InstallationID), owner, name)
  47. if err != nil {
  48. if errors.Is(err, gorm.ErrRecordNotFound) {
  49. c.HandleAPIError(w, r, apierrors.NewErrNotFound(
  50. fmt.Errorf("error creating deployment: %w", errEnvironmentNotFound)),
  51. )
  52. return
  53. }
  54. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  55. return
  56. }
  57. // create deployment on GitHub API
  58. client, err := getGithubClientFromEnvironment(c.Config(), env)
  59. if err != nil {
  60. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  61. return
  62. }
  63. // add a check for Github PR status
  64. prClosed, err := isGithubPRClosed(client, owner, name, int(request.PullRequestID))
  65. if err != nil {
  66. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
  67. return
  68. }
  69. if prClosed {
  70. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  71. fmt.Errorf("attempting to create deployment for a closed github PR"), http.StatusConflict,
  72. ))
  73. return
  74. }
  75. ghDeployment, err := createGithubDeployment(client, env, request.PRBranchFrom, request.ActionID)
  76. if err != nil {
  77. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusConflict))
  78. return
  79. }
  80. // create the deployment
  81. depl, err := c.Repo().Environment().CreateDeployment(&models.Deployment{
  82. EnvironmentID: env.ID,
  83. Namespace: request.Namespace,
  84. Status: types.DeploymentStatusCreating,
  85. PullRequestID: request.PullRequestID,
  86. GHDeploymentID: ghDeployment.GetID(),
  87. RepoOwner: request.GitHubMetadata.RepoOwner,
  88. RepoName: request.GitHubMetadata.RepoName,
  89. PRName: request.GitHubMetadata.PRName,
  90. CommitSHA: request.GitHubMetadata.CommitSHA,
  91. PRBranchFrom: request.GitHubMetadata.PRBranchFrom,
  92. PRBranchInto: request.GitHubMetadata.PRBranchInto,
  93. })
  94. if err != nil {
  95. // try to delete the GitHub deployment
  96. _, err = client.Repositories.DeleteDeployment(
  97. context.Background(),
  98. env.GitRepoOwner,
  99. env.GitRepoName,
  100. ghDeployment.GetID(),
  101. )
  102. if err != nil {
  103. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("%v: %w", errGithubAPI, err),
  104. http.StatusConflict))
  105. return
  106. }
  107. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error creating deployment: %w", err)))
  108. return
  109. }
  110. c.WriteResult(w, r, depl.ToDeploymentType())
  111. }
  112. func createGithubDeployment(
  113. client *github.Client,
  114. env *models.Environment,
  115. branchFrom string,
  116. actionID uint,
  117. ) (*github.Deployment, error) {
  118. requiredContexts := []string{}
  119. deployment, _, err := client.Repositories.CreateDeployment(
  120. context.Background(),
  121. env.GitRepoOwner,
  122. env.GitRepoName,
  123. &github.DeploymentRequest{
  124. Ref: github.String(branchFrom),
  125. Environment: github.String(env.Name),
  126. AutoMerge: github.Bool(false),
  127. RequiredContexts: &requiredContexts,
  128. },
  129. )
  130. if err != nil {
  131. return nil, fmt.Errorf("%v: %w", errGithubAPI, err)
  132. }
  133. depID := deployment.GetID()
  134. // Create Deployment Status to indicate it's in progress
  135. _, _, err = client.Repositories.CreateDeploymentStatus(
  136. context.Background(),
  137. env.GitRepoOwner,
  138. env.GitRepoName,
  139. depID,
  140. &github.DeploymentStatusRequest{
  141. State: github.String("in_progress"),
  142. LogURL: github.String(fmt.Sprintf("https://github.com/%s/%s/actions/runs/%d",
  143. env.GitRepoOwner, env.GitRepoName, actionID)), // link to actions tab
  144. },
  145. )
  146. if err != nil {
  147. return nil, fmt.Errorf("%v: %w", errGithubAPI, err)
  148. }
  149. return deployment, nil
  150. }