create_deployment.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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: no environment found")),
  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(
  67. fmt.Errorf("error fetching details of github PR. Error: %w", err), http.StatusConflict,
  68. ))
  69. return
  70. }
  71. if prClosed {
  72. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("Github PR has been closed"),
  73. http.StatusConflict))
  74. return
  75. }
  76. ghDeployment, err := createDeployment(client, env, request.PRBranchFrom, request.ActionID)
  77. if err != nil {
  78. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  79. return
  80. }
  81. // create the deployment
  82. depl, err := c.Repo().Environment().CreateDeployment(&models.Deployment{
  83. EnvironmentID: env.ID,
  84. Namespace: request.Namespace,
  85. Status: types.DeploymentStatusCreating,
  86. PullRequestID: request.PullRequestID,
  87. GHDeploymentID: ghDeployment.GetID(),
  88. RepoOwner: request.GitHubMetadata.RepoOwner,
  89. RepoName: request.GitHubMetadata.RepoName,
  90. PRName: request.GitHubMetadata.PRName,
  91. CommitSHA: request.GitHubMetadata.CommitSHA,
  92. PRBranchFrom: request.GitHubMetadata.PRBranchFrom,
  93. PRBranchInto: request.GitHubMetadata.PRBranchInto,
  94. })
  95. if err != nil {
  96. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  97. return
  98. }
  99. // create the backing namespace
  100. agent, err := c.GetAgent(r, cluster, "")
  101. if err != nil {
  102. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  103. return
  104. }
  105. _, err = agent.CreateNamespace(depl.Namespace)
  106. if err != nil {
  107. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  108. return
  109. }
  110. c.WriteResult(w, r, depl.ToDeploymentType())
  111. }
  112. func createDeployment(
  113. client *github.Client,
  114. env *models.Environment,
  115. branchFrom string,
  116. actionID uint,
  117. ) (*github.Deployment, error) {
  118. requiredContexts := []string{}
  119. deploymentRequest := github.DeploymentRequest{
  120. Ref: github.String(branchFrom),
  121. Environment: github.String(env.Name),
  122. AutoMerge: github.Bool(false),
  123. RequiredContexts: &requiredContexts,
  124. }
  125. deployment, _, err := client.Repositories.CreateDeployment(
  126. context.Background(),
  127. env.GitRepoOwner,
  128. env.GitRepoName,
  129. &deploymentRequest,
  130. )
  131. if err != nil {
  132. return nil, err
  133. }
  134. depID := deployment.GetID()
  135. // Create Deployment Status to indicate it's in progress
  136. state := "in_progress"
  137. log_url := fmt.Sprintf("https://github.com/%s/%s/actions/runs/%d", env.GitRepoOwner, env.GitRepoName, actionID)
  138. deploymentStatusRequest := github.DeploymentStatusRequest{
  139. State: &state,
  140. LogURL: &log_url, // link to actions tab
  141. }
  142. _, _, err = client.Repositories.CreateDeploymentStatus(
  143. context.Background(),
  144. env.GitRepoOwner,
  145. env.GitRepoName,
  146. depID,
  147. &deploymentStatusRequest,
  148. )
  149. if err != nil {
  150. return nil, err
  151. }
  152. return deployment, nil
  153. }