create_deployment.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. package environment
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "github.com/google/go-github/v41/github"
  7. "github.com/porter-dev/porter/api/server/authz"
  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. )
  17. type CreateDeploymentHandler struct {
  18. handlers.PorterHandlerReadWriter
  19. authz.KubernetesAgentGetter
  20. }
  21. func NewCreateDeploymentHandler(
  22. config *config.Config,
  23. decoderValidator shared.RequestDecoderValidator,
  24. writer shared.ResultWriter,
  25. ) *CreateDeploymentHandler {
  26. return &CreateDeploymentHandler{
  27. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  28. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  29. }
  30. }
  31. func (c *CreateDeploymentHandler) 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.CreateDeploymentRequest{}
  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. // create deployment on GitHub API
  50. client, err := getGithubClientFromEnvironment(c.Config(), env)
  51. if err != nil {
  52. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  53. return
  54. }
  55. // add a check for Github PR status
  56. prClosed, err := isGithubPRClosed(client, owner, name, int(request.PullRequestID))
  57. if err != nil {
  58. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  59. fmt.Errorf("error fetching details of github PR. Error: %w", err), http.StatusConflict,
  60. ))
  61. return
  62. }
  63. if prClosed {
  64. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("Github PR has been closed"),
  65. http.StatusConflict))
  66. return
  67. }
  68. ghDeployment, err := createDeployment(client, env, request.PRBranchFrom, request.ActionID)
  69. if err != nil {
  70. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  71. return
  72. }
  73. // create the deployment
  74. depl, err := c.Repo().Environment().CreateDeployment(&models.Deployment{
  75. EnvironmentID: env.ID,
  76. Namespace: request.Namespace,
  77. Status: types.DeploymentStatusCreating,
  78. PullRequestID: request.PullRequestID,
  79. GHDeploymentID: ghDeployment.GetID(),
  80. RepoOwner: request.GitHubMetadata.RepoOwner,
  81. RepoName: request.GitHubMetadata.RepoName,
  82. PRName: request.GitHubMetadata.PRName,
  83. CommitSHA: request.GitHubMetadata.CommitSHA,
  84. PRBranchFrom: request.GitHubMetadata.PRBranchFrom,
  85. PRBranchInto: request.GitHubMetadata.PRBranchInto,
  86. })
  87. if err != nil {
  88. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  89. return
  90. }
  91. // create the backing namespace
  92. agent, err := c.GetAgent(r, cluster, "")
  93. if err != nil {
  94. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  95. return
  96. }
  97. _, err = agent.CreateNamespace(depl.Namespace)
  98. if err != nil {
  99. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  100. return
  101. }
  102. c.WriteResult(w, r, depl.ToDeploymentType())
  103. }
  104. func createDeployment(
  105. client *github.Client,
  106. env *models.Environment,
  107. branchFrom string,
  108. actionID uint,
  109. ) (*github.Deployment, error) {
  110. requiredContexts := []string{}
  111. deploymentRequest := github.DeploymentRequest{
  112. Ref: github.String(branchFrom),
  113. Environment: github.String(env.Name),
  114. AutoMerge: github.Bool(false),
  115. RequiredContexts: &requiredContexts,
  116. }
  117. deployment, _, err := client.Repositories.CreateDeployment(
  118. context.Background(),
  119. env.GitRepoOwner,
  120. env.GitRepoName,
  121. &deploymentRequest,
  122. )
  123. if err != nil {
  124. return nil, err
  125. }
  126. depID := deployment.GetID()
  127. // Create Deployment Status to indicate it's in progress
  128. state := "in_progress"
  129. log_url := fmt.Sprintf("https://github.com/%s/%s/actions/runs/%d", env.GitRepoOwner, env.GitRepoName, actionID)
  130. deploymentStatusRequest := github.DeploymentStatusRequest{
  131. State: &state,
  132. LogURL: &log_url, // link to actions tab
  133. }
  134. _, _, err = client.Repositories.CreateDeploymentStatus(
  135. context.Background(),
  136. env.GitRepoOwner,
  137. env.GitRepoName,
  138. depID,
  139. &deploymentStatusRequest,
  140. )
  141. if err != nil {
  142. return nil, err
  143. }
  144. return deployment, nil
  145. }